sol
stringlengths
116
877k
report
stringlengths
298
126k
summary
stringlengths
350
3.62k
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) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } //SWC-Floating Pragma: L2 pragma solidity 0.5.16; import "./DGDInterface.sol"; contract Acid { event Refund(address indexed user, uint256 indexed dgds, uint256 refundAmount); // wei refunded per 0.000000001 DGD burned uint256 public weiPerNanoDGD; bool public isInitialized; address public dgdTokenContract; address public owner; modifier onlyOwner() { require(owner == msg.sender); _; } modifier unlessInitialized() { require(!isInitialized, "contract is already initialized"); _; } modifier requireInitialized() { require(isInitialized, "contract is not initialized"); _; } constructor() public { owner = msg.sender; isInitialized = false; } function () external payable {} function init(uint256 _weiPerNanoDGD, address _dgdTokenContract) public onlyOwner() unlessInitialized() returns (bool _success) { require(_weiPerNanoDGD > 0, "rate cannot be zero"); require(_dgdTokenContract != address(0), "DGD token contract cannot be empty"); weiPerNanoDGD = _weiPerNanoDGD; dgdTokenContract = _dgdTokenContract; isInitialized = true; _success = true; } //SWC-Integer Overflow and Underflow: L47-L59 function burn() public requireInitialized() returns (bool _success) { // Rate will be calculated based on the nearest decimal uint256 _amount = DGDInterface(dgdTokenContract).balanceOf(msg.sender); uint256 _wei = mul(_amount, weiPerNanoDGD); require(address(this).balance >= _wei, "Contract does not have enough funds"); require(DGDInterface(dgdTokenContract).transferFrom(msg.sender, 0x0000000000000000000000000000000000000000, _amount), "No DGDs or DGD account not authorized"); address _user = msg.sender; //SWC-Unchecked Call Return Value: L56 //SWC-DoS with Failed Call: L56 (_success,) = _user.call.value(_wei)(''); require(_success, "Transfer of Ether failed"); emit Refund(_user, _amount, _wei); } 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; } } pragma solidity 0.5.16; contract DGDInterface { string public constant name = "DigixDAO"; string public constant symbol = "DGD"; uint8 public constant decimals = 9; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; uint256 public totalSupply; constructor() public { totalSupply = 2000000000000000; balances[msg.sender] = totalSupply; } function balanceOf(address tokenOwner) public view returns (uint) { return balances[tokenOwner]; } function transfer(address receiver, uint numTokens) public returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender] - numTokens; balances[receiver] = balances[receiver] + numTokens; emit Transfer(msg.sender, receiver, numTokens); return true; } function approve(address delegate, uint numTokens) public returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public view returns (uint) { return allowed[owner][delegate]; } function transferFrom(address owner, address buyer, uint numTokens) public returns (bool _success) { require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner] - numTokens; allowed[owner][msg.sender] = allowed[owner][msg.sender] - numTokens; balances[buyer] = balances[buyer] + numTokens; emit Transfer(owner, buyer, numTokens); _success = true; } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low. (2020-02-10 - Update) 2.b Fix: Increase test coverage. Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk. (2020-02-06 - Update) 3.b Fix: Implement measures to protect user information. Critical Issue 5.a Problem: The issue puts a large number of users’ sensitive information at risk. (2020-01-27 - Initial report) 5.b Fix: Implement measures to protect user information. Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit found 1 critical issue, 3 moderate issues, and 3 minor issues. The project's measured test coverage is Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; import "nodepkg/DoesNotExist.sol"; contract Importer is DoesNotExist { uint local; constructor() public {} }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a large number of users’ sensitive information at risk. It is the responsibility of the Digix team to maintain sufficient balance and implement security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 3 Major: 0 Critical: 0 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues None 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. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; import "nodepkg/LocalNodeImport.sol"; import "nodepkg/NodeImport.sol"; import "ethpmpkg/EthPMImport.sol"; contract Importer is LocalNodeImport, NodeImport, EthPMImport { uint local; constructor() public {} }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a large number of users’ sensitive information at risk. It is the responsibility of the Digix team to maintain sufficient balance and implement security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. The Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.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); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low. (2020-02-10 - Update) 2.b Fix: Increase test coverage. Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk. (2020-02-06 - Update) 3.b Fix: Implement measures to protect user information. Critical Issue 5.a Problem: The issue puts a large number of users’ sensitive information at risk. (2020-01-27 - Initial report) 5.b Fix: Implement measures to protect user information. Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit found 1 critical issue, 3 moderate issues, and 3 minor issues. The project's measured test coverage is Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: The contract is repeatedly initializable. (Acid.sol) 3.b Fix: Check in (L32) that it was not initialized yet. Critical 5.a Problem: Unchecked Return Value (Acid.sol) 5.b Fix: Use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded. Observations - Integer overflow/underflow can cause unexpected behavior and was the core reason for the DAO attack. - It is important to ensure that every necessary function is checked. Conclusion The report found two Moderate and one Critical issue. It is important to ensure that every necessary function is checked and to use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded. Integer overflow/underflow can cause unexpected behavior and was the core reason for the DAO attack.
pragma solidity ^0.5.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); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low. (2020-02-10 - Update) 2.b Fix: Increase test coverage. Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk. (2020-02-06 - Update) 3.b Fix: Implement measures to protect user information. Critical Issue 5.a Problem: The issue puts a large number of users’ sensitive information at risk. (2020-01-27 - Initial report) 5.b Fix: Implement measures to protect user information. Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit found 1 critical issue, 3 moderate issues, and 3 minor issues. The project's measured test coverage is Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: The contract is repeatedly initializable. (Acid.sol) 3.b Fix: Check in (L32) that it was not initialized yet. Critical 5.a Problem: Unchecked Return Value (Acid.sol) 5.b Fix: Use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded. Observations - Integer overflow/underflow can cause unexpected behavior and was the core reason for the DAO attack. - It is important to ensure that every necessary function is checked. Conclusion The report found two Moderate and one Critical issue. It is important to ensure that every necessary function is checked and to use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded. Integer overflow/underflow can cause unexpected behavior and was the core reason for the DAO attack.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract is vulnerable to security risks, and that the test coverage is very low. It is recommended that the project increase its test coverage and implement robust security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations • Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract is vulnerable to security risks, and that the test coverage is very low. It is recommended that the project increase its test coverage and implement robust security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations • Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract is vulnerable to security risks, and that the test coverage is very low. It is recommended that the project increase its test coverage and implement robust security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations • Code review that includes the following: i. Review of the specifications, sources, and instructions provided to Quantstamp to make sure we Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low. (2020-02-10 - Update) 2.b Fix: Increase test coverage. Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk. (2020-02-06 - Update) 3.b Fix: Implement measures to protect user information. Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk. (2020-01-27 - Initial report) 5.b Fix: Implement measures to protect user information. Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit of the DigixDAO Dissolution Contract revealed 1 critical, 3 moderate, and 3 minor issues. The Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low. (2020-02-10 - Update) 2.b Fix: Increase test coverage. Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk. (2020-02-06 - Update) 3.b Fix: Implement measures to protect user information. Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk. (2020-01-27 - Initial report) 5.b Fix: Implement measures to protect user information. Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit of the DigixDAO Dissolution Contract revealed 1 critical, 3 moderate, and 3 minor issues. The Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low. (2020-02-10 - Update) 2.b Fix: Increase test coverage. Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk. (2020-02-06 - Update) 3.b Fix: Implement measures to protect user information. Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk. (2020-01-27 - Initial report) 5.b Fix: Implement measures to protect user information. Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit of the DigixDAO Dissolution Contract revealed 1 critical, 3 moderate, and 3 minor issues. The Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.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; contract Example { string public id = 'Example'; constructor() public {} }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit of the DigixDAO Dissolution Contract revealed one critical issue, three moderate issues, and three minor issues. The project's measured test coverage is very low, and it fails to meet Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. The Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Critical 5.a Problem: Unchecked Return Value in Acid.sol 5.b Fix: Require(success, "Transfer of Ether failed") Moderate 3.a Problem: Contract is Repeatedly Initializable in Acid.sol 3.b Fix: Add init 3.a Problem: Integer Overflow/Underflow in Acid.sol 3.b Fix: BatchOverflow Observations - The tools used for the assessment were Truffle, Ganache, SolidityCoverage, and Slither. - The assessment found 1 Critical issue, 2 Moderate issues, and 0 Minor/Major issues. Conclusion The assessment found 1 Critical issue, 2 Moderate issues, and 0 Minor/Major issues. The Critical issue was an Unchecked Return Value in Acid.sol, which was fixed by requiring(success, "Transfer of Ether failed"). The Moderate issues were a Contract that was Repeatedly Initializable in Acid.sol, which was fixed by adding init, and an Integer Overflow/Underflow
pragma solidity ^0.5.0; contract Abstract { function method() public; } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } } pragma solidity ^0.5.0; contract RevertWithReason { string public id = 'RevertWithReason'; constructor() public { require(false, 'reasonstring'); } } pragma solidity ^0.5.0; contract ExampleRevert { constructor() public { require(false); } } pragma solidity ^0.5.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; contract ExampleAssert { constructor() public { assert(false); } } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem (one line with code reference): Unchecked return value in the function `burn` (DGDInterface.sol#L90) 2.b Fix (one line with code reference): Check the return value of the `burn` function (DGDInterface.sol#L90) Moderate Issues 3.a Problem (one line with code reference): Unchecked return value in the function `burn` (DGDInterface.sol#L90) 3.b Fix (one line with code reference): Check the return value of the `burn` function (DGDInterface.sol#L90) Major Issues None Critical Issues 5.a Problem (one line with code reference): Unchecked return value in the function `burn` (DGDInterface.sol#L90) 5.b Fix (one line with code reference): Check the return value of the `burn` function (DGDInterface.sol#L90) Observations - The purpose of the smart Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. The Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Critical 5.a Problem: Unchecked Return Value in Acid.sol 5.b Fix: Require(success, "Transfer of Ether failed") Moderate 3.a Problem: Contract is repeatedly initializable in Acid.sol 3.b Fix: Add init 3.a Problem: Integer Overflow/Underflow in Acid.sol 3.b Fix: batchOverflow Observations - The tools used for the assessment were Truffle, Ganache, SolidityCoverage, and Slither. - Steps were taken to install and run the tools. Conclusion The assessment found one critical issue, two moderate issues, and no minor or major issues. The critical issue was an unchecked return value in Acid.sol, which was fixed by requiring success. The two moderate issues were a contract that was repeatedly initializable in Acid.sol, which was fixed by adding init, and an integer overflow/underflow in Acid.sol, which was fixed by batchOverflow.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a subset of users’ sensitive information at risk. The audit also found that the issue put a large number of users’ sensitive information at risk. The audit concluded that the smart contract should implement robust security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 3 Major: 0 Critical: 0 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues None 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. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a subset of users’ sensitive information at risk. The audit also found that the issue put a large number of users’ sensitive information at risk. The audit concluded that the smart contract should implement robust security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 3 Major: 0 Critical: 0 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues None 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. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; library IsLibrary { string constant public id = 'IsLibrary'; event IsLibraryEvent(uint eventID); function fireIsLibraryEvent(uint _id) public { emit IsLibraryEvent(_id); } } pragma solidity ^0.5.0; import "./IsLibrary.sol"; contract UsesLibrary { event UsesLibraryEvent(uint eventID); constructor() public {} function fireIsLibraryEvent(uint id) public { IsLibrary.fireIsLibraryEvent(id); } function fireUsesLibraryEvent(uint id) public { emit UsesLibraryEvent(id); } } pragma solidity ^0.5.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; contract PayableExample { string public id = 'PayableExample'; constructor() public payable {} } pragma solidity ^0.5.0; contract UsesExample { string public id = 'UsesExample'; address public other; constructor(address _other) public { other = _other; } } pragma solidity ^0.5.0; contract Example { string public id = 'Example'; constructor() public {} } pragma solidity ^0.5.0; contract Loops { uint public id; constructor() public { for(uint i = 0; i < 10000; i++){ id = i; } } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a subset of users’ sensitive information at risk. The audit also found that the issue put a large number of users’ sensitive information at risk. The audit concluded that the smart contract should implement robust security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 3 Major: 0 Critical: 0 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues None 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. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.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); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a large number of users’ sensitive information at risk. It is the responsibility of the Digix team to maintain sufficient balance and implement security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that the range of integers is not exceeded Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, Slither and MAIAN - The assessment found 1 critical issue, 2 moderate issues and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable. It is also important to ensure that the range of integers is not exceeded.
pragma solidity ^0.5.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); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a large number of users’ sensitive information at risk. It is the responsibility of the Digix team to maintain sufficient balance and implement security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that the range of integers is not exceeded Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, Slither and MAIAN - The assessment found 1 critical issue, 2 moderate issues and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable. It is also important to ensure that the range of integers is not exceeded.
pragma solidity ^0.5.0; 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); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract does not contain any automated Ether replenishing features and that the project's measured test coverage is very low. The audit also found that the issue puts a large number of users’ sensitive information at risk and that the file in the repository was out-of-scope and is Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. The Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that the range of integers is not passed Observations - The tools used for the assessment were Maian, Truffle, Ganache, SolidityCoverage and Slither - Steps taken to run the tools were installing Truffle, Ganache, SolidityCoverage, cloning the MAIAN tool, running the MAIAN tool, installing the Slither tool and running Slither Conclusion The assessment of the code revealed one critical issue and two moderate issues. The critical issue was an integer overflow/underflow in Acid.sol (Line 42). The two
pragma solidity ^0.5.0; contract Local { uint local; constructor() public { } } pragma solidity ^0.5.0; import "tokens/eip20/EIP20.sol"; import "./Local.sol"; contract PLCRVoting is EIP20, Local { function isExpired(uint _terminationDate) view public returns (bool expired) { return (block.timestamp > _terminationDate); } function attrUUID(address _user, uint _pollID) public pure returns (bytes32 UUID) { return keccak256(_user, _pollID); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a large number of users’ sensitive information at risk. It is the responsibility of the Digix team to maintain sufficient balance and implement security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: The contract is repeatedly initializable. (Acid.sol) 3.b Fix: Check in (L32) that it was not initialized yet. Critical 5.a Problem: Unchecked Return Value (Acid.sol) 5.b Fix: Use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded. Observations - Integer overflow/underflow can cause unexpected behavior and was the core reason for the DAO attack. - It is important to ensure that every necessary function is checked. Conclusion The audit found two Moderate and one Critical issue. It is important to ensure that every necessary function is checked and to use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded.
pragma solidity ^0.5.0; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); constructor() public { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) public returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; emit Transfer(msg.sender, receiver, amount); return true; } function getBalanceInEth(address addr) public view returns(uint){ return ConvertLib.convert(getBalance(addr),2); } function getBalance(address addr) public view returns(uint) { return balances[addr]; } } pragma solidity ^0.5.0; library ConvertLib{ function convert(uint amount,uint conversionRate) public pure returns (uint convertedAmount) { return amount * conversionRate; } } pragma solidity ^0.5.0; 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); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a large number of users’ sensitive information at risk. It is the responsibility of the Digix team to maintain sufficient balance and implement security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 3 Major: 0 Critical: 0 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues None 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. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, Slither and MAIAN - The assessment found 1 critical, 2 moderate and 0 minor and major issues Conclusion The assessment found 1 critical, 2 moderate and 0 minor and major issues in the Acid.sol contract. The tools used for the assessment were Truffle, Ganache, Solidity Coverage, Slither and MAIAN.
pragma solidity >=0.4.25 <0.6.0; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. If you want to create a standards-compliant // token, see: https://github.com/ConsenSys/Tokens. Cheers! contract MetaCoin { mapping (address => uint) balances; event Transfer(address indexed _from, address indexed _to, uint256 _value); constructor() public { balances[tx.origin] = 10000; } function sendCoin(address receiver, uint amount) public returns(bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; emit Transfer(msg.sender, receiver, amount); return true; } function getBalanceInEth(address addr) public view returns(uint){ return ConvertLib.convert(getBalance(addr),2); } function getBalance(address addr) public view returns(uint) { return balances[addr]; } } pragma solidity >=0.4.25 <0.6.0; library ConvertLib{ function convert(uint amount,uint conversionRate) public pure returns (uint convertedAmount) { return amount * conversionRate; } } pragma solidity >=0.4.25 <0.6.0; 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); } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. - The smart contract does not contain any automated Ether replenishing features. - The file in the repository was out-of-scope and is therefore not included in this report. Conclusion The audit of the DigixDAO Dissolution Contract revealed one critical issue, three moderate issues, and three minor issues. The project's measured test coverage is very low, and it fails to meet Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; import "./LeafC.sol"; contract LeafA is LeafC { uint leafA; } pragma solidity ^0.5.0; import "./LeafC.sol"; contract LeafB is LeafC { uint leafB; } pragma solidity ^0.5.0; contract LeafC { uint leafC; } pragma solidity ^0.5.0; 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) restricted public { last_completed_migration = completed; } function upgrade(address new_address) restricted public { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.5.0; import "./LeafC.sol"; contract SameFile1 is LeafC { uint samefile1; } contract SameFile2 { uint samefile2; } pragma solidity ^0.5.0; import "./Branch.sol"; import "./LeafC.sol"; import "./LibraryA.sol"; contract Root is Branch { uint root; function addToRoot(uint a, uint b) public { root = LibraryA.add(a, b); } } pragma solidity ^0.5.0; library LibraryA { function add(uint a, uint b) public pure returns (uint) { return a + b; } } pragma solidity ^0.5.0; import "./LeafA.sol"; import "./LeafB.sol"; contract Branch is LeafA, LeafB { uint branch; }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract does not contain any automated Ether replenishing features and that the project's measured test coverage is very low. The audit also found that the issue puts a large number of users’ sensitive information at risk and that the file in the repository was out-of-scope and is Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
pragma solidity ^0.5.0; contract Executable { uint public x; constructor() public { x = 5; } }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract had a low test coverage and put a large number of users’ sensitive information at risk. It is the responsibility of the Digix team to maintain sufficient balance and implement security measures to protect user information. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations Quantstamp's objective was to evaluate the repository for security-related issues, code quality, and adherence to specification and best practices. Possible Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: The contract is repeatedly initializable. (Acid.sol) 3.b Fix: Check in (L32) that it was not initialized yet. Critical 5.a Problem: Unchecked Return Value (Acid.sol) 5.b Fix: Use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded. Observations - Integer overflow/underflow can cause unexpected behavior and was the core reason for the DAO attack. - It is important to ensure that every necessary function is checked. Conclusion The report found two Moderate and one Critical issue. It is important to ensure that every necessary function is checked and to use require(success, "Transfer of Ether failed") to enforce that the transaction succeeded. Integer overflow/underflow can cause unexpected behavior and was the core reason for the DAO attack.
pragma solidity ^0.5.0; import "./contract.sol"; contract RelativeImport is Contract { } pragma solidity ^0.5.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; // This file defines a library that can be used as well. library InnerLibrary { } // This name doesn't match its filename. contract Contract { uint public specialValue = 1337; }
February 20th 2020— Quantstamp Verified Acid - DigixDAO Dissolution Contract This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type ERC20 Token Auditors Jan Gorzny , Blockchain ResearcherLeonardo Passos , Senior Research EngineerMartin Derka , Senior Research EngineerTimeline 2020-01-23 through 2020-02-10 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Source Code Repository Commit acid-solidity 8b43815 Changelog 2020-01-27 - Initial report [ ] • 349a30f 2020-02-04 - Update [ ] • ab4629b 2020-02-06 - Update [ ] • e95e000 2020-02-10 - Update [ ] • 8b43815 Overall Assessment The purpose of the smart contract is to burn DGD tokens and exchange them for Ether. The smart contract does not contain any automated Ether replenishing features, so it is the responsibility of the Digix team to maintain sufficient balance. If the Ether balance of the contract is not sufficient to cover the refund requested in a burn transaction, such a transaction will fail. The project's measured test coverage is very low, and it fails to meet many best practices. Finally, note that the file in the repository was out-of- scope and is therefore not included in this report. DGDInterface.solTotal Issues7 (7 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 3 (3 Resolved)Low Risk Issues 3 (3 Resolved)Informational Risk Issues 0 (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. Summary of Findings ID Description Severity Status QSP- 1 Unchecked Return Value High Resolved QSP- 2 Repeatedly Initializable Medium Resolved QSP- 3 Integer Overflow / Underflow Medium Resolved QSP- 4 Gas Usage / Loop Concerns forMedium Resolved QSP- 5 Unlocked Pragma Low Resolved QSP- 6 Race Conditions / Front-Running Low Resolved QSP- 7 Unchecked Parameter Low Resolved 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 followingi. 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 theestablished 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: • Maian• Truffle• Ganache• SolidityCoverage• 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. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 6. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 7. Installed the Slither tool:pip install slither-analyzer 8. Run Slither from the project directoryslither . Assessment Findings QSP-1 Unchecked Return Value Severity: High Risk Resolved Status: File(s) affected: Acid.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. Line 53 of transfers Ether using . If the transfer fails, this method does not revert the transaction. Instead, it returns . The check for the return value is not present in the code. Description:true falsesend() Acid.sol address.call.value() false It is possible that a user calls , their DGD is burned, an attempt to send Ether to them is made, but they do not receive it and they also lose their DGD tokens. Event is then emitted in any case. The method can fail for many reasons, e.g., the sender is a smart contract unable to receive Ether, or the execution runs out of gas (refer also to QSP-3). Exploit Scenario:burn() Refund() address.call.value() Use to enforce that the transaction succeeded. Recommendation: require(success, "Transfer of Ether failed") QSP-2 Repeatedly Initializable Severity: Medium Risk Resolved Status: File(s) affected: Acid.sol The contract is repeatedly initializable. Description: The contract should check in (L32) that it was not initialized yet. Recommendation: init QSP-3 Integer Overflow / Underflow Severity: Medium Risk Resolved Status: File(s) affected: Acid.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 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 } } Overflow is possible on line 42 in . There may be other locations where this is present. As a concrete example, Exploit Scenario: Acid.sol Say Bob has tokens and that is and assume thecontract has enough funds. Bob wants to convert his tokens to wei, and as such calls . The wei amount that Bob should get back is , but effectively, due to the overflow on line 42, he will get zero. 2^255weiPerNanoDGD 2 Acid burn() 2^256 wei Use the library anytime arithmetic is involved. Recommendation: SafeMath QSP-4 Gas Usage / Loop Concerns forSeverity: Medium Risk Resolved Status: File(s) affected: Acid.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 Line 46 hard codes gas transfer. The gas should be left as provided by the caller. Recommendation: QSP-5 Unlocked Pragma Severity: Low Risk Resolved Status: File(s) affected: Acid.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." 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. Description:pragma solidity (^)0.4.* ^ and above QSP-6 Race Conditions / Front-Running Severity: Low Risk Resolved Status: File(s) affected: Acid.sol A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:Depending on the construction method, there can be a race for initialization even after the other related issues are addressed. Exploit Scenario: QSP-7 Unchecked Parameter Severity: Low Risk Resolved Status: File(s) affected: Acid.sol The address as input for the function is never checked to be non-zero in . Description: init Acid.sol Check that the parameters are non-zero when the function is called. Recommendation: Automated Analyses Slither Slither detected that the following functions and , should be declared external. Other minor issues reported by Slither are noted elsewhere in this report. Acid.initAcid.burn Adherence to Best Practices The following could be improved: In , the zero address on line 44 would better be . resolved. • Acid.soladdress(0) Update: In , the Open Zeppelin library could be imported and used. • Acid.solOwner In , the modifier should be named as it is a modifier. resolved. • Acid.solisOwner onlyOwner Update: In , lines 16, 21, and 44: error messages should be provided for require statements. resolved. • Acid.solUpdate: In , lines 6 and 30 contain unnecessary trailing white space which should be removed. resolved. • Acid.solUpdate: In , the error message exceeds max length of 76 characters on line 76. • Acid.solIn , there should be ownerOnly setters for weiPerNanoDGD and dgdTokenContract. Setters allow updating these fields without redeploying a new contract. •Acid.solIn , on line 49, the visibility modifier "public" should come before other modifiers. resolved. • Acid.solUpdate: The library is never used; it could be removed. resolved. • ConvertLib.sol Update: All public and external functions should be documented to help ensure proper usage. •In , there are unlocked dependency versions. • package.jsonTest Results Test Suite Results You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project You can improve web3's peformance when running Node.js versions older than 10.5.0 by installing the (deprecated) scrypt package in your project Using network 'development'. Compiling your contracts... =========================== > Compiling ./contracts/Acid.sol > Compiling ./contracts/ConvertLib.sol > Compiling ./contracts/DGDInterface.sol > Compiling ./contracts/Migrations.sol > Compiling ./test/TestAcid.sol > Compiling ./test/TestDGDInterface.sol TestAcid ✓ testInitializationAfterDeployment (180ms) ✓ testOwnerAfterDeployment (130ms) ✓ testDGDTokenContractAfterDeployment (92ms) ✓ testWeiPerNanoDGDAfterDeployment (91ms) TestDGDInterface ✓ testInitialBalanceUsingDeployedContract (82ms) Contract: Acid ✓ should throw an error when calling burn() on an uninitialized contract (68ms) ✓ should not allow anyone but the owner to initialize the contract (81ms) ✓ should allow the owner to initialize the contract (144ms) ✓ should not allow burn if the contract is not funded (359ms) ✓ should allow itself to be funded with ETH (57ms) ✓ should allow a user to burn some DGDs and receive ETH (350ms) Accounting Report User DGD Balance Before: 1999999999999998 User DGD Balance After: 0 Contract ETH before: 386248.576296155363751424 Contract ETH Balance After: 0.00029615575 User ETH Balance Before: 999613751.38267632425 User ETH Balance After: 999999999.957861683863751424 ✓ should allow a user to burn the remaining DGDs in supply (215ms) Contract: DGDInterface ✓ should put 10000 DGDInterface in the first account ✓ should send coin correctly (167ms) 14 passing (16s) Code Coverage The test coverage measured by is very low. It is recommended to add additional tests to this project. solcoverFile % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 9.3 0 14.29 8.7 Acid.sol 8.33 0 12.5 7.41 … 63,65,66,68 DGDInterface.sol 10.53 0 16.67 10.53 … 50,51,52,53 All files 9.3 0 14.29 8.7 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 8154c170ce50b4b91b24656e5361d79f1c6d922026c516edda44ff97ccea8b92 ./contracts/Acid.sol 3cec1b0e8207ef51b8e918391f7fdc43f1aeeb144e212407a307f3f55b5dfa0b ./contracts/Migrations.sol Tests 2d7bf77a2960f5f3065d1b7860f2c3f98e20166f53140aa766b935112ae20ddf ./test/acid.js 8ec457f4fab9bd91daeb8884101bca2bd34cdcdb8d772a20ea618e8c8616dfa3 ./test/dgdinterface.js 8d0caeea4c848c5a02bac056282cef1c36c04cfb2ad755336b3d99b584c24940 ./test/TestAcid.sol f745f2ded6e7e3329f7349237fcbf94c952ad4a279c943f540ea100669efab61 ./test/TestDGDInterface.sol About Quantstamp 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. 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. Acid - DigixDAO Dissolution Contract Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 1 Minor Issues 2.a Problem: The project's measured test coverage is very low (Quantstamp) 2.b Fix: Increase test coverage Moderate Issues 3.a Problem: The issue puts a subset of users’ sensitive information at risk (Quantstamp) 3.b Fix: Implement security measures to protect user information Critical 5.a Problem: The issue puts a large number of users’ sensitive information at risk (Quantstamp) 5.b Fix: Implement robust security measures to protect user information Observations - The smart contract does not contain any automated Ether replenishing features - The file in the repository was out-of-scope and is therefore not included in this report Conclusion The audit found that the smart contract does not contain any automated Ether replenishing features and that the project's measured test coverage is very low. The audit also found that the issue puts a large number of users’ sensitive information at risk and that the file in the repository was out-of-scope and is Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 2 Major: 0 Critical: 3 Minor Issues 2.a Problem: Unchecked Return Value 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues 3.a Problem: Repeatedly Initializable 3.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 4.a Problem: Integer Overflow / Underflow 4.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Critical Issues 5.a Problem: Gas Usage / Loop Concerns 5.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 6.a Problem: Unlocked Pragma 6.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. 7.a Problem: Race Conditions / Front-Running 7.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations The Quantstamp auditing process follows a routine series of steps: 1. Code review that includes the following: i. Review of the specifications, sources Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 2 - Major: 0 - Critical: 1 Moderate 3.a Problem: Unchecked Return Value in Acid.sol (Line 53) 3.b Fix: Require a check for the return value 4.a Problem: Repeatedly Initializable in Acid.sol 4.b Fix: Check in Acid.sol (Line 32) that it was not initialized yet Critical 5.a Problem: Integer Overflow/Underflow in Acid.sol (Line 42) 5.b Fix: Ensure that integer overflow/underflow is not possible Observations - The tools used for the assessment were Truffle, Ganache, Solidity Coverage, and Slither - The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues Conclusion The assessment found 1 critical issue, 2 moderate issues, and 0 minor/major issues. It is important to ensure that the return value is checked and that the contract is not repeatedly initializable, as well as to ensure that integer overflow/underflow is not possible.
/** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { if (_upperBound == 0) { return 0; } uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } }/** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; import "./MCDAwarePool.sol"; import "scd-mcd-migration/src/ScdMcdMigration.sol"; /** * @title Pool * @author Brendan Asselstine * @notice The mainnet Pool contract that implements functions bound to mainnet addresses. */ contract Pool is MCDAwarePool { /** * @notice Function that returns the address of the Maker ScdMcdMigration contract on mainnet * @return The ScdMcdMigration contract address on mainnet */ function scdMcdMigration() public view returns (ScdMcdMigration) { return ScdMcdMigration(0xc73e0383F3Aff3215E6f04B0331D58CeCf0Ab849); } /** * @notice Function that returns the address of the PoolTogether Sai Pool contract on mainnet * @return The Sai Pool contract address on mainnet */ function saiPool() public view returns (MCDAwarePool) { return MCDAwarePool(0xb7896fce748396EcFC240F5a0d3Cc92ca42D7d84); } }/** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ // Migrations.sol pragma solidity 0.5.12; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; contract Migrations is Ownable { uint public last_completed_migration; function setCompleted(uint completed) public onlyOwner { last_completed_migration = completed; } function upgrade(address new_address) public onlyOwner { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; import "./ERC777Pool.sol"; contract RecipientWhitelistERC777Pool is ERC777Pool { //SWC-State Variable Default Visibility: L25-L26 bool _recipientWhitelistEnabled; mapping(address => bool) _recipientWhitelist; function recipientWhitelistEnabled() public view returns (bool) { return _recipientWhitelistEnabled; } function recipientWhitelisted(address _recipient) public view returns (bool) { return _recipientWhitelist[_recipient]; } function setRecipientWhitelistEnabled(bool _enabled) public onlyAdmin { _recipientWhitelistEnabled = _enabled; } function setRecipientWhitelisted(address _recipient, bool _whitelisted) public onlyAdmin { _recipientWhitelist[_recipient] = _whitelisted; } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address. Can only be whitelisted addresses, if any * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { if (_recipientWhitelistEnabled) { require(to == address(0) || _recipientWhitelist[to], "recipient is not whitelisted"); } address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; import "./UniformRandomNumber.sol"; import "@kleros/kleros/contracts/data-structures/SortitionSumTreeFactory.sol"; import "@openzeppelin/contracts/contracts/math/SafeMath.sol"; /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_LEAVES = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the first Draw index that an address deposited to. */ mapping(address => uint256) usersFirstDrawIndex; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) usersSecondDrawIndex; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (self.openDrawIndex == 0) { // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_LEAVES); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_LEAVES); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; // if this is the users first draw, set it if (firstDrawIndex == 0) { self.usersFirstDrawIndex[_addr] = openDrawIndex; // otherwise, if the first draw is not this draw } else if (firstDrawIndex != openDrawIndex) { // if a second draw does not exist if (secondDrawIndex == 0) { // set the second draw to the current draw self.usersSecondDrawIndex[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (secondDrawIndex != openDrawIndex) { // merge it into the first draw, and update the second draw index to this one uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); uint256 secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(secondAmount), _addr); drawSet(self, secondDrawIndex, 0, _addr); self.usersSecondDrawIndex[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; // if they have a committed balance if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { uint256 firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); drawSet(self, firstDrawIndex, firstAmount.add(_amount), _addr); } else { // they must not have any committed balance self.usersSecondDrawIndex[_addr] = firstDrawIndex; self.usersFirstDrawIndex[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.usersFirstDrawIndex[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (firstDrawIndex != 0) { drawSet(self, firstDrawIndex, 0, _addr); delete self.usersFirstDrawIndex[_addr]; } if (secondDrawIndex != 0) { drawSet(self, secondDrawIndex, 0, _addr); delete self.usersSecondDrawIndex[_addr]; } } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; uint256 firstAmount = 0; uint256 secondAmount = 0; uint256 total = 0; if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { secondAmount = self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), userId); total = total.add(secondAmount); } if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { firstAmount = self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), userId); total = total.add(firstAmount); } require(_amount <= total, "cannot withdraw more than available"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (remaining > firstAmount) { uint256 secondRemaining = remaining.sub(firstAmount); drawSet(self, secondDrawIndex, secondRemaining, _addr); } else if (secondAmount > 0) { // else delete the second amount if it exists delete self.usersSecondDrawIndex[_addr]; drawSet(self, secondDrawIndex, 0, _addr); } // if the first amount needs to be destroyed if (remaining == 0) { delete self.usersFirstDrawIndex[_addr]; drawSet(self, firstDrawIndex, 0, _addr); } else if (remaining < firstAmount) { drawSet(self, firstDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 firstDrawIndex = self.usersFirstDrawIndex[_addr]; uint256 secondDrawIndex = self.usersSecondDrawIndex[_addr]; if (firstDrawIndex != 0 && firstDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(firstDrawIndex), bytes32(uint256(_addr)))); } if (secondDrawIndex != 0 && secondDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(secondDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (self.openDrawIndex == 0) { return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (oldAmount != _amount) { // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // if the draw is committed if (_drawIndex != self.openDrawIndex) { // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (committedSupply(self) == 0) { return address(0); } require(_token < committedSupply(self), "token is beyond the eligible supply"); uint256 drawIndex = uint256(self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token)); uint256 drawSupply = self.sortitionSumTrees.total(bytes32(drawIndex)); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(bytes32(drawIndex), drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { return draw(self, UniformRandomNumber.uniform(uint256(_entropy), committedSupply(self))); } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "there is no open draw"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "address cannot be zero"); _; } }/** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; import "./RecipientWhitelistERC777Pool.sol"; import "scd-mcd-migration/src/ScdMcdMigration.sol"; import { GemLike } from "scd-mcd-migration/src/Interfaces.sol"; /** * @title MCDAwarePool * @author Brendan Asselstine brendan@pooltogether.us * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is RecipientWhitelistERC777Pool, IERC777Recipient { /** * @notice Returns the address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ function scdMcdMigration() public view returns (ScdMcdMigration); /** * @notice Returns the address of the Sai Pool contract */ function saiPool() public view returns (MCDAwarePool); /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee * @param name The name of the Pool ticket tokens * @param symbol The symbol (short name) of the Pool ticket tokens * @param defaultOperators Addresses that should always be able to move tokens on behalf of others */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, string memory name, string memory symbol, address[] memory defaultOperators ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, name, symbol, defaultOperators ); initMCDAwarePool(); } /** * @notice Used to initialze the BasePool contract after an upgrade. * @param name Name of the token * @param symbol Symbol of the token * @param defaultOperators The initial set of operators for all users */ function initBasePoolUpgrade( string memory name, string memory symbol, address[] memory defaultOperators ) public { initERC777(name, symbol, defaultOperators); initMCDAwarePool(); } /** * @notice Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens */ function initMCDAwarePool() public { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external { require(msg.sender == address(saiPool()), "can only receive tokens from Sai Pool"); require(address(token()) == address(daiToken()), "contract does not use Dai"); // cash out of the Pool. This call transfers sai to this contract saiPool().burn(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration()), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration().swapSaiToDai(amount); if (currentCommittedDrawId() > 0) { // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } function saiToken() internal returns (GemLike) { return scdMcdMigration().saiJoin().gem(); } function daiToken() internal returns (GemLike) { return scdMcdMigration().daiJoin().dai(); } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; import "./BasePool.sol"; import "@openzeppelin/contracts/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts/contracts/utils/Address.sol"; /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract ERC777Pool is IERC20, IERC777, BasePool { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, string memory name, string memory symbol, address[] memory defaultOperators ) public initializer { init(_owner, _cToken, _feeFraction, _feeBeneficiary); initERC777(name, symbol, defaultOperators); } /** * @dev `defaultOperators` may be an empty array. */ function initERC777 ( string memory name, string memory symbol, address[] memory defaultOperators ) public { require(bytes(name).length != 0, "name must be defined"); require(bytes(symbol).length != 0, "symbol must be defined"); require(bytes(_name).length == 0, "ERC777 has already been initialized"); _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return committedSupply(); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes calldata data) external { _burn(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "ERC777: caller is not an operator for holder"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "ERC777: caller is not an operator for holder"); _burn(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @notice Commits the current draw. Mints the open supply number of tokens. * @dev This function deviates from the ERC 777 spec (https://eips.ethereum.org/EIPS/eip-777). The spec * says that: * - "The balance of the recipient MUST be increased by the amount of tokens minted." * However, for this contract it is not feasible to emit Minted for every open deposit. */ function emitCommitted() internal { super.emitCommitted(); uint256 mintingAmount = openSupply(); _mintEvents(address(this), address(this), mintingAmount, '', ''); } /** * @notice Awards the winnings to a user. Ensures that the Minted event is fired */ function awardWinnings(address winner, uint256 amount) internal { super.awardWinnings(winner, amount); _mint(address(this), winner, amount, '', ''); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); _mintEvents(operator, account, amount, userData, operatorData); } function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, true); } /** * @dev Burn tokens * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "ERC777: burn from the zero address"); uint256 committedBalance = drawState.committedBalanceOf(from); require(amount <= committedBalance, "not enough funds"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables drawState.withdrawCommitted(from, amount); _withdraw(from, amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { balances[from] = balances[from].sub(amount, "move could not sub amount"); balances[to] = balances[to].add(amount); drawState.withdrawCommitted(from, amount); drawState.depositCommitted(to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: contract recipient has no implementer for ERC777TokensRecipient"); } } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; import "@openzeppelin/contracts/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol"; import "./compound/ICErc20.sol"; import "./DrawManager.sol"; import "fixidity/contracts/FixidityLib.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; bytes32 private constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event Paused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event Unpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State drawState; /** * A structure containing the administrators */ Roles.Role admins; /** * Whether the contract is paused */ bool public paused; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary ) public initializer { require(_owner != address(0), "owner cannot be the null address"); require(_cToken != address(0), "money market address is zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Commits the current draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (currentCommittedDrawId() > 0) { require(currentCommittedDrawHasBeenRewarded(), "the current committed draw has not been rewarded"); } if (currentOpenDrawId() != 0) { emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. */ //SWC-Transaction Order Dependence: L307-L310 function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw */ //SWC-Transaction Order Dependence: L323-L374 function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin requireCommittedNoReward nonReentrant { // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "secret does not match"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings = underlyingBalance.sub(accountedBalance); // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; awardWinnings(winningAddress, netWinnings); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); } function awardWinnings(address winner, uint256 amount) internal { // Update balance of the winner balances[winner] = balances[winner].add(amount); // Enter their winnings into the next draw drawState.deposit(winner, amount); } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { //SWC-Integer Overflow and Underflow: L414-L415 int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "token transfer failed"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "token transfer failed"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } function _depositPoolFromCommitted(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "could not approve money market spend"); require(cToken.mint(_amount) == 0, "could not supply money market"); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant { uint balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint balance = balances[_sender]; require(_amount <= balance, "not enough funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "could not redeem from compound"); require(token().transfer(_sender, _amount), "could not transfer winnings"); emit Withdrawn(_sender, _amount); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance, including both committed Draw balance and open Draw balance. * @param _addr The address of the user to check. * @return The users's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's total balance, including both committed Draw balance and open Draw balance. * @param _addr The address of the user to check. * @return The users's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "fee fraction must be 1 or less"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "beneficiary should not be 0x0"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "admin does not exist"); require(_admin != msg.sender, "cannot remove yourself"); admins.remove(_admin); emit AdminRemoved(_admin); } modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "must be a committed draw"); require(!currentCommittedDrawHasBeenRewarded(), "the committed draw has already been rewarded"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } function pause() public unlessPaused onlyAdmin { paused = true; emit Paused(msg.sender); } function unpause() public whenPaused onlyAdmin { paused = false; emit Unpaused(msg.sender); } modifier onlyAdmin() { require(admins.has(msg.sender), "must be an admin"); _; } modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "there is no open draw"); _; } modifier whenPaused() { require(paused, "contract is not paused"); _; } modifier unlessPaused() { require(!paused, "contract is paused"); _; } }
PoolTogether Audit JANUARY 16, 2020|IN SECURITY AUDITS|BY OPENZEPPELIN SECURITY PoolTogether is a protocol that allows users to join a trust-minimized no-loss lottery on the Ethereum network. The team asked us to review and audit the system. W e looked at the code and now publish our results. The audited commit is 78ac6863f4616269f7d04a0ddd1d60bdfc454937 and the contracts included in the scope were: BasePool DrawManager ERC777Pool MCDAwarePool Pool RecipientWhitelistERC777Pool UniformRandomNumber 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. Updat e: All issues hav e been addr essed or ac cepted by the P oolTogether t eam. Our analysis o f the mitigations assumes the pull r equests will be mer ged, but disr egards any other pot ential changes t o the c ode b ase. Not e that PR#3 introduces the Blocklock contract and r enames the ERC777Pool contract to PoolToken as part of a structur al change. Thes e new c ontracts ar e also in s cope. Here we present our findings. Summar y Overall, we are happy with the security posture of the team and the health of the codebase. W e are pleased to see the use of small, encapsulated functions and contracts that are mostly well documented. W e have some reservations about the privileged roles but we are glad to find that the team has considered the implications of their threat model with an intention to upgrade the design where appropriate. System Ov erview The system is a pool contract that accepts ER C20 tokens and deposits them into Compound Finance to earn interest, which is credited to the contract (not to the depositors). At any point in time, assuming Compound has available liquidity, users can withdraw their original ER C20 deposit to recover their initial value (at most, forfeiting the opportunity cost associated with the funds). The deposits are grouped into time windows, known as draws. Before a new draw is opened, a lottery is created and any interest held by the contract is assigned to the winner. Each user’s probability of winning is proportional to their total deposits in previous draws. It should be noted that the deposits in the current open draw are not eligible, so users cannot simply make a large deposit immediately before the transition in the hope of winning the lottery and then withdraw it immediately after. Users can also optionally deposit into a pool (increasing the interestearned by the contract) without entering the lottery. This last method is known as spons orship. Additionally, users are assigned a new ER C777 token representing their deposits in committed draws (that is, draws that are eligible for the current lottery). This makes it possible to transfer all or part of their stake in a pool. Of course, they still have the option of redeeming these tokens for the equivalent number of underlying ER C20 tokens if desired. To accommodate the ongoing transition from single- collateral D AI to multi-collateral D AI in the broader Ethereum ecosystem, the D AI pool contract also contains a mechanism for users to easily exchange their SAI P ool tokens for D AI Pool tokens. Privil eged R oles The pool contract is managed by administrators with wide-ranging powers. These powers include the ability to upgrade the contracts with completely new functionality. Naturally, in the hands of a malicious or compromised administrator, this includes the ability to freeze or steal the funds held by the pool contract. Additionally, administrators are involved in the regular operation of the system. For instance, the process to create a new draw is triggered by an administrator at a time of their choosing. They also choose (and pre- commit) the entropy that is used in the lottery. In the event that they forget the entropy, they have the option of opening a new draw without running a lottery, in which case the accrued interest is simply rolled into the subsequent lottery. An administrator can also pause the pool contract, which prevents new deposits but does not prevent token transfers or withdrawals. Lastly, the possible ER C777 token recipients are currently restricted to a whitelist, which is managed entirely by the administrators. The P oolTogether team intends to progressively decentralize many of these powers.Here we present our findings Critical Se verity None. High Se verity [H01] Users can influence the lotter y winner When the administrator calls reward or rewardAndOpenNextDraw, the secret and salt that will determine the lottery winner is revealed. However, the selected address will depend on the distribution of committed draws, which can be influenced by sending pool tokens to another address , burning pool tokens , or withdrawing an address’ entire balance . It can also be influenced by sending SAI pool tokens to the D AI pool contract . This gives users an opportunity to front-run the administrator transaction (by setting higher gas prices or mining the block themselves) in order to control the pool distribution and ensure an address they control will win the lottery. Consider freezing the committed distribution before revealing the lottery secret. Updat e: Fixed in PR#3 . Ther e is a new administr ator function that can t empor arily freeze all P ool Token balanc es, which should be called befor e the lott ery secret is r evealed. Additionally , it includes a c ool do wn period, s et dur ing the P ool initialization, t o prevent the administr ator from repeat edly calling this f unction and keeping the b alanc es frozen indef initely. Natur ally, this restriction can be changed or b ypassed if the c ontract is upgraded. [H02] Winners can stal l the systemBefore each new draw is created, the previous one must be rewarded . In the reward process, the awardWinnings function of the ERC777Pool contract, mints the new P ool tokens for the winner. Since the Pool T okens are an ER C777, they first call the tokensReceived hook for the winner’s address , if it exists. If the winner’s tokensReceived hook reverts, it will prevent the reward from being applied, stalling the whole system. They could also use this capability as leverage to extract resources (for instance, by writing a hook that will only succeed after receiving a payment). In the current version, the administrator can still bypass the reward step using the rollover feature . Naturally, this should not be relied upon as a mitigation since it introduces a new discretionary role for the administrator, and the feature will eventually be removed. As detailed in “[M01] Double counting r ewar ds”, assigning the reward should not be treated as a P ool Token minting event. Consider removing the awardWinnings function in the ERC777Pool contract , and instead relying on the overridden function in the BasePool contract . Updat e: Fixed in PR#3 . The awardWinnings function has been r emoved. Medium Se verity [M01] Doub le counting r ewards After each draw with a winner, the awardWinnings function is called. This updates the balances mapping, adds the reward to the current open draw on the winner’s behalf and emits the Minted and Transfer events. However, at this point in the process, the new P ool T okens have not been created (since the deposit is in the open draw).When the draw is subsequently committed, the balance of the draw becomes active and the corresponding events are emitted . This means that the Minted and Transfer events associated with the reward are emitted twice: first sending the prize to the winner address and then implicitly when the open supply is sent to the contract. This will cause a mismatch between the total supply created and the Minted events. Consider removing the awardWinnings function in the ERC777Pool contract , and instead relying on the overridden function in the BasePool contract . Note: this issue is related to “[H02] Winner s can stall the syst em” and any mitigation should consider both simultaneously. Updat e: Fixed in PR#3 . The awardWinnings function has been r emoved. This pull r equest actually r emoves the Minted and Transfer events entir ely as p art of a broader c ode r efact oring, but they ar e reintroduced in PR#4 [M02] B ypassing tok en e vents Pool T okens can be redeemed by calling the burn function on the ERC777Pool contract. This will emit the Burned and Transfer events . However, users can also call the withdraw function , which does not emit the events, to redeem their full balance of underlying tokens. This will prevent users from reacting to these state changes from the ER C777 events (although if they are aware of the code structure they could respond to the Withdrawn event). It also means that the Minted and Burned events will not track the total token supply. Note that the Withdrawn event does not compensate for this because it does not distinguish between committed balances, open draw balances, sponsorship balances, and fees. Consider either preventing the withdraw function from applying to committeddeposits (that have corresponding P ool tokens), or otherwise modifying it to emit the appropriate events. Note: this issue is related to “[L05] Conflat ed balances” and any mitigation should consider them both simultaneously. Updat e: Fixed in PR#4 . The Minted and Burned events are emitt ed when c ommitt ed balanc es are withdr awn from the pool. Low se verity [L01] De viation fr om ER C777 specification Pool T okens are created in a non-conventional way. Whenever users deposit assets into the system, they are internally accounted for but the new balances are not accessible to the ER C777 token functions. At the end of the draw, when the balances become available, it is no longer practical to create the corresponding Minted and Transfer events for each user. Instead, these events are emitted once for all users, with the recipient set to the P ool contract. This is a deviation from the ER C777 specification and makes it impossible to track balances using the event logs. This is already acknowledged and documented by the P oolTogether team , but we believe it should be stated in this report anyway for the sake of transparency and community awareness. [L02] Onl y dir ect deposits ar e pausab le The BasePool contract implements a mechanism to allow an administrator to pause the pool contract. However, only the direct deposit functions (depositPool and depositSponsorship) are affected. In particular, it is arguable that indirect deposits of D AI through the SAI migration mechanism should also be paused for consistency.Depending on the intended uses of the pause functionality, it may be desirable to permit the use of the other functions anyway. Nevertheless, it is surprising that the balances and contract state can change while the contract is paused. Consider documenting this decision and the corresponding rationale. Updat e: Fixed in PR#7 . The names and document ation have been updat ed to clar ify that the int ention is t o pause deposits int o depr ecated pools. P aused contracts are now als o prevented from ac cepting indir ect deposits and c onverting an y unexpect ed token balanc e into a spons orship. [L03] Doub le spending ER C20 allowance Like all compliant ER C20 tokens, the ERC777Pool contract is vulnerable to the allowance double spending attack. Briefly, an authorized spender could spend both allowances by front running an allowance- changing transaction. Consider implementing OpenZeppelin’s decreaseAllowance and increaseAllowance functions to help mitigate this. Updat e: Fixed in PR#16 . The f unctions w ere implement ed. [L04] Une xpected Side Eff ects Each P ool T oken is a claim on an equivalent amount of the underlying token. The burn and operatorBurn functions of the ERC777Pool contract destroy the P ool Tokens, redeem the equivalent value of cT okens in exchange for the underlying asset from Compound, and then return the underlying asset to the token holder. This is the standard mechanism for exiting the PoolTogether system. However, the conventionally understood definition of burning ER C20 or ER C777 tokens means sacrificing the token values by sending them to the zero address. Asit turns out, this is one step in the redeem functionality, but there are other side effects as well. Consider adding redeem and operatorRedeem functions to handle the standard withdrawal mechanism. The burn and operatorBurn functions should simply destroy tokens (and they may also prevent some or all users from burning tokens). Updat e: Fixed in PR#8 . The f unctionality t o exchange pool t okens for underlying t okens is no w kno wn as “redeeming” . The burn and operatorBurn functions revert. [L05] Confl ated bal ances The comments on the totalBalanceOf function suggest that the user’s total balance is comprised of the underlying token balance in open and committed draws. In fact, their underlying balance could also increase when receiving fees or when choosing to sponsor the lottery . Depending on the intention of the totalBalanceOf function, either the code or the comments should be updated for consistency. Additionally, since these increases never emit Minted events, update the committed supply, or effect the balanceOf function, they aren’t and won’t be tokenized into P ool T okens. This means there is no mechanism to withdraw them individually. Instead users must call the withdraw function to redeem their full balances across all draws. Consider allowing partial withdraws in the withdraw function or providing another mechanism to retrieve balances that are outside all draws. Note: this issue is related to “[M02] Byp assing t oken events” and any mitigation should consider them both simultaneously.Updat e: Fixed in PR#4 . The totalBalanceOf function comments hav e been updat ed. Additional ev ents and functions hav e been cr eated to suppor t withdr awing from the di fferent us er balanc es. Not e that the Withdrawn event no longer applies t o token transfer s betw een us ers. [L06] Misl eading comments and variab le names 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. The @return comment describing BasePool.getDraw only describes 4 of the 8 return values. The @notice function of BasePool.balanceOf states that it returns the user’s total balance but it only returns the committed balance. The rewardAndOpenNextDraw function and the reward function of BasePool do not have a @param comment for the salt. The BasePool contract returns the error message “could not transfer winnings” even though it applies to all balances. The @notice function of DrawManager.draw does not describe the case where are no participants. In addition, the following internal documentation could be clarified: The MAX_LEAVES constant does not constrain the number of leaves in the sortition tree. It should be a synonym of MAX_BRANCHES_PER_NODE or DEGREE_OF_TREE. It is also missing its comment. Many of the BaseP ool functions are not documented. The emitCommitted functions in the BasePool contract and the ERC777Pool contract claim tocommit the current draw. In fact, they simply emit events. The relevant state changes occur when the new draw is opened. The comments describing ERC777Pool._callTokensReceived do not include the last parameter. The requireOpenDraw and onlyNonZero modifiers are missing their comments. The RecipientWhitelistERC777Pool contract and most of its functions are not commented. Updat e: Fixed in PR#21 . Thes e suggestions w ere implement ed and the document ation has been significantly exp anded. [L07] Ex cessiv e code coup ling During a transfer of P ool T okens, the balance gets added to the recipient’s committed draw tree . If the recipient does not have any committed balance, it is added to a newly created balance associated with the previous draw . However, if the pool is currently in the first draw, which starts at index 1 , this will associate the new balance with the invalid zero draw, and will also leave the user’s first draw index at zero. This is an inconsistent state that would prevent the recipient from withdrawing, transferring or receiving awards based on their balance. Fortunately, the overall semantics of the system prevent this scenario. In particular, no user should have any P ool T okens during the first draw, so the situation could not arise. Nevertheless, it is bad practice to rely on global properties of the system to prevent local edge cases and it makes the code fragile to unrelated changes (for example, if a version of the code that pre-minted tokens was released, it would reintroduce this vulnerability).Consider confirming that the first draw is committed before assigning deposits to the previous draw. Updat e: Fixed in PR#9 . The depositCommitted and withdrawCommitted functions no w requir e at least one draw to be c ommitt ed. [L08] Uncheck ed casting fr om uint256 to int256 The BasePool contract uses the FixidityLib to perform fixed point arithmetic with protection against overflow . The newFixed function of the library accepts an int256 as the parameter so the uint256 variables _feeFraction and _grossWinnings first need to be cast into int256 values . If one of those parameters is higher than the maximum int256, the cast will overflow. This realistically should not occur but it is nevertheless good coding practice to explicitly check any assumptions. Consider ensuring that neither parameter exceeds the maximum int256. Updat e: Fixed in PR#12 . The _grossWinnings variable is now capped at the maximum s afe v alue. The _feeFraction was alr eady r estricted by the c ontract logic t o be less than 1e18 s o it c ould not caus e an overflow. Notes [N01] Unr estricted tok en ownership Whenever a pool token is transferred, the RecipientWhitelistERC777Pool contract restricts the possible recipients to an administrator-defined white list. It should be noted that this does not preventaddresses from receiving tokens in exchange for deposits or winning them in a lottery. Updat e: This is the expect ed behavior [N02] Inconsistent impor ts The code base imports contracts from the OpenZeppelin contracts package as well as contracts-ethereum-package. This is unnecessary and may cause issues if there is a name collision with imported contracts across both packages (or the contracts they depend on). In this case there is no collision, but it does introduce unnecessary fragility. Consider using contracts-ethereum-package exclusively, which is a copy of contracts that is consistent with the OpenZeppelin upgrades package. Updat e: Fixed in PR#10 . [N03] Def ault Visibil ity Throughout the code base, some of the contract variables use default visibility. For readability, consider explicitly declaring the visibility of all state variables. Updat e: Fixed in PR#13 . [N04] R eimp lementing P ausab le The BasePool contract allows an administrator to pause and resume some functions. The functionality is already part of OpenZeppelin contracts, which has been audited and is constantly reviewed by the community. Consider inheriting from the OpenZeppelin Pausable contract to benefit from bug fixes to be applied in future releases and to reduce the code’s attack surface. Updat e: Accepted. P oolTogether w ould pr efer not t o adopt this suggestion sinc e it w ould change the st orage layout o f an existing c ontract.[N05] R epeated code The RecipientWhitelistERC777Pool contract overrides the _callTokensToSend function to restrict the possible recipients . However, the rest of the function is identical. For simplicity, consider invoking the overridden function to execute the tokensToSend hook. Updat e: Fixed in PR#4 . [N06] R andom upper bound of zero The uniform function of the UniformRandomNumber library returns zero whenever the specified upper bound is zero . This contradicts the Ethereum Natural Specification comment and is inconsistent with the usual behavior of returning a value strictly less than the upper bound. Consider requiring the upper bound to be non-zero, or updating the comment accordingly. Updat e: Fixed in PR#14 . The bound is no w requir ed to be gr eater than zer o. The edge cas e is handled in the calling f unction. [N07] Semantic Ov erloading The pool contract identifies if a particular draw has been rewarded by checking if the entropy is non zero . This works because the winner is rewarded in the same function that the entropy is revealed , and it is highly unlikely to be zero. However, this is an example of semantic overloading . It also necessitates an arbitrary fake entropy value to be used whenever the administrator cannot reveal the entropy. W e did not identify any vulnerabilities arising from this pattern, but it does make the code more fragile.Consider including an explicit contract variable that tracks if the committed draw has been rewarded. Updat e: Acccepted. Sinc e the r ollover mechanism and entropy source will both be updat ed, P oolTogether would pr efer not t o intr oduce new st ate that will need t o be depr ecated. [N08] Unnecessar y casting of drawInde x During the draw function in the DrawManager library, the relevant tree index is obtained with the draw method of the SortionSumTreeFactory, which returns a bytes32 value . It is then cast to a uint256 and saved in the drawIndex variable. However, drawIndex is used twice to reference the selected tree , where it has to be cast back to a bytes32 value each time. Consider removing the redundant cast into a uint256 type. Updat e: Fixed in PR#17 . [N09] Unnecessar y Saf eMath sum oper ation In the committedBalanceOf function from the DrawManager contract , a balance variable is created to add the funds deposited under the firstDrawIndex and secondDrawIndex. When the funds under the firstDrawIndex are added to the balance, balance always equals zero, making the addition unnecessary. For simplicity and clarity, consider changing the SafeMath addition into a simple assignment. Updat e: Fixed in PR#18 . [N10] Instances of uintThroughout the code base, some variables are declared with type uint. To favor explicitness, consider changing all instances of uint to uint256. Updat e: Fixed in PR#19 . [N11] Naming To favor explicitness and readability, several parts of the contracts may benefit from better naming. Our suggestions are: In DrawManager.sol: usersFirstDrawIndex to consolidatedDrawIndex usersSecondDrawIndex to latestDrawIndex In BasePool.sol: Opened to DrawOpened Committed to DrawCommitted Rewarded to DrawConcluded Paused to PoolPaused Unpaused to PoolUnpaused open to openDraw Updat e: Partially f ixed in PR#20 . The ev ent names remain unchanged t o maint ain c onsist ency with the deplo yed contract. Conc lusion No critical and two high severity issues were found. Some changes were proposed to follow best practices and reduce potential attack surface. Securit y AuditsIf 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. RELA TED POSTS Freeverse A udit The Freeverse team asked us to review and audit their NFT marketplace. W e looked at the code and… READ MORE SECURITY AUDITS Celo Contr acts A udit – Release 7 – P art 1 The Celo team asked us to review and audit R elease 7 smart contracts. W e looked at the code and now… READ MORE SECURITY AUDITS Celo Contr acts A udit – Release 7Part2 SECURITY AUDITS Release 7 – P art 2 The Celo team asked us to review and audit R elease 7 smart contracts. W e looked at the code and now… READ MORE Email * Get our monthly news roundup SIGN UP © OpenZeppelin 2017-2022 Privacy | Terms of ServiceProducts Contracts DefenderSecurity Security AuditsLearn Docs Forum EthernautComp any Website About Jobs Logo Kit
Issues Count of Minor/Moderate/Major/Critical Minor: 4 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem (one line with code reference): The function `withdraw` in `BasePool` does not check the return value of `transferFrom` (Lines 545-546). 2.b Fix (one line with code reference): Check the return value of `transferFrom` (Lines 545-546). 3.a Problem (one line with code reference): The function `withdraw` in `BasePool` does not check the return value of `transfer` (Lines 548-549). 3.b Fix (one line with code reference): Check the return value of `transfer` (Lines 548-549). 4.a Problem (one line with code reference): The function `withdraw` in `BasePool` does not check the return value of `transfer` (Lines 551-552). 4.b Fix (one line with code reference): Check the return value of `transfer` (Lines 551-552). 5.a Problem (one line with code Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 1 Critical: 0 Major 4.a Problem [H01] Users can influence the lottery winner 4.b Fix Fixed in PR#3. There is a new administrator function that can temporarily freeze all Pool Token balances, which should be called before the lottery secret is revealed. Additionally, it includes a cool down period, set during the Pool initialization, to prevent the administrator from repeatedly calling this function and keeping the balances frozen indefinitely. Naturally, this restriction can be changed or bypassed if the contract is upgraded. 5.a Problem [H02] Winners can stall the system 5.b Fix Before each new draw is created, the previous one must be rewarded. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Double counting rewards 2.b Fix: Removed awardWinnings function in the ERC777Pool contract and instead relying on the overridden function in the BasePool contract. Moderate Issues: 3.a Problem: Bypassing token events 3.b Fix: Removed Withdrawn event and reintroduced in PR#4.
pragma solidity 0.5.4; import './DSLibrary/DSAuth.sol'; import './interface/IDispatcher.sol'; contract DispatcherEntrance is DSAuth { mapping(address => mapping(address => address)) dispatchers; function registDispatcher(address _fund, address _token, address _dispatcher) external auth { dispatchers[_fund][_token] = _dispatcher; } function getDispatcher(address _fund, address _token) public view returns (address) { return dispatchers[_fund][_token]; } }pragma solidity 0.5.4; import './DSLibrary/DSAuth.sol'; import './DSLibrary/DSMath.sol'; import './interface/ITargetHandler.sol'; import './interface/IDispatcher.sol'; import './interface/IERC20.sol'; interface IFund { function transferOut(address _tokenID, address _to, uint amount) external returns (bool); } contract Dispatcher is IDispatcher, DSAuth, DSMath { address token; address profitBeneficiary; address fundPool; TargetHandler[] ths; uint256 reserveUpperLimit; uint256 reserveLowerLimit; uint256 executeUnit; struct TargetHandler { address targetHandlerAddr; address targetAddr; uint256 aimedPropotion; } constructor (address _tokenAddr, address _fundPool, address[] memory _thAddr, uint256[] memory _thPropotion, uint256 _tokenDecimals) public { token = _tokenAddr; fundPool = _fundPool; require(_thAddr.length == _thPropotion.length, "wrong length"); uint256 sum = 0; uint256 i; for(i = 0; i < _thAddr.length; ++i) { sum = add(sum, _thPropotion[i]); } require(sum == 1000, "the sum of propotion must be 1000"); for(i = 0; i < _thAddr.length; ++i) { ths.push(TargetHandler(_thAddr[i], ITargetHandler(_thAddr[i]).getTargetAddress(), _thPropotion[i])); } executeUnit = (10 ** _tokenDecimals) / 10; //0.1 // set up the default limit reserveUpperLimit = 350; // 350 / 1000 = 0.35 reserveLowerLimit = 300; // 300 / 1000 = 0.3 } function trigger () auth external returns (bool) { uint256 reserve = getReserve(); uint256 denominator = add(reserve, getPrinciple()); uint256 reserveMax = reserveUpperLimit * denominator / 1000; uint256 reserveMin = reserveLowerLimit * denominator / 1000; uint256 amounts; if (reserve > reserveMax) { amounts = sub(reserve, reserveMax); amounts = div(amounts, executeUnit); amounts = mul(amounts, executeUnit); if (amounts > 0) { internalDeposit(amounts); return true; } } else if (reserve < reserveMin) { amounts = sub(reserveMin, reserve); amounts = div(amounts, executeUnit); amounts = mul(amounts, executeUnit); if (amounts > 0) { withdrawPrinciple(amounts); return true; } } return false; } function internalDeposit (uint256 _amount) internal { uint256 i; uint256 _amounts = _amount; uint256 amountsToTH; uint256 thCurrentBalance; uint256 amountsToSatisfiedAimedPropotion; uint256 totalPrincipleAfterDeposit = add(getPrinciple(), _amounts); TargetHandler memory _th; for(i = 0; i < ths.length; ++i) { _th = ths[i]; amountsToTH = 0; thCurrentBalance = getTHPrinciple(i); amountsToSatisfiedAimedPropotion = div(mul(totalPrincipleAfterDeposit, _th.aimedPropotion), 1000); amountsToSatisfiedAimedPropotion = mul(div(amountsToSatisfiedAimedPropotion, executeUnit), executeUnit); if (thCurrentBalance > amountsToSatisfiedAimedPropotion) { continue; } else { amountsToTH = sub(amountsToSatisfiedAimedPropotion, thCurrentBalance); if (amountsToTH > _amounts) { amountsToTH = _amounts; _amounts = 0; } else { _amounts = sub(_amounts, amountsToTH); } if(amountsToTH > 0) { IFund(fundPool).transferOut(token, _th.targetHandlerAddr, amountsToTH); ITargetHandler(_th.targetHandlerAddr).deposit(amountsToTH); } } } } function withdrawPrinciple (uint256 _amount) internal { uint256 i; uint256 _amounts = _amount; uint256 amountsFromTH; uint256 thCurrentBalance; uint256 amountsToSatisfiedAimedPropotion; uint256 totalBalanceAfterWithdraw = sub(getPrinciple(), _amounts); TargetHandler memory _th; for(i = 0; i < ths.length; ++i) { _th = ths[i]; amountsFromTH = 0; thCurrentBalance = getTHPrinciple(i); amountsToSatisfiedAimedPropotion = div(mul(totalBalanceAfterWithdraw, _th.aimedPropotion), 1000); if (thCurrentBalance < amountsToSatisfiedAimedPropotion) { continue; } else { amountsFromTH = sub(thCurrentBalance, amountsToSatisfiedAimedPropotion); if (amountsFromTH > _amounts) { amountsFromTH = _amounts; _amounts = 0; } else { _amounts = sub(_amounts, amountsFromTH); } if (amountsFromTH > 0) { ITargetHandler(_th.targetHandlerAddr).withdraw(amountsFromTH); } } } } function withdrawProfit () external auth returns (bool) { require(profitBeneficiary != address(0), "profitBeneficiary not settled."); uint256 i; TargetHandler memory _th; for(i = 0; i < ths.length; ++i) { _th = ths[i]; ITargetHandler(_th.targetHandlerAddr).withdrawProfit(); } return true; } function drainFunds (uint256 _index) external auth returns (bool) { require(profitBeneficiary != address(0), "profitBeneficiary not settled."); TargetHandler memory _th = ths[_index]; ITargetHandler(_th.targetHandlerAddr).drainFunds(); return true; } function refundDispather (address _receiver) external auth returns (bool) { uint256 lefto = IERC20(token).balanceOf(address(this)); IERC20(token).transfer(_receiver, lefto); return true; } // getter function function getReserve() public view returns (uint256) { return IERC20(token).balanceOf(fundPool); } function getReserveRatio() public view returns (uint256) { uint256 reserve = getReserve(); uint256 denominator = add(getPrinciple(), reserve); uint256 adjusted_reserve = add(reserve, executeUnit); if (denominator == 0) { return 0; } else { return div(mul(adjusted_reserve, 1000), denominator); } } function getPrinciple() public view returns (uint256 result) { result = 0; for(uint256 i = 0; i < ths.length; ++i) { result = add(result, getTHPrinciple(i)); } } function getBalance() public view returns (uint256 result) { result = 0; for(uint256 i = 0; i < ths.length; ++i) { result = add(result, getTHBalance(i)); } } function getProfit() public view returns (uint256) { return sub(getBalance(), getPrinciple()); } function getTHPrinciple(uint256 _index) public view returns (uint256) { return ITargetHandler(ths[_index].targetHandlerAddr).getPrinciple(); } function getTHBalance(uint256 _index) public view returns (uint256) { return ITargetHandler(ths[_index].targetHandlerAddr).getBalance(); } function getTHProfit(uint256 _index) public view returns (uint256) { return ITargetHandler(ths[_index].targetHandlerAddr).getProfit(); } function getTHData(uint256 _index) external view returns (uint256, uint256, uint256, uint256) { address _mmAddr = ths[_index].targetAddr; return (getTHPrinciple(_index), getTHBalance(_index), getTHProfit(_index), IERC20(token).balanceOf(_mmAddr)); } function getFund() external view returns (address) { return fundPool; } function getToken() external view returns (address) { return token; } function getProfitBeneficiary() external view returns (address) { return profitBeneficiary; } function getReserveUpperLimit() external view returns (uint256) { return reserveUpperLimit; } function getReserveLowerLimit() external view returns (uint256) { return reserveLowerLimit; } function getExecuteUnit() external view returns (uint256) { return executeUnit; } function getPropotion() external view returns (uint256[] memory) { uint256 length = ths.length; TargetHandler memory _th; uint256[] memory result = new uint256[](length); for (uint256 i = 0; i < length; ++i) { _th = ths[i]; result[i] = _th.aimedPropotion; } return result; } function getTHCount() external view returns (uint256) { return ths.length; } function getTHAddress(uint256 _index) external view returns (address) { return ths[_index].targetHandlerAddr; } function getTargetAddress(uint256 _index) external view returns (address) { return ths[_index].targetAddr; } function getTHStructures() external view returns (uint256[] memory, address[] memory, address[] memory) { uint256 length = ths.length; TargetHandler memory _th; uint256[] memory prop = new uint256[](length); address[] memory thAddr = new address[](length); address[] memory mmAddr = new address[](length); for (uint256 i = 0; i < length; ++i) { _th = ths[i]; prop[i] = _th.aimedPropotion; thAddr[i] = _th.targetHandlerAddr; mmAddr[i] = _th.targetAddr; } return (prop, thAddr, mmAddr); } // owner function function setAimedPropotion(uint256[] calldata _thPropotion) external auth returns (bool){ require(ths.length == _thPropotion.length, "wrong length"); uint256 sum = 0; uint256 i; TargetHandler memory _th; for(i = 0; i < _thPropotion.length; ++i) { sum = add(sum, _thPropotion[i]); } require(sum == 1000, "the sum of propotion must be 1000"); for(i = 0; i < _thPropotion.length; ++i) { _th = ths[i]; _th.aimedPropotion = _thPropotion[i]; ths[i] = _th; } return true; } function removeTargetHandler(address _targetHandlerAddr, uint256 _index, uint256[] calldata _thPropotion) external auth returns (bool) { uint256 length = ths.length; uint256 sum = 0; uint256 i; TargetHandler memory _th; require(length > 1, "can not remove the last target handler"); require(_index < length, "not the correct index"); require(ths[_index].targetHandlerAddr == _targetHandlerAddr, "not the correct index or address"); require(getTHPrinciple(_index) == 0, "must drain all balance in the target handler"); ths[_index] = ths[length - 1]; ths.length --; require(ths.length == _thPropotion.length, "wrong length"); for(i = 0; i < _thPropotion.length; ++i) { sum = add(sum, _thPropotion[i]); } require(sum == 1000, "the sum of propotion must be 1000"); for(i = 0; i < _thPropotion.length; ++i) { _th = ths[i]; _th.aimedPropotion = _thPropotion[i]; ths[i] = _th; } return true; } function addTargetHandler(address _targetHandlerAddr, uint256[] calldata _thPropotion) external auth returns (bool) { uint256 length = ths.length; uint256 sum = 0; uint256 i; TargetHandler memory _th; for(i = 0; i < length; ++i) { _th = ths[i]; require(_th.targetHandlerAddr != _targetHandlerAddr, "exist target handler"); } ths.push(TargetHandler(_targetHandlerAddr, ITargetHandler(_targetHandlerAddr).getTargetAddress(), 0)); require(ths.length == _thPropotion.length, "wrong length"); for(i = 0; i < _thPropotion.length; ++i) { sum += _thPropotion[i]; } require(sum == 1000, "the sum of propotion must be 1000"); for(i = 0; i < _thPropotion.length; ++i) { _th = ths[i]; _th.aimedPropotion = _thPropotion[i]; ths[i] = _th; } return true; } function setReserveUpperLimit(uint256 _number) external auth returns (bool) { require(_number >= reserveLowerLimit, "wrong number"); reserveUpperLimit = _number; return true; } function setReserveLowerLimit(uint256 _number) external auth returns (bool) { require(_number <= reserveUpperLimit, "wrong number"); reserveLowerLimit = _number; return true; } function setExecuteUnit(uint256 _number) external auth returns (bool) { executeUnit = _number; return true; } function setProfitBeneficiary(address _profitBeneficiary) external auth returns (bool) { profitBeneficiary = _profitBeneficiary; return 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.0; interface IERC20 { function balanceOf(address _owner) external view returns (uint); function allowance(address _owner, address _spender) external view returns (uint); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function totalSupply() external view returns (uint); } interface CErc20 { function mint(uint mintAmount) external returns (uint); function redeem(uint tokenAmount) external returns (uint); function redeemUnderlying(uint deemAmount) external returns (uint); function exchangeRateStored() external view returns (uint); } contract FakeCompound { address public token; mapping(address => uint256) public balances; constructor (address _token) public { token = _token; } function mint(uint _amounts) external returns (uint) { require(IERC20(token).transferFrom(msg.sender, address(this), _amounts)); balances[msg.sender] += _amounts; return 0; } function redeemUnderlying(uint _amounts) external returns (uint) { require(balances[msg.sender] >= _amounts, "user have no enough token"); balances[msg.sender] -= _amounts; require(IERC20(token).transfer(msg.sender, _amounts), "contrract balance not enough"); return 0; } function redeem(uint _amounts) external returns (uint) { require(balances[msg.sender] >= _amounts, "user have no enough token"); balances[msg.sender] -= _amounts; require(IERC20(token).transfer(msg.sender, _amounts), "contrract balance not enough"); return 0; } function makeProfitToUser(address _user, uint256 _percentage) external { balances[_user] = balances[_user] * (1000 + _percentage) / 1000; } function exchangeRateStored() external view returns (uint){ return (10 ** 18); } function balanceOf(address _owner) external view returns (uint) { return balances[_owner]; } }
Confidential SMART CONTRACT AUDIT REPORT for DFORCE NETWORK Prepared By: Shuxiao Wang Feb. 27, 2020 1/30 PeckShield Audit Report #: 2020-03Confidential Document Properties Client dForce Network Title Smart Contract Audit Report Target DIP001 Version 1.0 Author Huaguo Shi Auditors Chiachih Wu, Huaguo Shi Reviewed by Chiachih Wu Approved by Xuxian Jiang Classification Confidential Version Info Version Date Author(s) Description 1.0 Feb. 27, 2020 Huaguo Shi Final Release 0.3 Feb. 27, 2020 Huaguo Shi Status Update 0.2 Feb. 26, 2020 Huaguo Shi Status Update, More Findings Added 0.1 Feb. 15, 2020 Huaguo Shi Initial Draft 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/30 PeckShield Audit Report #: 2020-03Confidential Contents 1 Introduction 5 1.1 About DIP001 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 10 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3 Detailed Results 12 3.1 Misleading Return Code in Dispatcher . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.2 Missing Check before Withdrawing Principle . . . . . . . . . . . . . . . . . . . . . . 13 3.3 Wrong Proportion After Adding/Removing Target Handlers . . . . . . . . . . . . . . 15 3.4 Excessive Owner Privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.5 Gas Consumption Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.6 Wrong Proportion After Setting Aimed Proportion . . . . . . . . . . . . . . . . . . . 18 3.7 Insufficient Validation to Target Handler . . . . . . . . . . . . . . . . . . . . . . . . 19 3.8 Redundant Code in Dispatcher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.9 Optimization Suggestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.10 Other Suggestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 4 Conclusion 22 5 Appendix 23 5.1 Basic Coding Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.1.1 Constructor Mismatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.1.2 Ownership Takeover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.1.3 Redundant Fallback Function . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.1.4 Overflows & Underflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3/30 PeckShield Audit Report #: 2020-03Confidential 5.1.5 Reentrancy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.1.6 Money-Giving Bug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.1.7 Blackhole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.1.8 Unauthorized Self-Destruct . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.1.9 Revert DoS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.1.10 Unchecked External Call. . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 5.1.11 Gasless Send. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 5.1.12 SendInstead Of Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 5.1.13 Costly Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 5.1.14 (Unsafe) Use Of Untrusted Libraries . . . . . . . . . . . . . . . . . . . . . . 25 5.1.15 (Unsafe) Use Of Predictable Variables . . . . . . . . . . . . . . . . . . . . . 26 5.1.16 Transaction Ordering Dependence . . . . . . . . . . . . . . . . . . . . . . . 26 5.1.17 Deprecated Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 5.2 Semantic Consistency Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 5.3 Additional Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 5.3.1 Avoid Use of Variadic Byte Array . . . . . . . . . . . . . . . . . . . . . . . . 26 5.3.2 Use Fixed Compiler Version . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 5.3.3 Make Visibility Level Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . 27 5.3.4 Make Type Inference Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . 27 5.3.5 Adhere To Function Declaration Strictly . . . . . . . . . . . . . . . . . . . . 27 References 28 4/30 PeckShield Audit Report #: 2020-03Confidential 1 | Introduction Giventheopportunitytoreviewthe DIP001designdocumentandrelatedsmartcontractsourcecode, 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 DIP001 DIP001 is a protocol that unlocks collaterals from an initiated collateralized DeFi protocol and supply those collaterals into designated yield generating protocols (i.e., Lendf.Me, Compound, dydx etc.) With a DAO scheme, DIP001 allows DF holders to vote for managing the protocol (the management contract is not implemented yet). The basic information of DIP001 is as follows: Table 1.1: Basic Information of DIP001 ItemDescription IssuerdForce Network Website https://dforce.network/ TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report Feb. 27, 2020 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: •https://github.com/dforce-network/DIP001/tree/audit (513d6c5) •https://github.com/dforce-network/DIP001/tree/audit _v0.2 (830e89d) 5/30 PeckShield Audit Report #: 2020-03Confidential •https://github.com/dforce-network/DIP001/tree/audit (267ee75) Table 1.2: Audit Scope FolderFiles contracts Dispatcher.sol contracts DispatcherEntrance.sol contracts/DSLibrary *.* contracts/interface *.* contracts/CompoundHandler CompoundHandler.sol contracts/lendFMeHandler lendFMeHandler.sol 1.2 About PeckShield PeckShield Inc. [22] 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.3: 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 [17]: •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; 6/30 PeckShield Audit Report #: 2020-03Confidential •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.3. 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.4. 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) [16], 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.5 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. 7/30 PeckShield Audit Report #: 2020-03Confidential Table 1.4: 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 8/30 PeckShield Audit Report #: 2020-03Confidential Table 1.5: 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/30 PeckShield Audit Report #: 2020-03Confidential 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the DIP001 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 1 Low 0 Informational 8 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. 10/30 PeckShield Audit Report #: 2020-03Confidential 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 8informational recommendations. Table 2.1: Key Audit Findings IDSeverity Title Category Status PVE-001 Info. Misleading ReturnCodeinDispatcherError Conditions, Return Values, Status CodesResolved PVE-002 Info. MissingCheckbeforeWithdrawing PrincipleError Conditions, Return Values, Status CodesResolved PVE-003 MediumWrongProportion After Adding/Removing TargetHandlersBusiness Logics Resolved PVE-004 Info. Excessive OwnerPrivileges Business Logics Confirmed PVE-005 Info. GasConsumption Optimization Resource Management Confirmed PVE-006 Info.WrongProportion AfterSetting AimedProportionBusiness Logics Confirmed PVE-007 Info. Insufficient Validation toTargetHandlerError Conditions, Return Values, Status CodesConfirmed PVE-008 Info. Redundant CodeinDispatcher Coding Practices Resolved PVE-009 Info. Optimization Suggestions Behavioral Issues Confirmed Please refer to Section 3 for details. 11/30 PeckShield Audit Report #: 2020-03Confidential 3 | Detailed Results 3.1 Misleading Return Code in Dispatcher •ID: PVE-001 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Dispatcher.sol •Category: Error Conditions, Return Val- ues, Status Codes [14] •CWE subcategory: CWE-394 [6] Description In DIP001, the Dispatcher is designed to distribute digital assets between different yield generating protocols. Specifically, the trigger() function is used to trigger the re-balance process when the amount of reserved assets is below reserveMin or above reserveMax . However, the function always returns truewhether internalDeposit() orwithdrawPrinciple() are literally triggered or not. This makes the return code meaningless. 62 function t r i g g e r ( ) external returns (bool ) { 63 uint256 r e s e r v e = g e t R e s e r v e ( ) ; 64 uint256 denominator = r e s e r v e . add ( g e t P r i n c i p l e ( ) ) ; 65 uint256 reserveMax = r e s e r v e U p p e r L i m i t ∗denominator / 1000; 66 uint256 r e s e r v e M i n = r e s e r v e L o w e r L i m i t ∗denominator / 1000; 67 uint256 amounts ; 68 i f( r e s e r v e > reserveMax ) { 69 amounts = r e s e r v e *reserveMax ; 70 amounts = amounts / e x e c u t e U n i t ∗e x e c u t e U n i t ; 71 i f( amounts != 0) { 72 i n t e r n a l D e p o s i t ( amounts ) ; 73 } 74 }e l s e i f ( r e s e r v e < r e s e r v e M i n ) { 75 amounts = r e s e r v e M i n *r e s e r v e ; 76 amounts = amounts / e x e c u t e U n i t ∗e x e c u t e U n i t ; 77 i f( amounts != 0) { 78 w i t h d r a w P r i n c i p l e ( amounts ) ; 79 } 80 } 12/30 PeckShield Audit Report #: 2020-03Confidential 81 return true ; 82 } Listing 3.1: contracts/Dispatcher. sol Recommendation Return truewhen something is really triggered. Return falsewhen nothing happened. 62 function t r i g g e r ( ) external returns (bool ) { 63 uint256 r e s e r v e = g e t R e s e r v e ( ) ; 64 uint256 denominator = r e s e r v e . add ( g e t P r i n c i p l e ( ) ) ; 65 uint256 reserveMax = r e s e r v e U p p e r L i m i t ∗denominator / 1000; 66 uint256 r e s e r v e M i n = r e s e r v e L o w e r L i m i t ∗denominator / 1000; 67 uint256 amounts ; 68 i f( r e s e r v e > reserveMax ) { 69 amounts = r e s e r v e *reserveMax ; 70 amounts = amounts / e x e c u t e U n i t ∗e x e c u t e U n i t ; 71 i f( amounts != 0) { 72 i n t e r n a l D e p o s i t ( amounts ) ; 73 return true ; 74 } 75 }e l s e i f ( r e s e r v e < r e s e r v e M i n ) { 76 amounts = r e s e r v e M i n *r e s e r v e ; 77 amounts = amounts / e x e c u t e U n i t ∗e x e c u t e U n i t ; 78 i f( amounts != 0) { 79 w i t h d r a w P r i n c i p l e ( amounts ) ; 80 return true ; 81 } 82 } 83 return f a l s e ; 84 } Listing 3.2: contracts/Dispatcher. sol 3.2 Missing Check before Withdrawing Principle •ID: PVE-002 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Dispatcher.sol •Category: Error Conditions, Return Val- ues, Status Codes [14] •CWE subcategory: CWE-391 [5] Description In the Dispatcher contract, the trigger() function calls deposit()/ withdraw() of the corresponding target handler to re-balance the digital assets distribution. We noticed that in internalDeposit() , the amount to be deposited is validated such that the underlying deposit() is only invoked when the 13/30 PeckShield Audit Report #: 2020-03Confidential amount is greater than 0. However, the validation is not applied on the withdraw() case. Specifically, the withdrawPrinciple() does not validate the amount to be withdrew before calling the underlying withdraw() . 116 function w i t h d r a w P r i n c i p l e ( uint256 _amount ) i n t e r n a l {// 117 uint256 i ; 118 uint256 _amounts = _amount ; 119 uint256 amountsFromTH ; 120 uint256 t h C u r r e n t B a l a n c e ; 121 uint256 amountsToSatisfiedAimedPropotion ; 122 uint256 t o t a l B a l a n c e A f t e r W i t h d r a w = g e t P r i n c i p l e ( ) . sub ( _amounts ) ; 123 TargetHandler memory _th ; 124 for( i = 0 ; i < t h s . length ; ++i ) { 125 _th = t h s [ i ] ; 126 amountsFromTH = 0 ; 127 t h C u r r e n t B a l a n c e = g e t T H P r i n c i p l e ( i ) ; 128 amountsToSatisfiedAimedPropotion = t o t a l B a l a n c e A f t e r W i t h d r a w . mul ( _th . aimedPropotion ) / 1000; 129 i f( t h C u r r e n t B a l a n c e < amountsToSatisfiedAimedPropotion ) { 130 continue ; 131 }e l s e { 132 amountsFromTH = t h C u r r e n t B a l a n c e *amountsToSatisfiedAimedPropotion ; 133 i f( amountsFromTH > _amounts ) { 134 amountsFromTH = _amounts ; 135 _amounts = 0 ; 136 }e l s e { 137 _amounts *= amountsFromTH ; 138 } 139 I T a r g e t H a n d l e r ( _th . t a r g e t H a n d l e r A d d r ) . withdraw ( amountsFromTH ) ; 140 } 141 } 142 } Listing 3.3: contracts/Dispatcher. sol Recommendation Ensure amountsFromTH > 0 inwithdrawPrinciple() before calling withdraw() . For better maintenance, we suggest to change the amountsFromTH !=0 check in internalDeposit() to amountsFromTH > 0 regardless the fact that amountsFromTH is an unsigned integer. 116 function w i t h d r a w P r i n c i p l e ( uint256 _amount ) i n t e r n a l {// 117 uint256 i ; 118 uint256 _amounts = _amount ; 119 uint256 amountsFromTH ; 120 uint256 t h C u r r e n t B a l a n c e ; 121 uint256 amountsToSatisfiedAimedPropotion ; 122 uint256 t o t a l B a l a n c e A f t e r W i t h d r a w = g e t P r i n c i p l e ( ) . sub ( _amounts ) ; 123 TargetHandler memory _th ; 124 for( i = 0 ; i < t h s . length ; ++i ) { 125 _th = t h s [ i ] ; 126 amountsFromTH = 0 ; 127 t h C u r r e n t B a l a n c e = g e t T H P r i n c i p l e ( i ) ; 14/30 PeckShield Audit Report #: 2020-03Confidential 128 amountsToSatisfiedAimedPropotion = t o t a l B a l a n c e A f t e r W i t h d r a w . mul ( _th . aimedPropotion ) / 1000; 129 i f( t h C u r r e n t B a l a n c e < amountsToSatisfiedAimedPropotion ) { 130 continue ; 131 }e l s e { 132 amountsFromTH = t h C u r r e n t B a l a n c e *amountsToSatisfiedAimedPropotion ; 133 i f( amountsFromTH > _amounts ) { 134 amountsFromTH = _amounts ; 135 _amounts = 0 ; 136 }e l s e { 137 _amounts *= amountsFromTH ; 138 } 139 i f( amountsToTH > 0) { 140 I T a r g e t H a n d l e r ( _th . t a r g e t H a n d l e r A d d r ) . withdraw ( amountsFromTH ) ; 141 } 142 } 143 } 144 } Listing 3.4: contracts/Dispatcher. sol 3.3 Wrong Proportion After Adding/Removing Target Handlers •ID: PVE-003 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Dispatcher.sol •Category: Business Logics [13] •CWE subcategory: CWE-841 [9] Description While initializing the Dispatcher contract, we can add multiple target handlers with an array along with the corresponding proportion array. Essentially, the constructor of Dispatcher ensure the sum of the proportion bound with each target handler is 1000, which makes 100~of the digital assets deposited into target handlers are distributed. Beyond the initialization process, removeTargetHandler ()/ addTargetHandle() could be used to dynamically remove/add target handlers. However, the currentimplementationof removeTargetHandler()/ addTargetHandle() doesnotvalidatetheproportion after adding/removing a target handler, leading to invalid proportion settings. For example, when the privileged user adds or removes a target handler but forgets to re-org the proportion settings with setAimedPropotion , the sum of all aimedPropotion would be not equal to 1000. Moreover, even if the privileged user does re-org the proportion settings, there’s still a time window that the proportion settings is in a wrong state. This leads to a possible front-running attack. 15/30 PeckShield Audit Report #: 2020-03Confidential 116 function removeTargetHandler ( address _targetHandlerAddr , uint256 _index ) external auth returns (bool ) { 117 uint256 length = t h s . length ; 118 require (length != 1 , " can not remove the last target handler " ) ; 119 require ( _index < length ," not the correct index " ) ; 120 require ( t h s [ _index ] . t a r g e t H a n d l e r A d d r == _targetHandlerAddr , " not the correct index or address " ) ; 121 require ( g e t T H P r i n c i p l e ( _index ) == 0 , " must drain all balance in the target handler " ) ; 122 t h s [ _index ] = t h s [ length *1 ] ; 123 t h s . length **; 124 return true ; 125 } Listing 3.5: removeTargetHandler() contracts/Dispatcher. sol Recommendation Set the proportion of each target handler whenever a target handler is added or removed and make sure the total aimedPropotion is1000after the adding/removing operation. Here, we use removeTargetHandler() as an example. 116 function removeTargetHandler ( address _targetHandlerAddr , uint256 _index , uint256 [ ] c a l l d a t a _thPropotion ) external auth returns (bool ) { 117 uint256 length = t h s . length ; 118 uint256 sum = 0 ; 119 uint256 i ; 120 TargetHandler memory _th ; 121 122 require (length > 1 , " can not remove the last target handler " ) ; 123 require ( _index < length ," not the correct index " ) ; 124 require ( t h s [ _index ] . t a r g e t H a n d l e r A d d r == _targetHandlerAddr , " not the correct index or address " ) ; 125 require ( g e t T H P r i n c i p l e ( _index ) == 0 , " must drain all balance in the target handler " ) ; 126 t h s [ _index ] = t h s [ length *1 ] ; 127 t h s . length **; 128 129 require ( t h s . length == _thPropotion . length ," wrong length " ) ; 130 for( i = 0 ; i < _thPropotion . length ; ++i ) { 131 sum = add (sum , _thPropotion [ i ] ) ; 132 } 133 require (sum == 1000 , " the sum of propotion must be 1000 " ) ; 134 for( i = 0 ; i < _thPropotion . length ; ++i ) { 135 _th = t h s [ i ] ; 136 _th . aimedPropotion = _thPropotion [ i ] ; 137 t h s [ i ] = _th ; 138 } 139 return true ; 140 } Listing 3.6: removeTargetHandler() contracts/Dispatcher. sol 16/30 PeckShield Audit Report #: 2020-03Confidential 3.4 Excessive Owner Privileges •ID: PVE-004 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Dispatcher.sol, DispatcherEntrance .sol •Category: Business Logics [13] •CWE subcategory: CWE-708 [8] Description The current version of DIP001 does not implement the management contract which applies DAO managementscheme. Withthatbeingsaid,allprivilegedfunctionsin Dispatcher and DispatcherEntrance are controlled by the user having the auth key. That powerful auth key can be used to change the aimed proportion, set the beneficiary address, etc. It would be a single point of failure if the privileged user is compromised, leading to security risks to users’ assets. Recommendation Deploy the management contract and apply the DAO scheme to achieve decentralized governance. 3.5 Gas Consumption Optimization •ID: PVE-005 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: CompoundHandler.sol •Category: Resource Management [15] •CWE subcategory: CWE-920 [10] Description InCompoundHandler , the deposit() does not validate the _amounts, which is waste of gas. Specifically, in the case that _amounts = 0 , the principle would not change after some no-effect code which consumes gas. 35 // token deposit 36 function d e p o s i t ( uint256 _amounts ) external auth returns (uint256 ) { 37 i f( IERC20 ( token ) . balanceOf ( address (t h i s ) ) >= _amounts ) { 38 i f( ILendFMe ( t a r g e t Ad d r ) . s u p p l y ( address ( token ) , _amounts ) == 0) { 39 p r i n c i p l e = add ( p r i n c i p l e , _amounts ) ; 40 return 0 ; 41 } 42 } 43 return 1 ; 17/30 PeckShield Audit Report #: 2020-03Confidential 44 } Listing 3.7: contracts/handlers/CompoundHandler.sol Recommendation Ensure _amounts is not 0, which optimizes gas consumption. 35 // token deposit 36 function d e p o s i t ( uint256 _amounts ) external auth returns (uint256 ) { 37 i f( _amounts != 0 && IERC20 ( token ) . balanceOf ( address (t h i s ) ) >= _amounts ) { 38 i f( ILendFMe ( t a r g e t Ad d r ) . s u p p l y ( address ( token ) , _amounts ) == 0) { 39 p r i n c i p l e = add ( p r i n c i p l e , _amounts ) ; 40 return 0 ; 41 } 42 } 43 return 1 ; 44 } Listing 3.8: contracts/handlers/CompoundHandler.sol 3.6 Wrong Proportion After Setting Aimed Proportion •ID: PVE-006 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Dispatcher.sol •Category: Business Logics [13] •CWE subcategory: CWE-841 [9] Description When setAimedPropotion() is used to set a new set of aimed proportion, the amount of principle may not be compatible to the new settings. For example, there’re three target handlers having 2:3:5 proportion settings and the privileged user changes the settings to 4:1:5with setAimedPropotion() . Since the total reserved assets are not changed before or after the setAimedPropotion() operation, the trigger() function has no effect to re-balance the proportion (i.e., reserveMin <= reserve <= reserveMax ), leading to the amount of principle being incompatible to the aimed proportion settings until the next deposit or withdrawal. 18/30 PeckShield Audit Report #: 2020-03Confidential 3.7 Insufficient Validation to Target Handler •ID: PVE-007 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Dispatcher.sol •Category: Error Conditions, Return Val- ues, Status Codes [14] •CWE subcategory: CWE-391 [5] Description Whileaddinganewtargethandler,wenoticedthatDIP001validatesthe _targetHandlerAddr bycalling thegetTargetAddress() to ensure that the contract has the corresponding interface implemented (line 329). However, the validation is insufficient here. For example, if the contract is set to be controlled by a malicious owner, the assets deposited into it could be in risks. 319 function addTargetHandler ( address _targetHandlerAddr , uint256 [ ] c a l l d a t a _thPropotion ) external auth returns (bool ) { 320 uint256 length = t h s . length ; 321 uint256 sum = 0 ; 322 uint256 i ; 323 TargetHandler memory _th ; 324 325 for( i = 0 ; i < length ; ++i ) { 326 _th = t h s [ i ] ; 327 require ( _th . t a r g e t H a n d l e r A d d r != _targetHandlerAddr , " exist target handler " ) ; 328 } 329 t h s . push ( TargetHandler ( _targetHandlerAddr , I T a r g e t H a n d l e r ( _targetHandlerAddr ) . getTargetAddress ( ) , 0) ) ; 330 331 require ( t h s . length == _thPropotion . length ," wrong length " ) ; 332 for( i = 0 ; i < _thPropotion . length ; ++i ) { 333 sum += _thPropotion [ i ] ; 334 } 335 require (sum == 1000 , " the sum of propotion must be 1000 " ) ; 336 for( i = 0 ; i < _thPropotion . length ; ++i ) { 337 _th = t h s [ i ] ; 338 _th . aimedPropotion = _thPropotion [ i ] ; 339 t h s [ i ] = _th ; 340 } 341 return true ; 342 } Listing 3.9: contracts/Dispatcher. sol Recommendation Check the integrity of the target handler to be added. 19/30 PeckShield Audit Report #: 2020-03Confidential 3.8 Redundant Code in Dispatcher •ID: PVE-008 •Severity: Informational •Likelihood: N/A •Impact: N/A•Targets: Dispatcher.sol •Category: Coding Practices [11] •CWE subcategory: CWE-1041 [4] Description The DSMathlibrary is redundant in Dispatcher contract since DSLibrary/DSMath.sol could be included and used directly. 12 l i b r a r y DSMath { 13 function add ( uint x ,uint y )i n t e r n a l pure returns (uint z ) { 14 require ( ( z = x + y ) >= x , "ds -math -add - overflow " ) ; 15 } 16 function sub ( uint x ,uint y )i n t e r n a l pure returns (uint z ) { 17 require ( ( z = x *y ) <= x , "ds -math -sub - underflow " ) ; 18 } 19 function mul ( uint x ,uint y )i n t e r n a l pure returns (uint z ) { 20 require ( y == 0 | | ( z = x ∗y ) / y == x , "ds -math -mul - overflow " ) ; 21 } 22 } Listing 3.10: contracts/Dispatcher. sol 3.9 Optimization Suggestions •ID: PVE-009 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: CompoundHandler.sol •Category: Behavioral Issues [12] •CWE subcategory: CWE-440 [7] Description InCompoundHandler , oneofthetargethandler, the getProfit() functioncouldbeoptimizedbyreducing the calculation in the case _balance == _principle . Specifically, when _balance == _principle , the _amounts in line 99would be 0which means line 100is not necessary. 92 function g e t P r o f i t ( ) public view returns (uint256 ) { 93 uint256 _balance = getBalance ( ) ; 94 uint256 _ p r i n c i p l e = g e t P r i n c i p l e ( ) ; 95 uint256 _unit = I D i s p a t c h e r ( d i s p a t c h e r ) . g e t E x e c u t e U n i t ( ) ; 20/30 PeckShield Audit Report #: 2020-03Confidential 96 i f( _balance < _ p r i n c i p l e ) { 97 return 0 ; 98 }e l s e { 99 uint256 _amounts = sub ( _balance , _ p r i n c i p l e ) ; 100 _amounts = _amounts / _unit ∗_unit ; 101 return _amounts ; 102 } 103 } Listing 3.11: contracts/handlers/CompoundHandler.sol Recommendation Return 0directly when _balance == _principle . 92 function g e t P r o f i t ( ) public view returns (uint256 ) { 93 uint256 _balance = getBalance ( ) ; 94 uint256 _ p r i n c i p l e = g e t P r i n c i p l e ( ) ; 95 uint256 _unit = I D i s p a t c h e r ( d i s p a t c h e r ) . g e t E x e c u t e U n i t ( ) ; 96 i f( _balance <= _ p r i n c i p l e ) { 97 return 0 ; 98 }e l s e { 99 uint256 _amounts = sub ( _balance , _ p r i n c i p l e ) ; 100 _amounts = _amounts / _unit ∗_unit ; 101 return _amounts ; 102 } 103 } Listing 3.12: contracts/handlers/CompoundHandler.sol 3.10 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.4; instead of pragma solidity ^0.5.4; . Moreover, we strongly suggest not to use experimental Solidity features or third-party unaudited libraries. If necessary, refactor current code base to only use stable features or trusted libraries. In case there is an absolute need of leveraging experimental features or integrating external libraries, make necessary contingency plans. Based on the nature of DeFi, some security risks may exist while integrating different DeFi components. Currently, DIP001 integrates Lendf.me [3] and Compound [2], which works smoothly so far. If some new Defi components are needed to be integrated in the future, dForce Network should consider the security risks and the liquidity of them. It would be a good idea to conduct a security assessment before integrating each new component. 21/30 PeckShield Audit Report #: 2020-03Confidential 4 | Conclusion In this audit, we thoroughly analyzed the DIP001 documentation and implementation. The audited system does involve various intricacies in both design and implementation. The current code base is well 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. 22/30 PeckShield Audit Report #: 2020-03Confidential 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 [18, 19, 20, 21, 23]. •Result: Not found •Severity: Critical 23/30 PeckShield Audit Report #: 2020-03Confidential 5.1.5 Reentrancy •Description: Reentrancy [24] 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 24/30 PeckShield Audit Report #: 2020-03Confidential 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 25/30 PeckShield Audit Report #: 2020-03Confidential 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 26/30 PeckShield Audit Report #: 2020-03Confidential 5.3.2 Use Fixed Compiler Version •Description: Use fixed compiler version is better. •Result: Not found •Severity: Low 5.3.3 Make Visibility Level Explicit •Description: Assign explicit visibility specifiers for functions and state variables. •Result: Not found •Severity: Low 5.3.4 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.5 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 27/30 PeckShield Audit Report #: 2020-03Confidential References [1] axic. Enforcing ABI length checks for return data from calls can be breaking. https://github. com/ethereum/solidity/issues/4116. [2] Inc. Compound Labs. Compound. https://compound.finance/. [3] dForce Network. Lendf. https://www.lendf.me. [4] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. html. [5] MITRE. CWE-391: Unchecked Error Condition. https://cwe.mitre.org/data/definitions/391. html. [6] MITRE. CWE-394: Unexpected Status Code or Return Value. https://cwe.mitre.org/data/ definitions/394.html. [7] MITRE. CWE-440: Expected Behavior Violation. https://cwe.mitre.org/data/definitions/440. html. [8] MITRE. CWE-708: Incorrect Ownership Assignment. https://cwe.mitre.org/data/definitions/ 708.html. [9] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. 28/30 PeckShield Audit Report #: 2020-03Confidential [10] MITRE. CWE-920: Improper Restriction of Power Consumption. https://cwe.mitre.org/data/ definitions/920.html. [11] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [12] MITRE. CWE CATEGORY: Behavioral Problems. https://cwe.mitre.org/data/definitions/438. html. [13] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [14] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html. [15] MITRE. CWE CATEGORY: Resource Management Errors. https://cwe.mitre.org/data/ definitions/399.html. [16] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [17] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [18] PeckShield. ALERT: New batchOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018- 10299). https://www.peckshield.com/2018/04/22/batchOverflow/. [19] PeckShield. New burnOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 11239). https://www.peckshield.com/2018/05/18/burnOverflow/. [20] PeckShield. New multiOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 10706). https://www.peckshield.com/2018/05/10/multiOverflow/. [21] PeckShield. New proxyOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018-10376). https://www.peckshield.com/2018/04/25/proxyOverflow/. 29/30 PeckShield Audit Report #: 2020-03Confidential [22] PeckShield. PeckShield Inc. https://www.peckshield.com. [23] PeckShield. Your Tokens Are Mine: A Suspicious Scam Token in A Top Exchange. https: //www.peckshield.com/2018/04/28/transferFlaw/. [24] Solidity. Warnings of Expressions and Control Structures. http://solidity.readthedocs.io/en/ develop/control-structures.html. 30/30 PeckShield Audit Report #: 2020-03
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.1 Problem (one line with code reference) - Misleading Return Code in Dispatcher (Lines: 545-547) - Missing Check before Withdrawing Principle (Lines: 645-647) - Wrong Proportion After Adding/Removing Target Handlers (Lines: 745-747) - Excessive Owner Privileges (Lines: 845-847) 2.2 Fix (one line with code reference) - Misleading Return Code in Dispatcher (Lines: 545-547) - Missing Check before Withdrawing Principle (Lines: 645-647) - Wrong Proportion After Adding/Removing Target Handlers (Lines: 745-747) - Excessive Owner Privileges (Lines: 845-847) Moderate 3.1 Problem (one line with code reference) - Gas Consumption Optimization (Lines: 945-947) - Wrong Proportion After Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 4 Major: 2 Critical: 0 Minor Issues: 2.a Problem: Unchecked external call in function transferFrom(address _from, address _to, uint256 _value) (line 545) 2.b Fix: Add require statement to check the return value of the external call (line 545) 3.a Problem: Unchecked external call in function transferFrom(address _from, address _to, uint256 _value) (line 545) 3.b Fix: Add require statement to check the return value of the external call (line 545) 4.a Problem: Unchecked external call in function transferFrom(address _from, address _to, uint256 _value) (line 545) 4.b Fix: Add require statement to check the return value of the external call (line 545) 5.a Problem: Unchecked external call in function transferFrom(address _from, address _to, uint256 _value) (line 545) 5.b Fix: Add require statement to check the return value of the Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: No issues were found in the audit. Conclusion: The contracts reviewed in this audit are safe and secure.
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./Vesting/IvestingMinimal.sol"; import "./IFO/IFixPriceMinimal.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract DACFactory is Ownable { address public vestingImp; address public saleImp; address[] public vestingClones; address[] public saleClones; event VestingCreated(address indexed vesting, address indexed token); event SaleCreated(address indexed _address, address indexed offeringToken); constructor(address vesting, address sale) { vestingImp = vesting; saleImp = sale; } function createVestingClone ( address token, address admin, uint256 startInDays, uint256 durationInDays, uint256 cliff, uint256 cliffDelayInDays, uint256 exp ) external returns(address clone) { clone = Clones.clone(vestingImp); IvestingMinimal(clone).initialize( token, admin, startInDays, durationInDays, cliff, cliffDelayInDays, exp ); vestingClones.push(clone); emit VestingCreated(clone, token); } function createSaleClone ( address lpToken, address offeringToken, address priceFeed, address admin, uint256 offeringAmount, uint256 price, uint256 startBlock, uint256 endBlock, uint256 harvestBlock ) external returns(address clone) { clone = Clones.clone(saleImp); IMGHPublicOffering(clone).initialize( lpToken, offeringToken, priceFeed, admin, offeringAmount, price, startBlock, endBlock, harvestBlock ); saleClones.push(clone); emit SaleCreated(clone, offeringToken); } function customClone(address implementation) public returns(address clone) { clone = Clones.clone(implementation); } function updateImplementation(address _saleImp, address _vestImp) external onlyOwner { saleImp = _saleImp; vestingImp = _vestImp; } }
Audit Report March, 2022 For QuillA u d i t sContents Scope of Audit Check Vulnerabilities Techniques and Methods Issue Categories Number of security issues per severity. Introduction High Severity Issues 1. Insufficient require checks on the createPool parameters Medium Severity Issues 2. For loop over dynamic array leads to out of gas 3. Staking Token is assumed to be non-malicious 4. Insufficient require checks on cycletoken in updatePool() 5. Insufficient liquidity in the Staking Pool Low Severity Issues 6. Missing error messages 7. Missing zero address check01 01 02 03 03 04 05 05 05 05 06 06 07 08 08 08 8. Insufficient Documentation Provided Informational Issues 9. There is an unused function parameter Functional Tests Automated Tests Closing Summary09 09 09 10 11 1201 audits.quillhash.com The scope of this audit was to analyze and document the Metagamehub smar t contract codebase for quality, security, and correctness.Scope of the Audit We have scanned the smart contract for commonly known and more specific vuln erabilities. Here are some of the commonly known vuln erabilities 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 level MetaGameHub - Audit Report QuillA u d i t s02 audits.quillhash.comTechniques and Methods Through out the audit of smart contract, care was taken to ensure: The overall quality of code. Use of best pr actices. Code documentation and comments match logic and expected behaviour. Token distribution and calculations are as per the intended behaviour mentioned in the whitepaper. Implem entation 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 smar t contracts. Structural Analysis In this st ep, we have analysed the design patterns and structure of smart contracts. A thorough check was done to ensure the smart contract is struc tured in a way that will not result in future problems. Static Analysis Static analy sis of smart contracts was done to identify contract vuln erabilities. In this step, a series of automated tools are used to test the secur ity of smar t contracts. Code Review / Manual Analysis Manual analy sis 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 th e one described in the whitepaper. Besides, the results of the automat ed analysis were manually verified. Gas Consumption In this st ep, we have checked the behaviour of smart contracts in produ ction. 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 analy sis, Theo. MetaGameHub - Audit Report QuillA u d i t s03 audits.quillhash.comIssue C ategories Every issue in this report has been assigned to a severity level. There are four le vels of severity, and each of them has been explained below. HighRisk-level Description Medium Low Informational 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. 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 issue s can cause minor impact and or ar e jus t warnings that can remain unfixed for now. It would be better to fix these issue s at some point in the future. These ar e severity issue s that indicate an impr ovement request, a general question, a cosmetic or docum entation error, or a request for information. There is low-to-no impact. Number of issues per se verity OpenType High Closed AcknowledgedLow 0 0 10 400 0 10 30Medium Informa tional MetaGameHub - Audit Report QuillA u d i t s04 audits.quillhash.comIntroduction Between Jan 14, 2022 - Jan 25.2022 - QuillAudits Team performed a secur ity audit for TheDac smart contracts. The code for the audit was taken from following the official link: https://github.com/metagamehub/Tokenomics-Contracts/blob/main/ contracts/Staking/LockedStakingRewards.sol Fixed In: https://github.com/metagamehub/Tokenomics-Contracts/tree/ audit -fix/contracts/Staking V Date Files Commit ID 1 2Jan 14 contracts/* Jan 24 contracts/* f3899d0a31dbb7386eacb7efefbff2ac32ce7cbb 94e2027d9638a64fd1fc95f094975fd6f3b6013b MetaGameHub - Audit Report QuillA u d i t s05 audits.quillhash.comIssues F ound – Code Review / Manual Testing 1. Insufficient require checks on the createPool parameters Descr iption The parameters tokenPerShareMultiplier, cycleDuration, startOfDeposit and tokenPerShare in the constructor and createPool() function do not have an y required checks on their range of values allowed and thus, can be e xploited by the owner. Rem ediation It is a dvised to add proper “require” checks for the above mentioned variables.High severity issues Medium severity issues Status: FixedLine Code 87 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"); } Line Code 45 for (uint256 i = 0; i < _initialPools.length; i++) { createPool(i, _initialPools[i]); }2. For loop over dynamic array leads to out of gas MetaGameHub - Audit Report QuillA u d i t s06 audits.quillhash.com Status: Fixed Status: Fixed Auditor’s comment: The staking token is the MGH token which is a MiniMe Token. The token was audited and its audit report can be found here, https://docs.google.com/document/d/1oxLfheb_w27BtBHVU4J_ 2rb4KK 8kSagnQMifGJkkwkQ/edit?usp=sharing Descr iption There is a for loop used over dynamic array _initialPools in the constructor. Rem ediation It is a dvised to add a “require” check on the length of this array as it can lead to out of gas issue s. 3. 4. Staking Token is assumed to be non-malicious Insufficient require checks on cycletoken in updatePool() Descr iption In th e latest commi t that contains comments, it is added- "We don’t use Reentr ancy Guard here because we only call the stakeToken contract whic h is assum ed to be non-malicious". But there are no proofs given to prove this. Rem ediation It is a dvised that the team provide sufficient details such as any audits don e for this token. Perhaps such assumptions can be dangerous to assum e. Line Code 70 pool[_pool].startOfDeposit += pool[_pool].cycleDuration; MetaGameHub - Audit Report QuillA u d i t s07 audits.quillhash.com Descr iption If a user deposits sa y 50,000 Staking tokens and the owner updates the tokenPerShareMultiplier to 15000, then it is expected that the user will get 50% m ore tokens than he initially deposited. But this sc enario can fail if enough staking tokens are not available in the contract. That is it is expected that the pool has 25,000 additional tokens (75,0000 in total). It is also possible that user s A, B and C each deposit 50,000 tokens and then a fter updating the pool (with tokenPerShareMultiplier set to 15000), user A with draws 75,000, user B withdraws 75,000 and then the user C is not able to withdraw even a single token. Rem ediation Thus it is r equired to add sufficient checks and methods to see that the user s do get the promised returns. Descr iption cycleDuration in the updatePool() function has no checks and thus, startOfDeposit could be updated by a very large or a very small value whic h may lead to unwanted or undiscovered outcomes. Rem ediation It is a dvised to add proper “require” checks for the above mentioned variable. Status: Fixed Clients’ s comment: S ufficient liquidity has been supplied to staking contract Status: Fixed 5. Insufficient liquidity in the Staking Pool Line Code - Across the code MetaGameHub - Audit Report QuillA u d i t s08 audits.quillhash.com6. 7. Missin g Error messages Missin g zero address checkLow severity issues Line Code 51 62 require(stakeToken.transferFrom(_sender, address(this), _amount)); require(stakeToken.transfer(msg.sender, _tokenAmount)); Line Code 36 function receiveApproval ( address _sender, uint256 _amount, address _stakeToken, bytes memory data ) Descr iption There is mi ssing error message in the require statement on lines: 51 and 62 Rem ediation It is a dvised to add appropriate error messages. Descr iption Missin g zero address check for _sender parameter in the receiveAp proval() function. Rem ediation Added a “require” check for checking the zero address for the sender parameter. Status: Fixed Status: Fixed MetaGameHub - Audit Report QuillA u d i t s09 audits.quillhash.comInformational issues Status: Fixed Status: Fixed8. 9. Insufficient documentation provided There is an unused function parameter _stakeToken in the receiveApproval() function. It is advised to make clear as to why this parameter is unused and to remove it if not required. Descr iption There is insufficient documentation provided as to the business logic of the project and the expected implementation of the staking pools. Rem ediation It is a dvised to provide more documentation for the same. MetaGameHub - Audit Report QuillA u d i t s10 audits.quillhash.comFunctional Tests ✅ should be able to create a new pool and set cycleDuration of locking per iod ✅ should able to receive approval, transfer and stake tokens ✅ should be able to update the sharesAmount, unstake and withdraw tokens ✅ should be able to transfer ownership to the production wallet ✅ should be able to update pool and revert if a pool is terminated ✅ should be able to updateTokenPerShareMultiplier when the pool is in tr ansferPhase ✅ should be able to terminate Pool and return the value of the Transfer Phase as w ell. ✅ should be able to return sharesToToken/tokenToShares amount and Pool’s Information ✅ should be able to view the user's token amount. ✅ should revert if cycleDuration is zero or more. ✅ should revert if the withdraw function is called and the pool is locked. ✅ should revert if the user tries to deposit 0 tokens. ✅ should revert if the user tries to update a terminated pool. ✅ should revert if the start of deposit time is not greater than the block’s tim estamp. ✅ should revert if the reward amount is negative. MetaGameHub - Audit Report QuillA u d i t s1 1 audits.quillhash.comAutomated Tests Slith er No major issues w ere found. Some false positive errors were reported by the tool. All the other issue s have been categorized above according to their level of severity Mythril No issues w ere reported by Mythril. MetaGameHub - Audit Report QuillA u d i t s12 audits.quillhash.comClosin g Summary No instan ces of Integer Overflow and Underflow vulnerabilities are found in th e contract. Num erous issue s were discovered during the initial audit. All issues are Fixed by the Auditee. MetaGameHub - Audit Report QuillA u d i t s13 audits.quillhash.comDisc laimer QuillA udits smar t contract audit is not a security warranty, investment advic e, or an endorsement of the Metagamehub. The statements made in this document should not be interpreted as investment or legal advice, nor should its authors be held accountable for decisions ma de based on them. Securing smart contracts is a multistep process. One audit cannot be considered enough. We recommend that the Meta gamehub Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties. MetaGameHub - Audit Report QuillA u d i t sAudit Report March, 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: 6 Moderate: 5 Major: 0 Critical: 0 Minor Issues 2.a Problem: For loop over dynamic array leads to out of gas (Line: 28) 2.b Fix: Use a for-each loop instead (Line: 28) 3.a Problem: Staking Token is assumed to be non-malicious (Line: 34) 3.b Fix: Add a require check to ensure the token is not malicious (Line: 34) 4.a Problem: Insufficient require checks on cycletoken in updatePool() (Line: 40) 4.b Fix: Add a require check to ensure the token is not malicious (Line: 40) 5.a Problem: Insufficient liquidity in the Staking Pool (Line: 46) 5.b Fix: Increase the liquidity of the Staking Pool (Line: 46) 6.a Problem: Missing error messages (Line: 52) 6.b Fix: Add error messages to the code (Line: 52) 7.a Problem: Missing zero address check (Line: 58) 7.b Fix: Add a zero Fix Added require checks on the parameters tokenPerShareMultiplier, cycleDuration, startOfDeposit and tokenPerShare in the constructor and createPool() function. Summary Issues Count of Minor/Moderate/Major/Critical: Minor: 10 Moderate: 30 Major: 0 Critical: 0 Minor Issues: 1. Insufficient require checks on the createPool parameters - Added require checks on the parameters tokenPerShareMultiplier, cycleDuration, startOfDeposit and tokenPerShare in the constructor and createPool() function. Moderate Issues: 1. Major Issues: None Critical Issues: None Observations: Between Jan 14, 2022 - Jan 25.2022, QuillAudits Team performed a security audit for TheDac smart contracts. The code for the audit was taken from the official link: https://github.com/metagamehub/Tokenomics-Contracts/blob/main/contracts/Staking/LockedStakingRewards.sol Conclusion: The audit found 10 minor issues and 30 moderate issues, which were fixed Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 1 Minor Issues: 2.a Problem: For loop over dynamic array leads to out of gas 2.b Fix: Add a “require” check on the length of this array Moderate Issues: 3.a Problem: Staking Token is assumed to be non-malicious 3.b Fix: Provide sufficient details such as any audits done for this token Critical Issues: 5.a Problem: Insufficient require checks on cycletoken in updatePool() 5.b Fix: Add sufficient checks and methods to see that the users do get the promised returns Observations: - The staking token is a MiniMe Token and its audit report can be found at the given link. - If a user deposits a certain amount of Staking tokens and the owner updates the tokenPerShareMultiplier, it is expected that the user will get more tokens than he initially deposited. - cycleDuration in the updatePool() function has no checks and thus, startOfDeposit could be updated by a very large or a very
pragma solidity ^0.4.18; import "./OMIToken.sol"; import "./OMITokenLock.sol"; import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/zeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol"; import "../node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol"; /// @title OMICrowdsale /// @author Mikel Duffy - <mikel@ecomi.com> contract OMICrowdsale is WhitelistedCrowdsale, Pausable { using SafeMath for uint256; /* * Constants */ uint256 constant crowdsaleStartTime = 1530316800; uint256 constant crowdsaleFinishTime = 1538351999; uint256 constant crowdsaleUSDGoal = 44625000; uint256 constant crowdsaleTokenGoal = 362500000*1e18; uint256 constant minimumTokenPurchase = 2500*1e18; uint256 constant maximumTokenPurchase = 1000000*1e18; /* * Storage */ OMIToken public token; OMITokenLock public tokenLock; uint256 currentDiscountAmount; uint256 public totalUSDRaised; uint256 public totalTokensSold; bool public isFinalized = false; mapping(address => uint256) public purchaseRecords; /* * Events */ event RateChanged(uint256 newRate); event USDRaisedUpdated(uint256 newTotal); event CrowdsaleStarted(); event CrowdsaleFinished(); /* * Modifiers */ modifier whenNotFinalized () { require(!isFinalized); _; } /* * Public Functions */ /// @dev Contract constructor sets... function OMICrowdsale ( uint256 _startingRate, address _ETHWallet, address _OMIToken, address _OMITokenLock ) Crowdsale(_startingRate, _ETHWallet, ERC20(_OMIToken)) public { token = OMIToken(_OMIToken); tokenLock = OMITokenLock(_OMITokenLock); rate = _startingRate; } /// @dev Allows the owner to set the current rate for calculating the number of tokens for a purchase. /// @dev An external cron job will fetch the ETH/USD daily average from the cryptocompare API and call this function. function setRate(uint256 _newRate) public onlyOwner whenNotFinalized returns(bool) { require(_newRate > 0); rate = _newRate; RateChanged(rate); return true; } /// @dev Allows the owner to update the total amount of USD raised. T function setUSDRaised(uint256 _total) public onlyOwner whenNotFinalized { require(_total > 0); totalUSDRaised = _total; USDRaisedUpdated(_total); } /// @dev Gets the purchase records for a given address /// @param _beneficiary Tokan purchaser function getPurchaseRecord(address _beneficiary) public view isWhitelisted(_beneficiary) returns(uint256) { return purchaseRecords[_beneficiary]; } /* * Internal Functions */ /// @dev Extend parent behavior to check if current stage should close. Must call super to ensure the enforcement of the whitelist. /// @param _beneficiary Token purchaser /// @param _weiAmount Amount of wei contributed function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); // Crowdsale should not be paused require(!paused); // Crowdsale should not be finalized require(!isFinalized); uint256 _tokenAmount = _getTokenAmount(_weiAmount); // Beneficiary's total should be between the minimum and maximum purchase amounts uint256 _totalPurchased = purchaseRecords[_beneficiary].add(_tokenAmount); require(_totalPurchased >= minimumTokenPurchase); require(_totalPurchased <= maximumTokenPurchase); // Must make the purchase from the intended whitelisted address require(msg.sender == _beneficiary); // Must be after the start time require(now >= crowdsaleStartTime); } /// @dev Overrides parent by storing balances in timelock contract instead of issuing tokens right away. /// @param _beneficiary Token purchaser /// @param _tokenAmount Amount of tokens purchased function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { // Lock beneficiary's tokens uint day = 86400; tokenLock.lockTokens(_beneficiary, day.mul(7), _tokenAmount); } /// @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) /// @param _beneficiary Address receiving the tokens /// @param _weiAmount Value in wei involved in the purchase function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { uint256 _tokenAmount = _getTokenAmount(_weiAmount); // Add token amount to the purchase history purchaseRecords[_beneficiary] = purchaseRecords[_beneficiary].add(_tokenAmount); // Add token amount to total tokens sold totalTokensSold = totalTokensSold.add(_tokenAmount); // Finish the crowdsale... // ...if there is not a minimum purchase left if (crowdsaleTokenGoal.sub(totalTokensSold) < minimumTokenPurchase) { _finalization(); } // ...if USD funding goal has been reached if (totalUSDRaised >= crowdsaleUSDGoal) { _finalization(); } // ...if the time is after the crowdsale end time if (now > crowdsaleFinishTime) { _finalization(); } } /// @dev Finalizes crowdsale function _finalization() internal whenNotFinalized { isFinalized = true; tokenLock.finishCrowdsale(); CrowdsaleFinished(); } } pragma solidity ^0.4.18; import "../node_modules/zeppelin-solidity/contracts/token/ERC20/CappedToken.sol"; import "../node_modules/zeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; contract OMIToken is CappedToken, PausableToken { string public constant name = "Ecomi Token"; string public constant symbol = "OMI"; uint256 public decimals = 18; function OMIToken() public CappedToken(1000000000*1e18) {} }// SWC-Outdated Compiler Version: L2 pragma solidity ^0.4.17; 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 "./OMIToken.sol"; import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol"; import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol"; import "../node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol"; /// @title OMITokenLock /// @author Mikel Duffy - <mikel@ecomi.com> /// @dev OMITokenLock is a token holder contract that will allow multiple beneficiaries to extract the tokens after a given release time. It is a modification of the OpenZeppenlin TokenLock to allow for one token lock smart contract for many beneficiaries. contract OMITokenLock is Ownable, Pausable { using SafeMath for uint256; /* * Storage */ OMIToken public token; address public allowanceProvider; address public crowdsale; bool public crowdsaleFinished = false; uint256 public crowdsaleEndTime; struct Lock { uint256 amount; uint256 lockDuration; bool released; bool revoked; } struct TokenLockVault { address beneficiary; uint256 tokenBalance; uint256 lockIndex; Lock[] locks; } mapping(address => TokenLockVault) public tokenLocks; address[] public lockIndexes; uint256 public totalTokensLocked; /* * Modifiers */ modifier ownerOrCrowdsale () { require(msg.sender == owner || msg.sender == crowdsale); _; } /* * Events */ event LockedTokens(address indexed beneficiary, uint256 amount, uint256 releaseTime); event UnlockedTokens(address indexed beneficiary, uint256 amount); event FinishedCrowdsale(); /* * Public Functions */ /// @dev Constructor function function OMITokenLock (OMIToken _token) public { token = _token; } /// @dev Sets the crowdsale address to allow authorize locking permissions /// @param _crowdsale The address of the crowdsale function setCrowdsaleAddress (address _crowdsale) public onlyOwner returns (bool) { crowdsale = _crowdsale; return true; } /// @dev Sets the token allowance provider address /// @param _allowanceProvider The address of the token allowance provider function setAllowanceAddress (address _allowanceProvider) public onlyOwner returns (bool) { allowanceProvider = _allowanceProvider; return true; } /// @dev Marks the crowdsale as being finished and sets the crowdsale finish date function finishCrowdsale() public ownerOrCrowdsale whenNotPaused { require(!crowdsaleFinished); crowdsaleFinished = true; crowdsaleEndTime = now; FinishedCrowdsale(); } /// @dev Gets the total amount of tokens for a given address /// @param _beneficiary The address for which to look up the total token amount function getTokenBalance(address _beneficiary) public view returns (uint) { return tokenLocks[_beneficiary].tokenBalance; } /// @dev Gets the total number of locks for a given address /// @param _beneficiary The address for which to look up the total number of locks function getNumberOfLocks(address _beneficiary) public view returns (uint) { return tokenLocks[_beneficiary].locks.length; } /// @dev Gets the lock at a given index for a given address /// @param _beneficiary The address used to look up the lock /// @param _lockIndex The index used to look up the lock function getLockByIndex(address _beneficiary, uint256 _lockIndex) public view returns (uint256 amount, uint256 lockDuration, bool released, bool revoked) { require(_lockIndex >= 0); require(_lockIndex <= tokenLocks[_beneficiary].locks.length.sub(1)); return ( tokenLocks[_beneficiary].locks[_lockIndex].amount, tokenLocks[_beneficiary].locks[_lockIndex].lockDuration, tokenLocks[_beneficiary].locks[_lockIndex].released, tokenLocks[_beneficiary].locks[_lockIndex].revoked ); } /// @dev Revokes the lock at a given index for a given address /// @param _beneficiary The address used to look up the lock /// @param _lockIndex The lock index to be revoked function revokeLockByIndex(address _beneficiary, uint256 _lockIndex) public onlyOwner returns (bool) { require(_lockIndex >= 0); require(_lockIndex <= tokenLocks[_beneficiary].locks.length.sub(1)); require(!tokenLocks[_beneficiary].locks[_lockIndex].revoked); tokenLocks[_beneficiary].locks[_lockIndex].revoked = true; return true; } /// @dev Locks tokens for a given beneficiary /// @param _beneficiary The address to which the tokens will be released /// @param _lockDuration The duration of time that must elapse after the crowdsale end date /// @param _tokens The amount of tokens to be locked function lockTokens(address _beneficiary, uint256 _lockDuration, uint256 _tokens) external ownerOrCrowdsale whenNotPaused { // Lock duration must be greater than zero seconds require(_lockDuration >= 0); // Token amount must be greater than zero require(_tokens > 0); // Token Lock must have a sufficient allowance prior to creating locks uint256 tokenAllowance = token.allowance(allowanceProvider, address(this)); require(_tokens.add(totalTokensLocked) <= tokenAllowance); TokenLockVault storage lock = tokenLocks[_beneficiary]; // If this is the first lock for this beneficiary, add their address to the lock indexes if (lock.beneficiary == 0) { lock.beneficiary = _beneficiary; lock.lockIndex = lockIndexes.length; lockIndexes.push(_beneficiary); } // Add the lock lock.locks.push(Lock(_tokens, _lockDuration, false, false)); // Update the total tokens for this beneficiary lock.tokenBalance = lock.tokenBalance.add(_tokens); // Update the number of locked tokens totalTokensLocked = _tokens.add(totalTokensLocked); LockedTokens(_beneficiary, _tokens, _lockDuration); } /// @dev Transfers any tokens held in a timelock vault to beneficiary if they are due for release. function releaseTokens() public whenNotPaused returns(bool) { require(crowdsaleFinished); require(_release(msg.sender)); return true; } /// @dev Transfers tokens held by timelock to all beneficiaries within the provided range. /// @param _from the start lock index /// @param _to the end lock index function releaseAll(uint256 _from, uint256 _to) external whenNotPaused onlyOwner returns (bool) { require(_from >= 0); require(_from < _to); require(_to <= lockIndexes.length); require(crowdsaleFinished); for (uint256 i = _from; i < _to; i = i.add(1)) { address _beneficiary = lockIndexes[i]; //Skip any previously removed locks if (_beneficiary == 0x0) { continue; } require(_release(_beneficiary)); } return true; } /* * Internal Functions */ /// @dev Reviews and releases token for a given beneficiary /// @param _beneficiary address for which a token release should be attempted function _release(address _beneficiary) internal whenNotPaused returns (bool) { TokenLockVault memory lock = tokenLocks[_beneficiary]; require(lock.beneficiary == _beneficiary); bool hasUnDueLocks = false; bool hasReleasedToken = false; for (uint256 i = 0; i < lock.locks.length; i = i.add(1)) { Lock memory currentLock = lock.locks[i]; // Skip any locks which are already released or revoked if (currentLock.released || currentLock.revoked) { continue; } // Skip any locks that are not due for release if (crowdsaleEndTime.add(currentLock.lockDuration) >= now) { hasUnDueLocks = true; continue; } // The amount of tokens to transfer must be less than the number of locked tokens require(currentLock.amount <= token.allowance(allowanceProvider, address(this))); // Release Tokens UnlockedTokens(msg.sender, currentLock.amount); hasReleasedToken = true; tokenLocks[_beneficiary].locks[i].released = true; tokenLocks[_beneficiary].tokenBalance = tokenLocks[_beneficiary].tokenBalance.sub(currentLock.amount); totalTokensLocked = totalTokensLocked.sub(currentLock.amount); assert(token.transferFrom(allowanceProvider, msg.sender, currentLock.amount)); } // If there are no future locks to be released, delete the lock vault if (!hasUnDueLocks) { delete tokenLocks[msg.sender]; lockIndexes[lock.lockIndex] = 0x0; } return hasReleasedToken; } }
6/30/2022 tge-contract-audit/readme.md at audit · BlockchainLabsNZ/tge-contract-audit · GitHub https://github.com/BlockchainLabsNZ/tge-contract-audit/blob/audit/audit/readme.md 1/7BlockchainLabsNZ /tge-contract-audit Public forked from Ecomi-Ecosystem/tge-contract tge-contract-audit / audit / readme.mdCode Issues Pull requests Actions Projects Wiki Security Insights audit Ecomi T oken Sale contracts Audit R eport Prepared by: Alex Tikonoff, alexf@blockchainlabs.nz Matt Lough, matt@blockchainlabs.nz Report: June 06, 2018 – date of delivery June 27, 2018 – last report update Preamble This audit report was undertaken by BlockchainLabs.nz for the purpose of providing feedback to Ecomi . It has subsequently been shared publicly without any express or implied warranty. Solidity contracts were sourced from GitHub 17b96f We would encourage all community members and token holders to make their own assessment of the contracts.224 lines (142 sloc) 10.9 KB6/30/2022 tge-contract-audit/readme.md at audit · BlockchainLabsNZ/tge-contract-audit · GitHub https://github.com/BlockchainLabsNZ/tge-contract-audit/blob/audit/audit/readme.md 2/7Scope The following contracts were subject for static analysis: OMICrowdsale.sol OMIT oken.sol OMIT okenLock.sol Framework used This project is using openzeppelin-solidity v1.8.0 , which is not the latest version and lacks some of the useful features of latest Solidity releases, such as constructors, reverting reasons and emitting events. Repository "zeppelin-solidity" was renamed to "openzeppelin-solidity" in May, 2018. If y uses yarn to install dependencies, the changes in the contracts "import" statements are required, since yarn distinguishe these repos and import paths from the contract ton't be found. On the contrary, npm warns about this situation, but installs old "zeppelin-solidity" repository, so no extra actions are required. No original OpenZeppelin Solidity framework contracts were changed. Issues Severity Description MinorA defect that does not have a material impact on the contract execution and is likely to be subjective. ModerateA 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. Minor6/30/2022 tge-contract-audit/readme.md at audit · BlockchainLabsNZ/tge-contract-audit · GitHub https://github.com/BlockchainLabsNZ/tge-contract-audit/blob/audit/audit/readme.md 3/7Contract defining variables are not defined by default best practices There is no check that tokenAllowance, allowanceProvider, crowdsale are valid. Consider addi them to the contract constructor. View on GitHub Fixed: 81daf7 Old Solidity version best practices The current Solidity release version is 0.4.24. The project is using 0.4.18, which lacks some of the useful features of latest releases, such as constructors, reverting reasons and emitting events. View on GitHub Fixed: d32b56 Zeppelin Solidity framework was renamed testability Repository "zeppelin-solidity" was renamed to the "openzeppelin-solidity" in May, 2018. If y uses yarn to install dependencies, the changes in the contracts "import" statements are required, since yarn distinguish these repos and import paths from the contract won't be found. View on GitHub Fixed: 81daf7 Unnecessary limits checking correctness for (uint256 i = 0; i < lock.locks.length; i = i.add(1)) { – There is no r to use SafeMath.sol lab in this case since there is limits check already presented when checking ; i < lock.locks.lenght ; View on GitHub Fixed: 75103c require() vs. modifiers best practices require(!isFinalized); These lines use aapproach which is different to the rest of project with whenNotPaused and whenNotFinalized modifiers in the same contract. View on GitHub Fixed: 1f3837 Solidity variables should be used instead of hardcoded numbers best practice uint day = 86400; tokenLock.lockTokens(_beneficiary, day.mul(7), _tokenAmount); could be changed to tokenLock.lockTokens(_beneficiary, 1 weeks, _tokenAmount); View on GitHub Fixed: 3053fd6/30/2022 tge-contract-audit/readme.md at audit · BlockchainLabsNZ/tge-contract-audit · GitHub https://github.com/BlockchainLabsNZ/tge-contract-audit/blob/audit/audit/readme.md 4/7Moderate Multiple reverting correctness If require(_release(_beneficiary)) fails by some reason, releaseAll() function will also fail. It could be better to log failed release and continue the loop. View on GitHub Fixed. The logic was moved to the web. Any address could be used as Crowdsale or AllowanceProvider addresses correctness Consider validati that crowdsale contract is an actual crowdsale contract, not just an address. View on GitHub Fixed: 81daf7 Finalization crowdsale could be incomplete correctness The Crowdsale _finalization() is an internal function and could be called only that lines 166, 170, 174. But, _updatePurchasingState() could be called only from buyToken() from Crowdsale.sol. That means if there are not enough purchases, the developers will be forced to buy their tokens themselves. View on GitHub Fixed: 2c1c3 Variables assigned when it's possible to avoid them and thus save the gas gas optimisation Bariables that used not more than once could be removed in order to save on gas. View on GitHub Fixed: 1c2a01 function setCrowdsaleAddress (address _crowdsale) public onlyOwner returns (bool) { crowdsale = _crowdsale; return true; } 6/30/2022 tge-contract-audit/readme.md at audit · BlockchainLabsNZ/tge-contract-audit · GitHub https://github.com/BlockchainLabsNZ/tge-contract-audit/blob/audit/audit/readme.md 5/7Major None found Critical Token transfer to the wrong account correctness The transferFrom() fsends tokens to the msg.sender, which is ok if the internal function _release() called from public function releaseToken(). But when _release() icalled from the releaseAll(), then msg.sender is an owner (not the actual beneficiary) and the token will be transferred to that owner's (contract) account. View on GitHub Fixed: 8393fd Observations No real token transfers TockenLock contract does not transfer tokens during the Sale. All tokens are virtually deposited to the Lock contract and could be transferred to the customers after 7 days after the Sale is finished. The process of sending tokens is possible only when particular AllowanceProvider Contract has that tokens on its balance. That contract is not under audit, so we can not grant that AllowanceProvider will have required amount of tokens to distribute to buyers. Exchange rate updated from outside The token exchange rate is a subject to external changes and could be set by tContract Owner to any value. W e encourage customers to check the rate thoroughly before buying. WhitelistedCrowdsale.sol Only whitelisted accounts allowed to check the token purchases from its own and other accounts, but Ethereum blockchain is transparent to everyone and anyone could check token purchases history for this project.6/30/2022 tge-contract-audit/readme.md at audit · BlockchainLabsNZ/tge-contract-audit · GitHub https://github.com/BlockchainLabsNZ/tge-contract-audit/blob/audit/audit/readme.md 6/7Nevertheless, WhitelistedCrowdsale.sol contract modifier isWhitelisted was used, just once and just to restrict purchase histoy check. Latest Solidity versions benefits are not used It is possible to use emit and constructor keywords, to increase readability but that is up to authors, use them or not. Functions state mutability can be restricted to pure Sfunctions can be marked explicitly with pure attribute to clarify that they do not change anything on the blockchain. Conclusion The developers demonstrated an understanding of Solidity and smart contracts. They were receptive to the feedback provided to help improve the robustness of the contracts. We took part in carefully reviewing all source code provided Overall we consider the resulting contracts following the audit feedback period adequate and any potential vulnerabilities have now been fully resolved. These contract has a low level risk of ETH and OMI being hacked or stolen from the inspected contracts. ___ Disclaimer Our team uses our current understanding of the best practises for Solidity and Smart Contracts. Development in Solidity and for Blockchain is an emerging area of software engineering which still has a lot of room to grow, hence our current understanding of best practices 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 encourage all users interacting with smart contract code to continue to analyse and inform themselves of any risks before interacting with any smart contracts.6/30/2022 tge-contract-audit/readme.md at audit · BlockchainLabsNZ/tge-contract-audit · GitHub https://github.com/BlockchainLabsNZ/tge-contract-audit/blob/audit/audit/readme.md 7/7
Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem: Contract defining variables are not defined by default best practices 2.b Fix: Fixed: 81daf7 Issues Count of Minor/Moderate/Major/Critical: Minor: 3 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Zeppelin Solidity framework was renamed testability 2.b Fix: d32b56 3.a Problem: Unnecessary limits checking correctness 3.b Fix: 81daf7 4.a Problem: require() vs. modifiers best practices 4.b Fix: 75103c Moderate Issues: 5.a Problem: Solidity variables should be used instead of hardcoded numbers best practice 5.b Fix: 1f3837 6.a Problem: Any address could be used as Crowdsale or AllowanceProvider addresses correctness 6.b Fix: 81daf7 Major Issues: None Critical Issues: None Observations: The project is using 0.4.18, which lacks some of the useful features of latest releases, such as constructors, reverting reasons and emitting events. Conclusion: The audit found 3 minor issues, 2 moderate issues and no major or critical issues. The issues were related to testability, correctness, best Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 1 - Critical: 1 Major - Problem: None found - Fix: None found Critical - Problem: Token transfer to the wrong account correctness - Fix: Fixed: 8393fd - The transferFrom() sends tokens to the msg.sender, which is ok if the internal function _release() called from public function releaseToken(). But when _release() is called from the releaseAll(), then msg.sender is an owner (not the actual beneficiary) and the token will be transferred to that owner's (contract) account. Observations - No real token transfers - TokenLock contract does not transfer tokens during the Sale. All tokens are virtually deposited to the Lock contract and could be transferred to the customers after 7 days after the Sale is finished. - The process of sending tokens is possible only when particular AllowanceProvider Contract has that tokens on its balance. - Exchange rate updated from outside - The token exchange rate is a subject to external changes and could be set by tContract Owner to any value. We encourage customers to check the rate thoroughly before buying
pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only // Note: For some reason Migrations.sol needs to be in the root or they run everytime contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { require(msg.sender == owner); _; } constructor() { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address newAddress) public restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(last_completed_migration); } }
Rocketpool Rocketpool Date Date April 2021 Lead Auditor Lead Auditor Dominik Muhs Co-auditors Co-auditors Martin Ortner, David Oz Kashi 1 Executive Summary 1 Executive Summary This report presents the results of our engagement with Rocket Pool Rocket Pool to review the smart the smart contract system contract system , the go language bindings the go language bindings for smart contract interaction, and the Smart Smart Node Node implementation. The review was conducted over five weeks, from March 8, 2021 March 8, 2021 to April 9, 2021 April 9, 2021 . A total of 40 person-days were spent. Due to the audit’s extend, covering more than 6000 solidity source lines of code (ca 3.5k normalized) with 47 logic contracts in a complex smart contract system. A Golang implementation of a RocketPool node application consuming the smart contracts, the results represented with this report are to be interpreted as a best effort best effort review given the broad scope and time-boxed nature of this engagement. Technical documentation other than inline source code or blog posts was not available for this review. It is highly recommended that technical documentation and a precise specification for the main components that comprise the system be created. For example, a security documentation that outlines risks and potential threats to the system, technical system, and design documentation that outlines the main components and how they interact, in what places value is stored, and how to safely upgrade/migrate parts of the system. Furthermore, diagrams for high-level interaction flows and outlines that describe the essential workings of the main components (Settings, Vault, Node Management, Minipools and Staking, Rewards, User Staking, Auctions, DAO Member responsibilities, Oracle functionality, DAO proposals, and risks). Ultimately, it is paramount that before the system goes live, the team establishes incident response readiness, having worst-case scenarios and risks assessed, and risk mitigation and incident treatment playbooks prepared. 1.1 Timeline 1.1 Timeline During the first week, the assessment team spent time understanding the system, map the attack surface, and explore potential high-risk areas. The assessment team split up the efforts with one part of the team investigating the off-chain components and mapping thesmart contract system. The second week was spent assessing the smart contract system (vault, storage, tokens, general view on node management) and the interaction with the off-chain elements. After a one-week hiatus, the assessment team continued to assess the node- and minipool- management functionality in the smart contract system and the high-level interaction with the various custom tokens in the system. The fourth week continued with reviewing tokens/rewards/auctions and transitioned into reviewing the DAO implementation. Given the limited time available for this review and the amount of findings listed in this report, combined with the sparse availability of documentation it is suggested that further security reviews be conducted. Update: 27 May 20201 - Mitigations The report was updated to reflect mitigations implemented for the findings. An additional 5 person days (in the week of May 24 - May 27) were spent to conduct the review, focusing on reviewing the changes that were implemented addressing the specific findings. As with every project that undergoes significant changes it is recommended to conduct a complete re- assessment of the changed system. 2 Scope 2 Scope Commit Hash Commit Hash Repository Repository 44cbf038b97abffa91058cebb2f604220 996e641 https://github.com/rocket-pool/rocketpool/tree/v2.5- Tokenomics-updates 439f0a2e0db7110fef424361a49df2a0b 3cb1a5c https://github.com/rocket-pool/rocketpool-go/tree/v2.5- Tokenomics 7a71915bdb443efbe3d2179d0f6e9cf61 f56083e https://github.com/rocket-pool/smartnode/tree/v2.5- Tokenomics 2.1 Objectives 2.1 Objectives Together with the Rocket Pool 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 the Smart Contract Weakness Classification Registry . 3 . Identify security vulnerabilities in the off-chain components 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 system under review. Please refer to Section 4 - Security Specification for a security-centric view on the system.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 values in the `getVaultData` function (contracts/vault/Vault.sol#L717) 2.b Fix (one line with code reference): Check return values in the `getVaultData` function (contracts/vault/Vault.sol#L717) 3.a Problem (one line with code reference): Unchecked return values in the `getVaultData` function (contracts/vault/Vault.sol#L717) 3.b Fix (one line with code reference): Check return values in the `getVaultData` function (contracts/vault/Vault.sol#L717) 4.a Problem (one line with code reference): Unchecked return values in the `getVaultData` function (contracts/vault/Vault.sol#L717) 4.b Fix (one line with code reference): Check return Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unchecked return values in the RocketPoolVault contract (line 545) 2.b Fix: Added a check for the return value (line 545) 3.a Problem: Unchecked return values in the RocketPoolVault contract (line 545) 3.b Fix: Added a check for the return value (line 545) 4.a Problem: Unchecked return values in the RocketPoolVault contract (line 545) 4.b Fix: Added a check for the return value (line 545) 5.a Problem: Unchecked return values in the RocketPoolVault contract (line 545) 5.b Fix: Added a check for the return value (line 545) Observations: The assessment team identified a number of issues in the system, including unchecked return values in the RocketPoolVault contract, lack of input validation, and lack of documentation. Conclusion: The assessment team concluded that further security reviews should be conducted
// contracts/SuperRareToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; contract Migrations { address public owner; uint256 public lastCompletedMigration; constructor() { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) { _; } } function setCompleted(uint256 _completed) public restricted { lastCompletedMigration = _completed; } function upgrade(address _newAddress) public restricted { Migrations upgraded = Migrations(_newAddress); upgraded.setCompleted(lastCompletedMigration); } } // contracts/InitializableV2.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * Wrapper around OpenZeppelin's Initializable contract. * Exposes initialized state management to ensure logic contract functions cannot be called before initialization. * This is needed because OZ's Initializable contract no longer exposes initialized state variable. * https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol */ contract InitializableV2 is Initializable { bool private isInitialized; string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized"; /** * @notice wrapper function around parent contract Initializable's `initializable` modifier * initializable modifier ensures this function can only be called once by each deployed child contract * sets isInitialized flag to true to which is used by _requireIsInitialized() */ function initialize() public initializer virtual { isInitialized = true; } /** * @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure * contract is initialized before functions can be called. */ function _requireIsInitialized() internal view { require(isInitialized == true, ERROR_NOT_INITIALIZED); } /** * @notice Exposes isInitialized bool var to child contracts with read-only access */ function _isInitialized() internal view returns (bool) { return isInitialized; } }
August 26th 2021— Quantstamp Verified SuperRare Token This smart contract audit was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type ERC-20 Token and its Airdrop Auditors Mohsen Ahmadvand , Senior Research EngineerPoming Lee , Research EngineerJoseph Xu , Technical R&D AdvisorTimeline 2021-05-19 through 2021-06-15 EVM Berlin Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification None Documentation Quality Low Test Quality Low Source Code Repository Commit rarest-token (initial audit) 8c5abd3 rarest-token (re-audit) 50bafc8 Total Issues 6 (4 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 1 (1 Resolved)Informational Risk Issues 3 (1 Resolved)Undetermined Risk Issues 2 (2 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 FindingsNo High or Medium severity issues were detected in our audit. There is one Low severity issue pertaining to input parameter validations. Three informational issues and two undetermined threats were identified. The SuperRare contract enables the contract owner to mint an unlimited amount of tokens to arbitrary addresses. This resembles a centralisation of power and therefore it has to be explicitly communicated with the platform users. Furthermore, the documentation and test coverage need to be improved. ID Description Severity Status QSP- 1 Missing Checks If Important Parameters Are Non-Zero Low Fixed QSP- 2 Privileged Roles and Ownership Informational Acknowledged QSP- 3 Unlocked Pragma Informational Fixed QSP- 4 Allowance Double-Spend Exploit Informational Acknowledged QSP- 5 Tokens Can Potentially Get Locked in the Airdrop Contract Undetermined Fixed QSP- 6 Potentially Zero-Addressed Retrieved Contracts 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 . Setup Tool Setup: v0.6.6 • SlitherSteps taken to run the tools: Installed the Slither tool: Run Slither from the project directory: pip install slither-analyzer slither . Findings QSP-1 Missing Checks If Important Parameters Are Non-ZeroSeverity: Low Risk Fixed Status: , File(s) affected: contracts/claim/SuperRareTokenMerkleDrop.sol contracts/erc20/SuperRareToken.sol : does not check if and are non-zero. : does not check if is non-zero. Description:contracts/claim/SuperRareTokenMerkleDrop.sol constructor superRareToken merkleRoot contracts/erc20/SuperRareToken.sol init _owner Add relevant checks. Recommendation: QSP-2 Privileged Roles and Ownership Severity: Informational Acknowledged Status: File(s) affected: SuperRareToken.sol Smart contracts will often have some variables to designate the person(s) 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:The SuperRare token deployer address can mint additional tokens to arbitrary addresses without any restriction and can pause all transfers. This easily leads to censorship. Exploit Scenario: We recommend explicitly mentioning the following information in the user-facing documentation: Recommendation: There is no cap on the amount of tokens that can be minted. Contract admins can also update the transfer rules at any moment in time as many times as they want. One possible mitigation strategy on the minting aspect is to allow minting only to a designated time-lock or vesting contract or to include the inflation/distribution mechanism explicitly in the token. The response from the SuperRare team: Update: We’re aware of the optics of allowing admins to mint tokens at will and control if people can transfer them, this will be reflected in our Terms of Service of our platform. QSP-3 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 - Version used: ['>=0.4.24<0.8.0', '>=0.6.0<0.8.0', '>=0.6.2<0.8.0', '^0.7.3'] - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/presets/ERC20PresetMinterPauserUpgradeable.sol#3) - >=0.4.24<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol#4) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20PausableUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol#3) - >=0.6.2<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol#3) - >=0.6.0<0.8.0 (node_modules/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol#3) - ^0.7.3 (contracts/InitializableV2.sol#3) - ^0.7.3 (contracts/Migrations.sol#3) - ^0.7.3 (contracts/claim/SuperRareTokenMerkleDrop.sol#3) - ^0.7.3 (contracts/erc20/SuperRareToken.sol#3) - ^0.7.3 (contracts/registry/Registry.sol#3) 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. Hardhat locks the project to a specific Solidity version but this issue still applies as is very common for projects to re-use contracts from other projects. Recommendation:QSP-4 Allowance Double-Spend Exploit Severity: Informational Acknowledged Status: File(s) affected: SuperRareToken.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 the method 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() The SuperRare team responded with "we will be sure to use the increase/decrease approval on our end and advise others to do the same." Update: QSP-5 Tokens Can Potentially Get Locked in the Airdrop ContractSeverity: Undetermined Fixed Status: File(s) affected: SuperRareTokenMerkleDrop.sol The value in the contract must be guaranteed to be correct before tokens are transferred, otherwise Tokens may get locked in the contract. Description:_merkleRoot SuperRareTokenMerkleDrop.sol Consider including an emergency function for the contract owner to either update the or to recover locked tokens. Recommendation: _merkleRoot With the fix the can update the Merkle root. On a side note, extra indents seem to be introduced to the contract, which needs to be linted. Update: Owner QSP-6 Potentially Zero-Addressed Retrieved Contracts Severity: Undetermined Fixed Status: File(s) affected: Registry.sol The function also counts in the entries whose contract has been removed through function . This leads to address being counted as one version. Moreover, the function can potentially return a zero address when is pointing to an element in the map that is set to zero by the function. Description:getContractVersionCount removeContract 0x0 getContract _version addressStorageHistory removeContract We recommend to adhere to the fail early principle. Revise the logic to ensure that zero addresses can not be returned as a legitimate contract address. Recommendation: The issue was fixed by entirely removing the Registry.sol contract. Update: Automated Analyses Slither In total 119 issues were detected. We analysed those issues and triaged false positives. Except for the first issue (faulty modifier), we believe the rest of short-listed issues are not security relevant. Faulty modifier Modifier Migrations.restricted() (contracts/Migrations.sol#13-17) does not always execute _; or revertReference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-modifier Dead code InitializableV2._isInitialized() (contracts/InitializableV2.sol#39-41) is never used and should be removed Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code Variable naming Parameter Migrations.setCompleted(uint256)._completed (contracts/Migrations.sol#19) is not in mixedCase Parameter Migrations.upgrade(address)._newAddress (contracts/Migrations.sol#23) is not in mixedCase Variable SuperRareTokenMerkleDrop._owner (contracts/claim/SuperRareTokenMerkleDrop.sol#9) is not in mixedCase Variable SuperRareTokenMerkleDrop._merkleRoot (contracts/claim/SuperRareTokenMerkleDrop.sol#10) is not in mixedCase Variable SuperRareTokenMerkleDrop._superRareToken (contracts/claim/SuperRareTokenMerkleDrop.sol#11) is not in mixedCase Variable SuperRareTokenMerkleDrop._claimed (contracts/claim/SuperRareTokenMerkleDrop.sol#12) is not in mixedCase Parameter SuperRareToken.init(address)._owner (contracts/erc20/SuperRareToken.sol#34) is not in mixedCase Variable SuperRareToken.DOMAIN_SEPARATOR (contracts/erc20/SuperRareToken.sol#29) is not in mixedCase Parameter Registry.addContract(bytes32,address)._name (contracts/registry/Registry.sol#53) is not in mixedCase Parameter Registry.addContract(bytes32,address)._address (contracts/registry/Registry.sol#53) is not in mixedCase Parameter Registry.removeContract(bytes32)._name (contracts/registry/Registry.sol#74) is not in mixedCase Parameter Registry.upgradeContract(bytes32,address)._name (contracts/registry/Registry.sol#93) is not in mixedCase Parameter Registry.upgradeContract(bytes32,address)._newAddress (contracts/registry/Registry.sol#93) is not in mixedCase Parameter Registry.getContract(bytes32)._name (contracts/registry/Registry.sol#118) is not in mixedCase Parameter Registry.getContract(bytes32,uint256)._name (contracts/registry/Registry.sol#125) is not in mixedCase Parameter Registry.getContract(bytes32,uint256)._version (contracts/registry/Registry.sol#125) is not in mixedCase Parameter Registry.getContractVersionCount(bytes32)._name (contracts/registry/Registry.sol#143) is not in mixedCase Parameter Registry.setAddress(bytes32,address)._key (contracts/registry/Registry.sol#155) is not in mixedCase Parameter Registry.setAddress(bytes32,address)._value (contracts/registry/Registry.sol#155) is not in mixedCase Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions Gas optimization opportunities setCompleted(uint256) should be declared external: - Migrations.setCompleted(uint256) (contracts/Migrations.sol#19-21) upgrade(address) should be declared external: - Migrations.upgrade(address) (contracts/Migrations.sol#23-26) claim(uint256,bytes32[]) should be declared external: - SuperRareTokenMerkleDrop.claim(uint256,bytes32[]) (contracts/claim/SuperRareTokenMerkleDrop.sol#25-33) init(address) should be declared external: - SuperRareToken.init(address) (contracts/erc20/SuperRareToken.sol#34-65) Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-external INFO:Slither:. analyzed (18 contracts with 75 detectors), 119 result(s) found Adherence to Specification comment on L21 has incorrect calculations. 1 million tokens at 18 decimals is equal to 10^24 base units. Ensure that the comments in the code correspond to the actual implementation. SuperRareToken.solCode Documentation There is no documentation. It is strongly advised to document assumptions, usage, and future plans. Adherence to Best Practices The included tests indicate a low coverage (about ~37%). It is strongly recommended to aim for a 100% test coverage. Test ResultsTest Suite Results SuperRareTokenMerkleDrop ✓ Update Merkle Root ✓ Attempt to Update Merkle Root from Non-Owner Address ✓ Deploy - fail - 0 token Address ✓ Deploy - fail - 0 Merkle Root SuperRareToken ✓ Token init - fail ✓ Token Properties Setup Correctly (41ms) ✓ Token Roles Setup Correctly (60ms) ✓ Token Minting Functionality (92ms) ✓ Token Pausing Functionality (102ms) 9 passing (1s) Code Coverage The implemented tests achieve an overall statement and branch coverage of 36.84 and 36.36, respectively. We strongly advice to develop more tests reaching a 100% coverage. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 12.5 0 14.29 11.11 InitializableV2.sol 33.33 0 33.33 33.33 33,40 Migrations.sol 0 0 0 0 … 15,20,24,25 contracts/ claim/ 36.84 50 33.33 36.84 SuperRareTokenMerkleDrop.sol 36.84 50 33.33 36.84 … 47,48,51,55 contracts/ erc20/ 54.55 33.33 50 58.33 SuperRareToken.sol 54.55 33.33 50 58.33 79,80,87,88,92 All files 36.84 36.36 26.67 37.5 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 51373f620e0355729083e78076380f42fadee79b39dcb714d5da4cb81d0d95e7 ./contracts/Migrations.sol f0e808bd8dea48f176f4fa977f3e418387372e3256b42f7aa5067cd597e280f6 ./contracts/InitializableV2.sol 7aea17f95f57e909eb319f14bbaf67eeab3bc429af0d719050cc5c3f178e5191 ./contracts/claim/SuperRareTokenMerkleDrop.sol c0d270bd6e00cc925eaf9a68fc3e833bf94bb57c71a4270c19e705a91eba88e7 ./contracts/erc20/SuperRareToken.sol Tests 173f97220be7515b14b6dbc2e6009d948c860cbb36b992f97ac1b19a5b70618e ./test/claim/SuperRareTokenMerkleDrop.test.js 949be2edeec22886cded83c80bd948a51349b3a4d874c1bfaf282e6fb97a98b4 ./test/erc20/SuperRareToken.test.js Changelog 2021-05-24 - Initial report •2021-06-15 - Fixes audit (re-audit) •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. SuperRare Token Audit
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 1 - Moderate Issues: 0 - Major Issues: 0 - Critical Issues: 0 Minor Issues - Problem: Lack of input parameter validations - Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues: None Major Issues: None Critical Issues: None Observations - The SuperRare contract enables the contract owner to mint an unlimited amount of tokens to arbitrary addresses. - This resembles a centralisation of power and therefore it has to be explicitly communicated with the platform users. Conclusion No High or Medium severity issues were detected in the audit. There is one Low severity issue pertaining to input parameter validations. Three informational issues and two undetermined threats were identified. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: QSP-1: Missing Checks If Important Parameters Are Non-Zero Problem: Does not check if and are non-zero. Does not check if is non-zero. Fix: Added checks to ensure that and are non-zero and is non-zero. Moderate: None Major: None Critical: None Observations: The audit process followed a routine series of steps, including code review, testing and automated analysis, and best practices review. Conclusion: The audit was successful in identifying and fixing the minor issue of missing checks if important parameters are non-zero. No moderate, major, or critical issues were identified. Issues Count of Minor/Moderate/Major/Critical: No Major/Critical Issues Minor Issues: 2.a Problem: contracts/claim/SuperRareTokenMerkleDrop.sol constructor superRareToken merkleRoot contracts/erc20/SuperRareToken.sol init _owner Add relevant checks. 2.b Fix: QSP-2 Privileged Roles and Ownership Moderate Issues: 3.a Problem: The SuperRare token deployer address can mint additional tokens to arbitrary addresses without any restriction and can pause all transfers. 3.b Fix: Mention the information in the user-facing documentation, allow minting only to a designated time-lock or vesting contract or to include the inflation/distribution mechanism explicitly in the token. Major/Critical Issues: None Observations: 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". Conclusion: The SuperRare team is aware of the optics of allowing admins to mint tokens at will and control if people can transfer them, and this will be reflected in
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/BEP20.sol"; // Dice token with Governance. contract DiceToken is BEP20 { constructor(string memory name, string memory symbol) public BEP20(name, symbol) {} /// @notice Creates _amount token to _to. function mint(address _to, uint256 _amount) external onlyOwner returns(bool) { _mint(_to, _amount); return true; } function burn(address _to, uint256 _amount) external onlyOwner { _burn(_to, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./DiceToken.sol"; import "./libs/IBEP20.sol"; import "./libs/SafeBEP20.sol"; import "./libs/ILuckyChipRouter02.sol"; import "./libs/IMasterChef.sol"; contract Dice is Ownable, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeBEP20 for IBEP20; uint256 public prevBankerAmount; uint256 public bankerAmount; uint256 public netValue; uint256 public currentEpoch; uint256 public playerEndBlock; uint256 public bankerEndBlock; uint256 public totalBonusAmount; uint256 public totalLotteryAmount; uint256 public totalLcLotteryAmount; uint256 public masterChefBonusId; uint256 public intervalBlocks; uint256 public playerTimeBlocks; uint256 public bankerTimeBlocks; uint256 public constant TOTAL_RATE = 10000; // 100% uint256 public gapRate = 500; uint256 public lcBackRate = 1000; // 10% in gap uint256 public bonusRate = 1000; // 10% in gap uint256 public lotteryRate = 100; // 1% in gap uint256 public lcLotteryRate = 50; // 0.5% in gap uint256 public minBetAmount; uint256 public maxBetRatio = 5; uint256 public maxExposureRatio = 300; uint256 public feeAmount; uint256 public maxBankerAmount; address public adminAddress; address public lcAdminAddress; address public masterChefAddress; IBEP20 public token; IBEP20 public lcToken; DiceToken public diceToken; ILuckyChipRouter02 public swapRouter; enum Status { Pending, Open, Lock, Claimable, Expired } struct Round { uint256 startBlock; uint256 lockBlock; uint256 secretSentBlock; bytes32 bankHash; uint256 bankSecret; uint256 totalAmount; uint256 maxBetAmount; uint256[6] betAmounts; uint256 lcBackAmount; uint256 bonusAmount; uint256 swapLcAmount; uint256 betUsers; uint32 finalNumber; Status status; } struct BetInfo { uint256 amount; uint16 numberCount; bool[6] numbers; bool claimed; // default false bool lcClaimed; // default false } struct BankerInfo { uint256 diceTokenAmount; uint256 avgBuyValue; } mapping(uint256 => Round) public rounds; mapping(uint256 => mapping(address => BetInfo)) public ledger; mapping(address => uint256[]) public userRounds; mapping(address => BankerInfo) public bankerInfo; event RatesUpdated(uint256 indexed block, uint256 gapRate, uint256 lcBackRate, uint256 bonusRate, uint256 lotteryRate, uint256 lcLotteryRate); event AmountsUpdated(uint256 indexed block, uint256 minBetAmount, uint256 feeAmount, uint256 maxBankerAmount); event RatiosUpdated(uint256 indexed block, uint256 maxBetRatio, uint256 maxExposureRatio); event StartRound(uint256 indexed epoch, uint256 blockNumber, bytes32 bankHash); event LockRound(uint256 indexed epoch, uint256 blockNumber); event SendSecretRound(uint256 indexed epoch, uint256 blockNumber, uint256 bankSecret, uint32 finalNumber); event BetNumber(address indexed sender, uint256 indexed currentEpoch, bool[6] numbers, uint256 amount); event Claim(address indexed sender, uint256 indexed currentEpoch, uint256 amount); event ClaimBonusLC(address indexed sender, uint256 amount); event ClaimBonus(uint256 amount); event RewardsCalculated(uint256 indexed epoch,uint256 lcbackamount,uint256 bonusamount,uint256 swaplcamount); event SwapRouterUpdated(address indexed router); event EndPlayerTime(uint256 epoch, uint256 blockNumber); event EndBankerTime(uint256 epoch, uint256 blockNumber); event UpdateNetValue(uint256 epoch, uint256 blockNumber, uint256 netValue); event Deposit(address indexed user, uint256 tokenAmount); event Withdraw(address indexed user, uint256 diceTokenAmount); constructor( address _tokenAddress, address _lcTokenAddress, address _diceTokenAddress, address _masterChefAddress, uint256 _masterChefBonusId, uint256 _intervalBlocks, uint256 _playerTimeBlocks, uint256 _bankerTimeBlocks, uint256 _minBetAmount, uint256 _feeAmount, uint256 _maxBankerAmount ) public { token = IBEP20(_tokenAddress); lcToken = IBEP20(_lcTokenAddress); diceToken = DiceToken(_diceTokenAddress); masterChefAddress = _masterChefAddress; masterChefBonusId = _masterChefBonusId; intervalBlocks = _intervalBlocks; playerTimeBlocks = _playerTimeBlocks; bankerTimeBlocks = _bankerTimeBlocks; minBetAmount = _minBetAmount; feeAmount = _feeAmount; maxBankerAmount = _maxBankerAmount; netValue = uint256(1e12); _pause(); } modifier notContract() { require(!_isContract(msg.sender), "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); _; } modifier onlyAdmin() { require(msg.sender == adminAddress, "admin: wut?"); _; } // set blocks function setBlocks(uint256 _intervalBlocks, uint256 _playerTimeBlocks, uint256 _bankerTimeBlocks) external onlyAdmin { intervalBlocks = _intervalBlocks; playerTimeBlocks = _playerTimeBlocks; bankerTimeBlocks = _bankerTimeBlocks; } // set rates function setRates(uint256 _gapRate, uint256 _lcBackRate, uint256 _bonusRate, uint256 _lotteryRate, uint256 _lcLotteryRate) external onlyAdmin { require(_gapRate <= 1000, "gapRate <= 10%"); require(_lcBackRate.add(_bonusRate).add(_lotteryRate).add(_lcLotteryRate) <= TOTAL_RATE, "rateSum <= TOTAL_RATE"); gapRate = _gapRate; lcBackRate = _lcBackRate; bonusRate = _bonusRate; lotteryRate = _lotteryRate; lcLotteryRate = _lcLotteryRate; emit RatesUpdated(block.number, gapRate, lcBackRate, bonusRate, lotteryRate, lcLotteryRate); } // set amounts function setAmounts(uint256 _minBetAmount, uint256 _feeAmount, uint256 _maxBankerAmount) external onlyAdmin { minBetAmount = _minBetAmount; feeAmount = _feeAmount; maxBankerAmount = _maxBankerAmount; emit AmountsUpdated(block.number, minBetAmount, feeAmount, maxBankerAmount); } // set ratios function setRatios(uint256 _maxBetRatio, uint256 _maxExposureRatio) external onlyAdmin { maxBetRatio = _maxBetRatio; maxExposureRatio = _maxExposureRatio; emit RatiosUpdated(block.number, maxBetRatio, maxExposureRatio); } // set admin address function setAdmin(address _adminAddress, address _lcAdminAddress) external onlyOwner { require(_adminAddress != address(0) && _lcAdminAddress != address(0), "Cannot be zero address"); adminAddress = _adminAddress; lcAdminAddress = _lcAdminAddress; } // End banker time function endBankerTime(uint256 epoch, bytes32 bankHash) external onlyAdmin whenPaused { require(epoch == currentEpoch + 1, "epoch == currentEpoch + 1"); require(bankerAmount > 0, "Round can start only when bankerAmount > 0"); prevBankerAmount = bankerAmount; _unpause(); emit EndBankerTime(currentEpoch, block.timestamp); currentEpoch = currentEpoch + 1; _startRound(currentEpoch, bankHash); playerEndBlock = rounds[currentEpoch].startBlock.add(playerTimeBlocks); bankerEndBlock = rounds[currentEpoch].startBlock.add(bankerTimeBlocks); } // Start the next round n, lock for round n-1 function executeRound(uint256 epoch, bytes32 bankHash) external onlyAdmin whenNotPaused{ require(epoch == currentEpoch, "epoch == currentEpoch"); // CurrentEpoch refers to previous round (n-1) lockRound(currentEpoch); // Increment currentEpoch to current round (n) currentEpoch = currentEpoch + 1; _startRound(currentEpoch, bankHash); require(rounds[currentEpoch].startBlock < playerEndBlock, "startBlock < playerEndBlock"); require(rounds[currentEpoch].lockBlock <= playerEndBlock, "lockBlock < playerEndBlock"); } // end player time, triggers banker time function endPlayerTime(uint256 epoch, uint256 bankSecret) external onlyAdmin whenNotPaused{ require(epoch == currentEpoch, "epoch == currentEpoch"); sendSecret(epoch, bankSecret); _pause(); _updateNetValue(epoch); _claimBonusAndLottery(); emit EndPlayerTime(currentEpoch, block.timestamp); } // end player time without caring last round function endPlayerTimeImmediately(uint256 epoch) external onlyAdmin whenNotPaused{ require(epoch == currentEpoch, "epoch == currentEpoch"); _pause(); _updateNetValue(epoch); _claimBonusAndLottery(); emit EndPlayerTime(currentEpoch, block.timestamp); } // update net value function _updateNetValue(uint256 epoch) internal whenPaused{ netValue = netValue.mul(bankerAmount).div(prevBankerAmount); emit UpdateNetValue(epoch, block.timestamp, netValue); } // send bankSecret function sendSecret(uint256 epoch, uint256 bankSecret) public onlyAdmin whenNotPaused{ Round storage round = rounds[epoch]; require(round.lockBlock != 0, "End round after round has locked"); require(round.status == Status.Lock, "End round after round has locked"); require(block.number >= round.lockBlock, "Send secret after lockBlock"); require(block.number <= round.lockBlock.add(intervalBlocks), "Send secret within intervalBlocks"); require(round.bankSecret == 0, "Already revealed"); require(keccak256(abi.encodePacked(bankSecret)) == round.bankHash, "Bank reveal not matching commitment"); _safeSendSecret(epoch, bankSecret); _calculateRewards(epoch); } function _safeSendSecret(uint256 epoch, uint256 bankSecret) internal whenNotPaused { Round storage round = rounds[epoch]; round.secretSentBlock = block.number; round.bankSecret = bankSecret; uint256 random = round.bankSecret ^ round.betUsers ^ block.difficulty; round.finalNumber = uint32(random % 6); round.status = Status.Claimable; emit SendSecretRound(epoch, block.number, bankSecret, round.finalNumber); } // bet number function betNumber(bool[6] calldata numbers, uint256 amount) external payable whenNotPaused notContract nonReentrant { Round storage round = rounds[currentEpoch]; require(msg.value >= feeAmount, "msg.value > feeAmount"); require(round.status == Status.Open, "Round not Open"); require(block.number > round.startBlock && block.number < round.lockBlock, "Round not bettable"); require(ledger[currentEpoch][msg.sender].amount == 0, "Bet once per round"); uint16 numberCount = 0; uint256 maxSingleBetAmount = 0; for (uint32 i = 0; i < 6; i ++) { if (numbers[i]) { numberCount = numberCount + 1; if(round.betAmounts[i] > maxSingleBetAmount){ maxSingleBetAmount = round.betAmounts[i]; } } } require(numberCount > 0, "numberCount > 0"); require(amount >= minBetAmount.mul(uint256(numberCount)), "BetAmount >= minBetAmount * numberCount"); require(amount <= round.maxBetAmount.mul(uint256(numberCount)), "BetAmount <= round.maxBetAmount * numberCount"); if(numberCount == 1){ require(maxSingleBetAmount.add(amount).sub(round.totalAmount.sub(maxSingleBetAmount)) < bankerAmount.mul(maxExposureRatio).div(TOTAL_RATE), 'MaxExposure Limit'); } if (feeAmount > 0){ _safeTransferBNB(adminAddress, feeAmount); } token.safeTransferFrom(address(msg.sender), address(this), amount); // Update round data round.totalAmount = round.totalAmount.add(amount); round.betUsers = round.betUsers.add(1); uint256 betAmount = amount.div(uint256(numberCount)); for (uint32 i = 0; i < 6; i ++) { if (numbers[i]) { round.betAmounts[i] = round.betAmounts[i].add(betAmount); } } // Update user data BetInfo storage betInfo = ledger[currentEpoch][msg.sender]; betInfo.numbers = numbers; betInfo.amount = amount; betInfo.numberCount = numberCount; userRounds[msg.sender].push(currentEpoch); emit BetNumber(msg.sender, currentEpoch, numbers, amount); } // Claim reward function claim(uint256 epoch) external notContract nonReentrant { require(rounds[epoch].startBlock != 0, "Round has not started"); require(block.number > rounds[epoch].lockBlock, "Round has not locked"); require(!ledger[epoch][msg.sender].claimed, "Rewards claimed"); uint256 reward; BetInfo storage betInfo = ledger[epoch][msg.sender]; // Round valid, claim rewards if (rounds[epoch].status == Status.Claimable) { require(claimable(epoch, msg.sender), "Not eligible for claim"); uint256 singleAmount = betInfo.amount.div(uint256(betInfo.numberCount)); reward = singleAmount.mul(5).mul(TOTAL_RATE.sub(gapRate)).div(TOTAL_RATE); reward = reward.add(singleAmount); } // Round invalid, refund bet amount else { require(refundable(epoch, msg.sender), "Not eligible for refund"); reward = ledger[epoch][msg.sender].amount; } betInfo.claimed = true; token.safeTransfer(msg.sender, reward); emit Claim(msg.sender, epoch, reward); } // Claim lc back function claimLcBack(address user) external notContract nonReentrant { (uint256 lcAmount, uint256 startIndex, uint256 endIndex) = pendingLcBack(user); if (lcAmount > 0){ uint256 epoch; for(uint256 i = startIndex; i < endIndex; i ++){ epoch = userRounds[user][i]; ledger[epoch][user].lcClaimed = true; } lcToken.safeTransfer(user, lcAmount); } emit ClaimBonusLC(user, lcAmount); } // View pending lc back function pendingLcBack(address user) public view returns (uint256 lcAmount, uint256 startIndex, uint256 endIndex) { uint256 epoch; uint256 roundLcAmount = 0; lcAmount = 0; startIndex = 0; endIndex = userRounds[user].length; for (uint256 i = userRounds[user].length - 1; i >= 0; i --){ epoch = userRounds[user][i]; BetInfo storage betInfo = ledger[epoch][msg.sender]; if (betInfo.lcClaimed){ startIndex = i.add(1); break; }else{ Round storage round = rounds[epoch]; if (round.status == Status.Claimable){ if (betInfo.numbers[round.finalNumber]){ roundLcAmount = betInfo.amount.div(uint256(betInfo.numberCount)).mul(5).mul(gapRate).div(TOTAL_RATE).mul(lcBackRate).div(TOTAL_RATE); if (betInfo.numberCount > 1){ roundLcAmount = roundLcAmount.add(betInfo.amount.div(uint256(betInfo.numberCount)).mul(uint256(betInfo.numberCount - 1)).mul(gapRate).div(TOTAL_RATE).mul(lcBackRate).div(TOTAL_RATE)); } }else{ roundLcAmount = betInfo.amount.mul(gapRate).div(TOTAL_RATE).mul(lcBackRate).div(TOTAL_RATE); } roundLcAmount = roundLcAmount.mul(round.swapLcAmount).div(round.lcBackAmount); lcAmount = lcAmount.add(roundLcAmount); } } } } // Claim all bonus to masterChef function _claimBonusAndLottery() internal { uint256 tmpAmount = 0; if(totalBonusAmount > 0){ tmpAmount = totalBonusAmount; totalBonusAmount = 0; token.safeTransfer(masterChefAddress, tmpAmount); IMasterChef(masterChefAddress).updateBonus(masterChefBonusId); emit ClaimBonus(tmpAmount); } if(totalLotteryAmount > 0){ tmpAmount = totalLotteryAmount; totalLotteryAmount = 0; token.safeTransfer(adminAddress, tmpAmount); } if(totalLcLotteryAmount > 0){ tmpAmount = totalLcLotteryAmount; totalLcLotteryAmount = 0; token.safeTransfer(lcAdminAddress, tmpAmount); } } // Return round epochs that a user has participated function getUserRounds( address user, uint256 cursor, uint256 size ) external view returns (uint256[] memory, uint256) { uint256 length = size; if (length > userRounds[user].length - cursor) { length = userRounds[user].length - cursor; } uint256[] memory values = new uint256[](length); for (uint256 i = 0; i < length; i++) { values[i] = userRounds[user][cursor.add(i)]; } return (values, cursor.add(length)); } // Get the claimable stats of specific epoch and user account function claimable(uint256 epoch, address user) public view returns (bool) { return (rounds[epoch].status == Status.Claimable) && (ledger[epoch][user].numbers[rounds[epoch].finalNumber]); } // Get the refundable stats of specific epoch and user account function refundable(uint256 epoch, address user) public view returns (bool) { return (rounds[epoch].status != Status.Claimable) && block.number > rounds[epoch].lockBlock.add(intervalBlocks) && ledger[epoch][user].amount != 0; } // Manual Start round. Previous round n-1 must lock function manualStartRound(bytes32 bankHash) external onlyAdmin whenNotPaused { require(block.number >= rounds[currentEpoch].lockBlock, "Manual start new round after current round lock"); currentEpoch = currentEpoch + 1; _startRound(currentEpoch, bankHash); } function _startRound(uint256 epoch, bytes32 bankHash) internal { Round storage round = rounds[epoch]; round.startBlock = block.number; round.lockBlock = block.number.add(intervalBlocks); round.bankHash = bankHash; round.totalAmount = 0; round.maxBetAmount = bankerAmount.mul(maxBetRatio).div(TOTAL_RATE); round.status = Status.Open; emit StartRound(epoch, block.number, bankHash); } // Lock round function lockRound(uint256 epoch) public whenNotPaused { Round storage round = rounds[epoch]; require(round.startBlock != 0, "Lock round after round has started"); require(block.number >= round.lockBlock, "Lock round after lockBlock"); require(block.number <= round.lockBlock.add(intervalBlocks), "Lock round within intervalBlocks"); round.status = Status.Lock; emit LockRound(epoch, block.number); } // Calculate rewards for round function _calculateRewards(uint256 epoch) internal { require(lcBackRate.add(bonusRate) <= TOTAL_RATE, "lcBackRate + bonusRate <= TOTAL_RATE"); require(rounds[epoch].bonusAmount == 0, "Rewards calculated"); Round storage round = rounds[epoch]; { // avoid stack too deep uint256 lcBackAmount = 0; uint256 bonusAmount = 0; uint256 tmpAmount = 0; uint256 gapAmount = 0; uint256 tmpBankerAmount = bankerAmount; for (uint32 i = 0; i < 6; i ++){ if (i == round.finalNumber){ tmpBankerAmount = tmpBankerAmount.sub(round.betAmounts[i].mul(5).mul(TOTAL_RATE.sub(gapRate)).div(TOTAL_RATE)); gapAmount = gapAmount = round.betAmounts[i].mul(5).mul(gapRate).div(TOTAL_RATE); }else{ tmpBankerAmount = tmpBankerAmount.add(round.betAmounts[i]); gapAmount = round.betAmounts[i].mul(gapRate).div(TOTAL_RATE); } tmpAmount = gapAmount.mul(lcBackRate).div(TOTAL_RATE); lcBackAmount = lcBackAmount.add(tmpAmount); tmpBankerAmount = tmpBankerAmount.sub(tmpAmount); tmpAmount = gapAmount.mul(bonusRate).div(TOTAL_RATE); bonusAmount = bonusAmount.add(tmpAmount); tmpBankerAmount = tmpBankerAmount.sub(tmpAmount); } round.lcBackAmount = lcBackAmount; round.bonusAmount = bonusAmount; bankerAmount = tmpBankerAmount; if(address(token) == address(lcToken)){ round.swapLcAmount = lcBackAmount; }else if(address(swapRouter) != address(0)){ address[] memory path = new address[](2); path[0] = address(token); path[1] = address(lcToken); uint256 lcAmout = swapRouter.swapExactTokensForTokens(round.lcBackAmount, 0, path, address(this), block.timestamp + (5 minutes))[1]; round.swapLcAmount = lcAmout; } totalBonusAmount = totalBonusAmount.add(bonusAmount); } { // avoid stack too deep uint256 lotteryAmount = 0; uint256 lcLotteryAmount = 0; uint256 tmpAmount = 0; uint256 gapAmount = 0; uint256 tmpBankerAmount = bankerAmount; for (uint32 i = 0; i < 6; i ++){ if (i == round.finalNumber){ gapAmount = gapAmount = round.betAmounts[i].mul(5).mul(gapRate).div(TOTAL_RATE); }else{ gapAmount = round.betAmounts[i].mul(gapRate).div(TOTAL_RATE); } tmpAmount = gapAmount.mul(lotteryRate).div(TOTAL_RATE); lotteryAmount = lotteryAmount.add(tmpAmount); tmpBankerAmount = tmpBankerAmount.sub(tmpAmount); tmpAmount = gapAmount.mul(lcLotteryRate).div(TOTAL_RATE); lcLotteryAmount = lcLotteryAmount.add(tmpAmount); tmpBankerAmount = tmpBankerAmount.sub(tmpAmount); } bankerAmount = tmpBankerAmount; totalLotteryAmount = totalLotteryAmount.add(lotteryAmount); totalLcLotteryAmount = totalLcLotteryAmount.add(lcLotteryAmount); } emit RewardsCalculated(epoch, round.lcBackAmount, round.bonusAmount, round.swapLcAmount); } // Deposit token to Dice as a banker, get Syrup back. function deposit(uint256 _tokenAmount) public whenPaused nonReentrant notContract { require(_tokenAmount > 0, "Deposit amount > 0"); require(bankerAmount.add(_tokenAmount) < maxBankerAmount, 'maxBankerAmount Limit'); BankerInfo storage banker = bankerInfo[msg.sender]; token.safeTransferFrom(address(msg.sender), address(this), _tokenAmount); uint256 diceTokenAmount = _tokenAmount.mul(1e12).div(netValue); diceToken.mint(address(msg.sender), diceTokenAmount); uint256 totalDiceTokenAmount = banker.diceTokenAmount.add(diceTokenAmount); banker.avgBuyValue = banker.avgBuyValue.mul(banker.diceTokenAmount).div(1e12).add(_tokenAmount).mul(1e12).div(totalDiceTokenAmount); banker.diceTokenAmount = totalDiceTokenAmount; bankerAmount = bankerAmount.add(_tokenAmount); emit Deposit(msg.sender, _tokenAmount); } // Withdraw syrup from dice to get token back function withdraw(uint256 _diceTokenAmount) public whenPaused nonReentrant notContract { require(_diceTokenAmount > 0, "diceTokenAmount > 0"); BankerInfo storage banker = bankerInfo[msg.sender]; banker.diceTokenAmount = banker.diceTokenAmount.sub(_diceTokenAmount); SafeBEP20.safeTransferFrom(diceToken, msg.sender, address(diceToken), _diceTokenAmount); diceToken.burn(address(diceToken), _diceTokenAmount); uint256 tokenAmount = _diceTokenAmount.mul(netValue).div(1e12); bankerAmount = bankerAmount.sub(tokenAmount); token.safeTransfer(address(msg.sender), tokenAmount); emit Withdraw(msg.sender, _diceTokenAmount); } // View function to see banker diceToken Value on frontend. function canWithdrawToken(address bankerAddress) external view returns (uint256){ return bankerInfo[bankerAddress].diceTokenAmount.mul(netValue).div(1e12); } // View function to see banker diceToken Value on frontend. function calProfitRate(address bankerAddress) external view returns (uint256){ return netValue.mul(100).div(bankerInfo[bankerAddress].avgBuyValue); } // Judge address is contract or not function _isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } // Update the swap router. function updateSwapRouter(address _router) external onlyAdmin { require(_router != address(0), "DICE: Invalid router address."); swapRouter = ILuckyChipRouter02(_router); emit SwapRouterUpdated(address(swapRouter)); } function _safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{gas: 23000, value: value}(""); require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); } }
Public SMART CONTRACT AUDIT REPORT for Lucky Dice Prepared By: Yiqun Chen PeckShield September 5, 2021 1/26 PeckShield Audit Report #: 2021-262Public Document Properties Client LuckyChip Title Smart Contract Audit Report Target Lucky Dice Version 1.0 Author Xuxian Jiang Auditors Jing Wang, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 September 5, 2021 Xuxian Jiang Final Release 1.0-rc1 September 1, 2021 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/26 PeckShield Audit Report #: 2021-262Public Contents 1 Introduction 4 1.1 About Lucky Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Predictable Results For Dice Rolling . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 Logic Error For MaxExposure Limit Check . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Improved Validation Of manualStartRound() . . . . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.5 Suggested Event Generation For setAdmin() . . . . . . . . . . . . . . . . . . . . . . 16 3.6 Possible Sandwich/MEV Attacks For Reduced Returns . . . . . . . . . . . . . . . . 17 3.7 Timely massUpdatePools During Pool Weight Changes . . . . . . . . . . . . . . . . 18 3.8 Duplicate Pool/Bonus Detection and Prevention . . . . . . . . . . . . . . . . . . . . 19 3.9 Incompatibility with Deflationary Tokens . . . . . . . . . . . . . . . . . . . . . . . . 21 4 Conclusion 24 References 25 3/26 PeckShield Audit Report #: 2021-262Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the Lucky Dice 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 Lucky Dice LuckyChip is a Defi Casino that everyone can play-to-win and bank-to-earn . Users can participate as PlayerorBankerin the PLAYpart of LuckyChip . In each game, a small amount of betting reward is collected from the winners as Lucky Bonus .Lucky Bonus is the only income of the LuckyChip protocol, and will be totally distributed to all LCbuilders. The first game in the PLAYpart is Lucky Dice . The basic information of audited contracts is as follows: Table 1.1: Basic Information of Lucky Dice ItemDescription Target Lucky Dice TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report September 5, 2021 In the following, we list the reviewed files and the commit hash values used in this audit. •https://github.com/luckychip-io/dice/blob/master/contracts/Dice.sol (70e4405) •https://github.com/luckychip-io/staking/blob/master/contracts/MasterChef.sol (23e5db6) 4/26 PeckShield Audit Report #: 2021-262Public And here are the commit IDs after all fixes for the issues found in the audit have been checked in: •https://github.com/luckychip-io/dice/blob/master/contracts/Dice.sol (de3090c) •https://github.com/luckychip-io/staking/blob/master/contracts/MasterChef.sol (6e43aa1) 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 accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/26 PeckShield Audit Report #: 2021-262Public 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/26 PeckShield Audit Report #: 2021-262Public 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) [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. 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/26 PeckShield Audit Report #: 2021-262Public 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/26 PeckShield Audit Report #: 2021-262Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the Lucky Dice protocol. 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 5 Informational 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/26 PeckShield Audit Report #: 2021-262Public 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, 5low-severity vulnerabilities, and 1informational recommendation. Table 2.1: Key Audit Findings ID Severity Title Category Status PVE-001 High Predictable Results For Dice Rolling Business Logic Fixed PVE-002 Medium Logic Error For MaxExposure Limit Check Business Logic Fixed PVE-003 Low Improved Validation of manual- StartRound()Coding Practices Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated PVE-005 Informational Suggested Event Generation For setAd- min()/setBlocks()Coding Practices Fixed PVE-006 Low Possible Sandwich/MEV Attacks For Re- duced ReturnTime and State Fixed PVE-007 Low Timely massUpdatePools During Pool Weight ChangesBusiness Logic Fixed PVE-008 Low Duplicate Pool/Bonus Detection and Pre- ventionBusiness Logics Fixed PVE-009 Low Incompatibility With Deflationary Tokens Business Logics 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/26 PeckShield Audit Report #: 2021-262Public 3 | Detailed Results 3.1 Predictable Results For Dice Rolling •ID: PVE-001 •Severity: High •Likelihood: Medium •Impact: High•Target: Dice •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description In the Dicecontract, there is an Adminaccount acting as croupier for the game. The Adminplays a critical role in starting/ending a dice rolling round and sending the secretto reveal the dice rolling result. To elaborate, we show below the sendSecret() and _safeSendSecret() routines in the Dice contract. 247 function sendSecret ( uint256 epoch , uint256 bankSecret ) public onlyAdmin whenNotPaused { 248 Round storage round = rounds [ epoch ]; 249 require ( round . lockBlock != 0, " End round after round has locked "); 250 require ( round . status == Status .Lock , "End round after round has locked "); 251 require ( block . number >= round . lockBlock , " Send secret after lockBlock "); 252 require ( block . number <= round . lockBlock . add ( intervalBlocks ), " Send secret within intervalBlocks "); 253 require ( round . bankSecret == 0, " Already revealed "); 254 require ( keccak256 ( abi. encodePacked ( bankSecret )) == round . bankHash , " Bank reveal not matching commitment "); 255 256 _safeSendSecret (epoch , bankSecret ); 257 _calculateRewards ( epoch ); 258 } 259 260 function _safeSendSecret ( uint256 epoch , uint256 bankSecret ) internal whenNotPaused { 261 Round storage round = rounds [ epoch ]; 262 round . secretSentBlock = block . number ; 263 round . bankSecret = bankSecret ; 264 uint256 random = round . bankSecret ^ round . betUsers ^ block . difficulty ; 11/26 PeckShield Audit Report #: 2021-262Public 265 round . finalNumber = uint32 ( random % 6); 266 round . status = Status . Claimable ; 267 268 emit SendSecretRound (epoch , block .number , bankSecret , round . finalNumber ); 269 } Listing 3.1: dice::sendSecret()and dice::_safeSendSecret() Before each round, the Adminwill provide a hashed secretand the value will be stored at round. bankHash. Aftertheroundislocked, the Adminwillsendthe bankSecret bycalling sendSecret() tocheck if the hashed value of bankSecret matches the the stored round.bankHash , and then it would trigger the_safeSendSecret() to reveal the finalNumber . However, if we take a close look at _safeSendSecret (), this specific routine computes the round.finalNumber based on a random number generated from round.bankSecret ^ round.betUsers ^ block.difficulty . Sincethe round.bankSecret isprovidedbythe Admin, the block.difficulty is hard-coded in certain blockchains (e.g. BSC), and the round.betUsers is possibly colluding with Admin, the result for the dice rolling may become predictable. If so, the game will become unfair and Banker’s funds may be be drained round by round as the Adminwould inform the colluding users to bet a maximum amount allowed on the finalNumber . Recommendation Add the block.timestamp to feed the random seed. Status This issue has been fixed in the commit: de3090c. Although there is no real randomness on Ethereum, the change could ensure that the Dice Rolling results are not predictable from the Admin’s side. 3.2 Logic Error For MaxExposure Limit Check •ID: PVE-002 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Dice •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description There are two roles of users in the Lucky Dice contract: Bankerand Player. In Bankertime, the users can bank/unbank certain tokens into the protocol to receive LP tokens. In Playertime, the users can bet on the dice rolling result and claim the betting rewards if they bet on the correct finalNumber . However, since the betting rewards would be 5times the amount of the user’s betting amounts, if we do not limit the user’s betting amounts, the banker may face a big lost and what’s more, the protocol may fail to pay the rewards to the winners. 12/26 PeckShield Audit Report #: 2021-262Public While reviewing the betNumber() routine, we do see there are some logic checks that are in place to constrain the betAmount by checking if the banker’s maxExposureRatio is exceeded (line 292 from betNumber() ). However, there is a missing multiplication of 5for the betAmount so the current limitation may not work properly in preventing above situation. 272 function betNumber ( bool [6] calldata numbers , uint256 amount ) external payable whenNotPaused notContract nonReentrant { 273 Round storage round = rounds [ currentEpoch ]; 274 require ( msg . value >= feeAmount , " msg. value > feeAmount "); 275 require ( round . status == Status .Open , " Round not Open "); 276 require ( block . number > round . startBlock && block . number < round . lockBlock , " Round not bettable "); 277 require ( ledger [ currentEpoch ][ msg . sender ]. amount == 0, " Bet once per round "); 278 uint16 numberCount = 0; 279 uint256 maxSingleBetAmount = 0; 280 for ( uint32 i = 0; i < 6; i ++) { 281 if ( numbers [i]) { 282 numberCount = numberCount + 1; 283 if( round . betAmounts [i] > maxSingleBetAmount ){ 284 maxSingleBetAmount = round . betAmounts [i]; 285 } 286 } 287 } 288 require ( numberCount > 0, " numberCount > 0"); 289 require ( amount >= minBetAmount . mul ( uint256 ( numberCount )), " BetAmount >= minBetAmount * numberCount "); 290 require ( amount <= round . maxBetAmount . mul ( uint256 ( numberCount )), " BetAmount <= round . maxBetAmount * numberCount "); 291 if( numberCount == 1){ 292 require ( maxSingleBetAmount .add ( amount ).sub ( round . totalAmount . sub ( maxSingleBetAmount )) < bankerAmount . mul( maxExposureRatio ). div ( TOTAL_RATE ), ’MaxExposure Limit ’); 293 } 294 ... 295 } Listing 3.2: Dice::betNumber() Recommendation Improved the betNumber() routine to properly check BetAmount against maxExposureRatio . Status This issue has been fixed in the commit: de3090c. 13/26 PeckShield Audit Report #: 2021-262Public 3.3 Improved Validation Of manualStartRound() •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: Dice •Category: Coding Practices [7] •CWE subcategory: CWE-1041 [1] Description In the Dicecontract, there is a public function manualStartRound() which is used by the Adminof the contract to start a new round manually. To elaborate, we show below the related code snippet. 449 function manualStartRound ( bytes32 bankHash ) external onlyAdmin whenNotPaused { 450 require ( block . number >= rounds [ currentEpoch ]. lockBlock , " Manual start new round after current round lock "); 451 currentEpoch = currentEpoch + 1; 452 _startRound ( currentEpoch , bankHash ); 453 } Listing 3.3: Dice::manualStartRound() 207 // Start the next round n, lock for round n -1 208 function executeRound ( uint256 epoch , bytes32 bankHash ) external onlyAdmin whenNotPaused { 209 require ( epoch == currentEpoch , " epoch == currentEpoch "); 210 211 // CurrentEpoch refers to previous round (n -1) 212 lockRound ( currentEpoch ); 213 214 // Increment currentEpoch to current round (n) 215 currentEpoch = currentEpoch + 1; 216 _startRound ( currentEpoch , bankHash ); 217 require ( rounds [ currentEpoch ]. startBlock < playerEndBlock , " startBlock < playerEndBlock "); 218 require ( rounds [ currentEpoch ]. lockBlock <= playerEndBlock , " lockBlock < playerEndBlock "); 219 } Listing 3.4: Dice::executeRound() It comes to our attention that the manualStartRound() function has the inherent assumption that the Player’s time is not ended. However, this is only enforced inside the executeRound() function (line 217). We suggest to add the rounds[currentEpoch].startBlock < playerEndBlock check also in the manualStartRound() function. Recommendation Improve the validation of of manualStartRound() following above suggestion. Status This issue has been fixed in the commit: de3090c. 14/26 PeckShield Audit Report #: 2021-262Public 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Dice •Category: Security Features [6] •CWE subcategory: CWE-287 [2] Description In the Diceprotocol, there is a privileged Adminaccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and game management). 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 setRatios() routine in the Dicecontract. This routine allows the Adminaccount to adjust the maxBetRatio and maxExposureRatio without any limitations. 180 function setRatios ( uint256 _maxBetRatio , uint256 _maxExposureRatio ) external onlyAdmin { 181 maxBetRatio = _maxBetRatio ; 182 maxExposureRatio = _maxExposureRatio ; 183 emit RatiosUpdated ( block . number , maxBetRatio , maxExposureRatio ); 184 } Listing 3.5: Dice::setRatios() We emphasize that the privilege assignments are necessary and required for proper protocol operations. However, it is worrisome if the Adminis not governed by a DAO-like structure. We point out that a compromised Adminaccount would set the value of maxExposureRatio toTOTAL_RATE , which puts the Banker’s funds in big risk. Note that a multi-sig account or adding the maximum limitation of these parameters 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. And add the limitation of maximum value for maxBetRatio and maxExposureRatio . Status This issue has been fixed in the commit: de3090c. 15/26 PeckShield Audit Report #: 2021-262Public 3.5 Suggested Event Generation For setAdmin() •ID: PVE-005 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Dice •Category: Coding Practices [7] •CWE subcategory: CWE-563 [3] 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. While examining the events that reflect the Dicedynamics, we notice there is a lack of emitting an event to reflect adminAddress changes and playerTimeBlocks changes. To elaborate, we show below the related code snippet of the contract. 187 // set admin address 188 function setAdmin ( address _adminAddress , address _lcAdminAddress ) external onlyOwner { 189 require ( _adminAddress != address (0) && _lcAdminAddress != address (0) , " Cannot be zero address "); 190 adminAddress = _adminAddress ; 191 lcAdminAddress = _lcAdminAddress ; 192 } Listing 3.6: Dice::setAdmin() 153 // set blocks 154 function setBlocks ( uint256 _intervalBlocks , uint256 _playerTimeBlocks , uint256 _bankerTimeBlocks ) external onlyAdmin { 155 intervalBlocks = _intervalBlocks ; 156 playerTimeBlocks = _playerTimeBlocks ; 157 bankerTimeBlocks = _bankerTimeBlocks ; 158 } Listing 3.7: Dice::setBlocks() Recommendation Properly emit the above-mentioned events with accurate information to timely reflect state changes. This is very helpful for external analytics and reporting tools. Status This issue has been fixed in the commit: de3090c. 16/26 PeckShield Audit Report #: 2021-262Public 3.6 Possible Sandwich/MEV Attacks For Reduced Returns •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Low•Target: Dice •Category: Time and State [9] •CWE subcategory: CWE-682 [4] Description The Dicecontract has a helper routine, i.e., _calculateRewards() , that is designed to calculate rewards for a round. It has a rather straightforward logic in swapping the tokentolcTokenwhen calculating the lcBackAmount . 478 function _calculateRewards ( uint256 epoch ) internal { 479 require ( lcBackRate .add ( bonusRate ) <= TOTAL_RATE , " lcBackRate + bonusRate <= TOTAL_RATE "); 480 require ( rounds [ epoch ]. bonusAmount == 0, " Rewards calculated "); 481 Round storage round = rounds [ epoch ]; 482 ... 483 if( address ( token ) == address ( lcToken )){ 484 round . swapLcAmount = lcBackAmount ; 485 } else if( address ( swapRouter ) != address (0) ){ 486 address [] memory path = new address [](2) ; 487 path [0] = address ( token ); 488 path [1] = address ( lcToken ); 489 uint256 lcAmout = swapRouter . swapExactTokensForTokens ( round . lcBackAmount , 0, path , address ( this ), block . timestamp + (5 minutes )) [1]; 490 round . swapLcAmount = lcAmout ; 491 } 492 totalBonusAmount = totalBonusAmount . add ( bonusAmount ); 493 ... 494 } Listing 3.8: Dice::_calculateRewards() Toelaborate, weshowabovethe _calculateRewards() routine. Wenoticethetokenswapisrouted toswapRouter and the actual swap operation swapExactTokensForTokens() essentially does not specify any restriction (with amountOutMin=0 ) on possible slippage 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 17/26 PeckShield Audit Report #: 2021-262Public 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 This issue has been fixed in the commit: de3090c. 3.7 Timely massUpdatePools During Pool Weight Changes •ID: PVE-007 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterChef •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description As mentioned in Section 3.6, the Diceprotocol provides incentive mechanisms that reward the staking of supported assets. The rewards are carried out by designating a number of staking pools into which supported assets can be staked. And staking users are rewarded in proportional to their share of LP tokens in the reward pool. The reward pools can be dynamically added via add()and the weights of supported pools can be adjusted via set(). When analyzing the pool weight update routine set(), we notice the need of timely invoking massUpdatePools() to update the reward distribution before the new pool weight becomes effective. 204 // Update the given pool ’s LC allocation point . Can only be called by the owner . 205 function set ( uint256 _pid , uint256 _allocPoint , bool _withUpdate ) public onlyOwner { 206 if ( _withUpdate ) { 207 massUpdatePools (); 208 } 209 totalAllocPoint = totalAllocPoint . sub ( poolInfo [ _pid ]. allocPoint ). add ( _allocPoint ); 210 poolInfo [ _pid ]. allocPoint = _allocPoint ; 211 } Listing 3.9: MasterChef::set() If the call to massUpdatePools() is not immediately invoked before updating the pool weights, certain situations may be crafted to create an unfair reward distribution. Moreover, a hidden pool withoutanyweightcansuddenlysurfacetoclaimunreasonableshareofrewardedtokens. Fortunately, 18/26 PeckShield Audit Report #: 2021-262Public this interface is restricted to the owner (via the onlyOwner modifier), which greatly alleviates the concern. Recommendation Timely invoke massUpdatePools() when any pool’s weight has been updated. In fact, the third parameter ( _withUpdate ) to the set()routine can be simply ignored or removed. 204 // Update the given pool ’s LC allocation point . Can only be called by the owner . 205 function set ( uint256 _pid , uint256 _allocPoint , bool _withUpdate ) public onlyOwner { 206 massUpdatePools (); 207 totalAllocPoint = totalAllocPoint . sub ( poolInfo [ _pid ]. allocPoint ). add ( _allocPoint ); 208 poolInfo [ _pid ]. allocPoint = _allocPoint ; 209 } Listing 3.10: MasterChef::set() Status This issue has been fixed in the commit: 6e43aa1. 3.8 Duplicate Pool/Bonus Detection and Prevention •ID: PVE-008 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterChef •Category: Business Logics [8] •CWE subcategory: CWE-841 [5] Description The MasterChef protocol provides incentive mechanisms that reward the staking of supported assets with certain reward tokens. The rewards are carried out by designating a number of staking pools into which supported assets can be staked. Each pool has its allocPoint*100%/totalAllocPoint share of scheduled rewards and the rewards for stakers are proportional to their share of LP tokens in the pool. In current implementation, there are a number of concurrent pools that share the rewarded tokens and more can be scheduled for addition (via a proper governance procedure). To accommodate these new pools, the design has the necessary mechanism in place that allows for dynamic additions of new staking pools that can participate in being incentivized as well. The addition of a new pool is implemented in add(), whose code logic is shown below. It turns out it did not perform necessary sanity checks in preventing a new pool but with a duplicate token from being added. Though it is a privileged interface (protected with the modifier onlyOwner ), it is still desirable to enforce it at the smart contract code level, eliminating the concern of wrong pool introduction from human omissions. 19/26 PeckShield Audit Report #: 2021-262Public 173 // Add a new lp to the pool . Can only be called by the owner . 174 // XXX DO NOT add the same LP token more than once . Rewards will be messed up if you do. 175 function add ( uint256 _allocPoint , uint256 _bonusPoint , IBEP20 _lpToken , bool _withUpdate ) public onlyOwner { 176 if ( _withUpdate ) { 177 massUpdatePools (); 178 } 179 uint256 lastRewardBlock = block . number > startBlock ? block . number : startBlock ; 180 totalAllocPoint = totalAllocPoint . add ( _allocPoint ); 181 totalBonusPoint = totalBonusPoint . add ( _bonusPoint ); 182 183 poolInfo . push ( 184 PoolInfo ({ 185 lpToken : _lpToken , 186 allocPoint : _allocPoint , 187 bonusPoint : _bonusPoint , 188 lastRewardBlock : lastRewardBlock , 189 accLCPerShare : 0 190 }) 191 ); 192 } Listing 3.11: MasterChef::add() Recommendation Detect whether the given pool for addition is a duplicate of an existing pool. The pool addition is only successful when there is no duplicate. 173 function checkPoolDuplicate ( IBEP20 _lpToken ) public { 174 uint256 length = poolInfo . length ; 175 for ( uint256 pid = 0; pid < length ; ++ pid) { 176 require ( poolInfo [ _pid ]. lpToken != _lpToken , " add: existing pool ?"); 177 } 178 } 179 180 // Add a new lp to the pool . Can only be called by the owner . 181 // XXX DO NOT add the same LP token more than once . Rewards will be messed up if you do. 182 function add ( uint256 _allocPoint , IBEP20 _lpToken , bool _withUpdate ) public onlyOwner { 183 if ( _withUpdate ) { 184 massUpdatePools (); 185 } 186 checkPoolDuplicate ( _lpToken ); 187 uint256 lastRewardBlock = block . number > startBlock ? block . number : startBlock ; 188 totalAllocPoint = totalAllocPoint . add ( _allocPoint ); 189 totalBonusPoint = totalBonusPoint . add ( _bonusPoint ); 190 191 poolInfo . push ( 192 PoolInfo ({ 193 lpToken : _lpToken , 194 allocPoint : _allocPoint , 20/26 PeckShield Audit Report #: 2021-262Public 195 bonusPoint : _bonusPoint , 196 lastRewardBlock : lastRewardBlock , 197 accLCPerShare : 0 198 }) 199 ); 200 } Listing 3.12: Revised MasterChef::add() We point out that if a new pool with a duplicate LP token can be added, it will likely cause a havoc in the distribution of rewards to the pools and the stakers. Note that addBonus() shares the very same issue. Status This issue has been fixed in the commit: 6e43aa1. 3.9 Incompatibility with Deflationary Tokens •ID: PVE-009 •Severity: Low •Likelihood: Low •Impact: Low•Target: MasterChef •Category: Business Logics [8] •CWE subcategory: CWE-841 [5] Description In the LuckyChip protocol, the MasterChef contract is designed to take user’s asset and deliver rewards depending on the user’s 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. 322 function deposit ( uint256 _pid , uint256 _amount , address _referrer ) public nonReentrant { 323 PoolInfo storage pool = poolInfo [ _pid ]; 324 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 325 updatePool ( _pid ); 326 if( _amount > 0 && address ( luckychipReferral ) != address (0) && _referrer != address (0) && _referrer != msg . sender ){ 327 luckychipReferral . recordReferral ( msg . sender , _referrer ); 328 } 329 payPendingLC (_pid , msg . sender ); 330 if ( pool . bonusPoint > 0){ 21/26 PeckShield Audit Report #: 2021-262Public 331 payPendingBonus (_pid , msg . sender ); 332 } 333 if( _amount > 0){ 334 pool . lpToken . safeTransferFrom ( address ( msg. sender ), address ( this ), _amount ); 335 user . amount = user . amount .add ( _amount ); 336 } 337 user . rewardDebt = user . amount .mul ( pool . accLCPerShare ).div (1 e12 ); 338 if ( pool . bonusPoint > 0){ 339 for ( uint256 i = 0; i < bonusInfo . length ; i ++) { 340 userBonusDebt [i][ msg. sender ] = user . amount . mul ( poolBonusPerShare [ _pid ][i]). div (1 e12) ; 341 } 342 } 344 emit Deposit ( msg . sender , _pid , _amount ); 345 } 347 // Withdraw LP tokens from MasterChef . 348 function withdraw ( uint256 _pid , uint256 _amount ) public nonReentrant { 350 PoolInfo storage pool = poolInfo [ _pid ]; 351 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 352 require ( user . amount >= _amount , " withdraw : not good "); 353 updatePool ( _pid ); 354 payPendingLC (_pid , msg . sender ); 355 if ( pool . bonusPoint > 0){ 356 payPendingBonus (_pid , msg . sender ); 357 } 358 if( _amount > 0){ 359 user . amount = user . amount .sub ( _amount ); 360 pool . lpToken . safeTransfer ( address ( msg. sender ), _amount ); 361 } 362 user . rewardDebt = user . amount .mul ( pool . accLCPerShare ).div (1 e12 ); 363 if ( pool . bonusPoint > 0){ 364 for ( uint256 i = 0; i < bonusInfo . length ; i ++) { 365 userBonusDebt [i][ msg. sender ] = user . amount . mul ( poolBonusPerShare [ _pid ][i]). div (1 e12) ; 366 } 367 } 368 emit Withdraw (msg. sender , _pid , _amount ); 369 } Listing 3.13: MasterChef::deposit()and MasterChef::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 or transferFrom. 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 balance inconsistencies when comparing internal asset records with external ERC20 token contracts. Apparently, these balance inconsistencies are damaging to accurate and precise portfolio management 22/26 PeckShield Audit Report #: 2021-262Public of the pool and affects protocol-wide operation and maintenance. Specially, ifwetakealookatthe updatePool() routine. Thisroutinecalculates pool.accLCPerShare via dividing LCReward bylpSupply, where the lpSupply is derived from pool.lpToken.balanceOf(address (this))(line 259). Because the balance inconsistencies of the pool, the lpSupply could be 1Weiand may give a big pool.accLCPerShare as the final result, which dramatically inflates the pool’s reward. 253 // Update reward variables of the given pool to be up -to - date . 254 function updatePool ( uint256 _pid ) public { 255 PoolInfo storage pool = poolInfo [ _pid ]; 256 if ( block . number <= pool . lastRewardBlock ) { 257 return ; 258 } 259 uint256 lpSupply = pool . lpToken . balanceOf ( address ( this )); 260 if ( lpSupply <= 0) { 261 pool . lastRewardBlock = block . number ; 262 return ; 263 } 264 uint256 multiplier = getMultiplier ( pool . lastRewardBlock , block . number ); 265 uint256 LCReward = multiplier .mul ( LCPerBlock ).mul ( pool . allocPoint ). div ( totalAllocPoint ).mul ( stakingPercent ). div( percentDec ); 266 LC. mint ( address ( this ), LCReward ); 267 pool . accLCPerShare = pool . accLCPerShare . add ( LCReward . mul (1 e12 ). div ( lpSupply )); 268 pool . lastRewardBlock = block . number ; 269 } Listing 3.14: MasterChef::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 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. Another mitigation is to regulate the set of ERC20 tokens that are permitted into Lucky Dice for indexing. However, certain existing stable coins may exhibit control switches that can be dynamically exercised to convert into deflationary. Recommendation Checkthebalancebeforeandafterthe safeTransfer() orsafeTransferFrom() call to ensure the book-keeping amount is accurate. An alternative solution is using non-deflationary tokens as collateral but some tokens (e.g., USDT) allow the admin to have the deflationary-like features kicked in later, which should be verified carefully. Status This issue has been confirmed. 23/26 PeckShield Audit Report #: 2021-262Public 4 | Conclusion In this audit, we have analyzed the Lucky Dice design and implementation. The system presents a unique play-to-win ,bank-to-earn Defi Casino on blockchain, where users can participate in as PlayerorBanker. The current code base is clearly organized and those identified issues are promptly confirmed and resolved. 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. 24/26 PeckShield Audit Report #: 2021-262Public 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-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. 25/26 PeckShield Audit Report #: 2021-262Public [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. 26/26 PeckShield Audit Report #: 2021-262
Issues Count of Minor/Moderate/Major/Critical Minor: 3 Moderate: 2 Major: 1 Critical: 0 Minor Issues 2.a Problem (one line with code reference) The function setAdmin() does not emit an event (line 545). 2.b Fix (one line with code reference) Emit an event when setAdmin() is called (line 545). Moderate 3.a Problem (one line with code reference) The function manualStartRound() does not check the current round ID (line 517). 3.b Fix (one line with code reference) Add a check to ensure the current round ID is valid (line 517). Major 4.a Problem (one line with code reference) The function maxExposureLimit() does not check the current round ID (line 517). 4.b Fix (one line with code reference) Add a check to ensure the current round ID is valid (line 517). Observations The Lucky Dice protocol has several issues related to either security or performance. The code can be further improved by addressing the issues identified in this report. Conclusion Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Unchecked return value in the function _withdraw (Lucky Dice.sol#L717) 2.b Fix: Checked return value in the function _withdraw (de3090c) Observations - No major or critical issues were found in the audited contracts. - All issues found were minor and have been fixed. Conclusion The audited contracts have been found to be secure and free of major or critical issues. All minor issues have been fixed. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 4 Major: 3 Critical: 0 Minor Issues: 2.a Problem: Constructor Mismatch (CWE-699) 2.b Fix: Ensure that the constructor is properly defined and called. Moderate Issues: 3.a Problem: Ownership Takeover (CWE-699) 3.b Fix: Ensure that the ownership of the contract is properly managed. 3.c Problem: Redundant Fallback Function (CWE-699) 3.d Fix: Remove redundant fallback functions. 3.e Problem: Overflows & Underflows (CWE-699) 3.f Fix: Ensure that all arithmetic operations are properly checked for overflows and underflows. 3.g Problem: Reentrancy (CWE-699) 3.h Fix: Ensure that all external calls are properly checked for reentrancy. Major Issues: 4.a Problem: Money-Giving Bug (CWE-699) 4.b Fix: Ensure that all external calls are properly checked for money-giving bugs.
// SPDX-License-Identifier: MIT pragma solidity >=0.4.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "./libs/IBEP20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of BEP20 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 {IBEP20-approve}. */ contract LCBEP20 is Context, IBEP20, Ownable { uint256 private constant _maxSupply = 10000000000 * 1e18; using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } function maxSupply() public pure returns (uint256) { return _maxSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance") ); 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(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 {BEP20-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 returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero") ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(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 * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal returns(bool) { require(account != address(0), "BEP20: mint to the zero address"); if (amount.add(_totalSupply) > _maxSupply) { return false; } _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(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 { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance") ); } } // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol // 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. // // Ctrl+f for XXX to see all the modifications. // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/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 = 6 hours; 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; } // XXX: function() external payable { } receive() 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./libs/IBEP20.sol"; import "./libs/SafeBEP20.sol"; import "./libs/ILuckyChipReferral.sol"; import "./libs/IMasterChef.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./LCToken.sol"; // MasterChef is the master of LC. He can make LC and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once LC is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable, ReentrancyGuard, IMasterChef { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of LCs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accLCPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accLCPerShare` (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. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. LCs to distribute per block. uint256 bonusPoint; // How many bonus points assigned to this pool. uint256 lastRewardBlock; // Last block number that LCs distribution occurs. uint256 accLCPerShare; // Accumulated LCs per share, times 1e12. See below. } struct BonusInfo { IBEP20 bonusToken; uint256 lastBalance; uint256 lastRewardBlock; } // The LC TOKEN! LCToken public LC; //Pools, Farms, Dev, Refs percent decimals uint256 public percentDec = 1000000; //Pools and Farms percent from token per block uint256 public stakingPercent; //Developers percent from token per block uint256 public dev0Percent; //Developers percent from token per block uint256 public dev1Percent; //Developers percent from token per block uint256 public dev2Percent; //Safu fund percent from token per block uint256 public safuPercent; // Dev0 address. address public dev0addr; // Dev1 address. address public dev1addr; // Dev2 address. address public dev2addr; // Treasury fund. address public treasuryaddr; // Safu fund. address public safuaddr; // Last block then develeper withdraw dev and ref fee uint256 public lastBlockDevWithdraw; // LC tokens created per block. uint256 public LCPerBlock; // Bonus muliplier for early LC makers. uint256 public BONUS_MULTIPLIER = 1; // Info of each pool. PoolInfo[] public poolInfo; // Info of each bonus. BonusInfo[] public bonusInfo; // mapping pid to bonus accPerShare. mapping(uint256 => uint256[]) public poolBonusPerShare; // user bonus debt mapping(uint256 => mapping(address => uint256)) public userBonusDebt; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // Total bonus poitns. Must be the sum of all bonus points in all pools. uint256 public totalBonusPoint = 0; // The block number when LC mining starts. uint256 public startBlock; // LuckyChip referral contract address. ILuckyChipReferral public luckychipReferral; // Referral commission rate in basis points. uint16 public referralCommissionRate = 100; // Max referral commission rate: 10%. uint16 public constant MAXIMUM_REFERRAL_COMMISSION_RATE = 1000; 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); event EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount); event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount); constructor( LCToken _LC, address _dev0addr, address _dev1addr, address _dev2addr, address _safuaddr, address _treasuryaddr, uint256 _LCPerBlock, uint256 _startBlock, uint256 _stakingPercent, uint256 _dev0Percent, uint256 _dev1Percent, uint256 _dev2Percent, uint256 _safuPercent ) public { LC = _LC; dev0addr = _dev0addr; dev1addr = _dev1addr; dev2addr = _dev2addr; safuaddr = _safuaddr; treasuryaddr = _treasuryaddr; LCPerBlock = _LCPerBlock; startBlock = _startBlock; stakingPercent = _stakingPercent; dev0Percent = _dev0Percent; dev1Percent = _dev1Percent; dev2Percent = _dev2Percent; safuPercent = _safuPercent; lastBlockDevWithdraw = _startBlock; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } function bonusLength() external view returns (uint256) { return bonusInfo.length; } function withdrawDevFee() public{ require(lastBlockDevWithdraw < block.number, 'wait for new block'); uint256 multiplier = getMultiplier(lastBlockDevWithdraw, block.number); uint256 LCReward = multiplier.mul(LCPerBlock); LC.mint(dev0addr, LCReward.mul(dev0Percent).div(percentDec)); LC.mint(dev1addr, LCReward.mul(dev1Percent).div(percentDec)); LC.mint(dev2addr, LCReward.mul(dev2Percent).div(percentDec)); LC.mint(safuaddr, LCReward.mul(safuPercent).div(percentDec)); lastBlockDevWithdraw = block.number; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. // SWC-Code With No Effects: L173 - L190 function add(uint256 _allocPoint, uint256 _bonusPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); totalBonusPoint = totalBonusPoint.add(_bonusPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, bonusPoint: _bonusPoint, lastRewardBlock: lastRewardBlock, accLCPerShare: 0 }) ); } function addBonus(IBEP20 _bonusToken) public onlyOwner { uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; bonusInfo.push(BonusInfo({bonusToken: _bonusToken, lastBalance: 0, lastRewardBlock: lastRewardBlock})); for(uint256 i = 0; i < poolInfo.length; i ++){ PoolInfo storage pool = poolInfo[i]; if (pool.bonusPoint > 0){ poolBonusPerShare[i].push(0); } } } // Update the given pool's LC allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending LCs on frontend. function pendingLC(uint256 _pid, address _user) external view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accLCPerShare = pool.accLCPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 LCReward = multiplier.mul(LCPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec); accLCPerShare = accLCPerShare.add(LCReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accLCPerShare).div(1e12).sub(user.rewardDebt); } // View function to see pending bonus on frontend. function pendingBonus(uint256 _pid, address _user) external view returns (uint256[] memory){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256[] memory values = new uint256[](bonusInfo.length); if (pool.bonusPoint > 0){ for(uint256 i = 0; i < bonusInfo.length; i ++) { values[i] = user.amount.mul(poolBonusPerShare[_pid][i]).div(1e12).sub(userBonusDebt[i][_user]); } } return values; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply <= 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 LCReward = multiplier.mul(LCPerBlock).mul(pool.allocPoint).div(totalAllocPoint).mul(stakingPercent).div(percentDec); LC.mint(address(this), LCReward); pool.accLCPerShare = pool.accLCPerShare.add(LCReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Update bonus function updateBonus(uint256 _pid) external override { require(_pid < bonusInfo.length, "_pid must be less than bonusInfo length"); BonusInfo storage bonusPool = bonusInfo[_pid]; uint256 currentBalance = bonusPool.bonusToken.balanceOf(address(this)); if(currentBalance > bonusPool.lastBalance){ uint256 amount = currentBalance.sub(bonusPool.lastBalance); for(uint256 i = 0; i < poolInfo.length; i ++){ PoolInfo storage pool = poolInfo[i]; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if(lpSupply <= 0){ continue; } if (pool.bonusPoint > 0){ poolBonusPerShare[i][_pid] = poolBonusPerShare[i][_pid].add(amount.mul(pool.bonusPoint).div(totalBonusPoint).mul(1e12).div(lpSupply)); } } bonusPool.lastBalance = currentBalance; bonusPool.lastRewardBlock = block.number; } } // Pay pending LCs. function payPendingLC(uint256 _pid, address _user) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 pending = user.amount.mul(pool.accLCPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { // send rewards safeLCTransfer(_user, pending); payReferralCommission(_user, pending); } } // Pay pending Bonus. function payPendingBonus(uint256 _pid, address _user) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; if (pool.bonusPoint > 0){ require(poolBonusPerShare[_pid].length == bonusInfo.length, "poolBonusPerShare.length must equal to bonusInof length"); for(uint256 i = 0; i < bonusInfo.length; i ++) { uint256 pending = user.amount.mul(poolBonusPerShare[_pid][i]).div(1e12).sub(userBonusDebt[i][_user]); if (pending > 0) { BonusInfo storage bonusPool = bonusInfo[i]; bonusPool.lastBalance = bonusPool.lastBalance.sub(pending); bonusPool.bonusToken.safeTransfer(address(_user), pending); } } } } // Deposit LP tokens to MasterChef for LC allocation. function deposit(uint256 _pid, uint256 _amount, address _referrer) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if(_amount > 0 && address(luckychipReferral) != address(0) && _referrer != address(0) && _referrer != msg.sender){ luckychipReferral.recordReferral(msg.sender, _referrer); } payPendingLC(_pid, msg.sender); if (pool.bonusPoint > 0){ payPendingBonus(_pid, msg.sender); } if(_amount > 0){ pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accLCPerShare).div(1e12); if (pool.bonusPoint > 0){ for(uint256 i = 0; i < bonusInfo.length; i ++) { userBonusDebt[i][msg.sender] = user.amount.mul(poolBonusPerShare[_pid][i]).div(1e12); } } emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); payPendingLC(_pid, msg.sender); if (pool.bonusPoint > 0){ payPendingBonus(_pid, msg.sender); } if(_amount > 0){ user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accLCPerShare).div(1e12); if (pool.bonusPoint > 0){ for(uint256 i = 0; i < bonusInfo.length; i ++) { userBonusDebt[i][msg.sender] = user.amount.mul(poolBonusPerShare[_pid][i]).div(1e12); } } emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; if(pool.bonusPoint > 0){ } } // Safe LC transfer function, just in case if rounding error causes pool to not have enough LCs. function safeLCTransfer(address _to, uint256 _amount) internal { uint256 LCBal = LC.balanceOf(address(this)); if (_amount > LCBal) { LC.transfer(_to, LCBal); } else { LC.transfer(_to, _amount); } } function setDevAddress(address _dev0addr,address _dev1addr,address _dev2addr) public onlyOwner { dev0addr = _dev0addr; dev1addr = _dev1addr; dev2addr = _dev2addr; } function setSafuAddress(address _safuaddr) public onlyOwner{ safuaddr = _safuaddr; } function setTreasuryAddress(address _treasuryaddr) public onlyOwner{ treasuryaddr = _treasuryaddr; } function updateLcPerBlock(uint256 newAmount) public onlyOwner { require(newAmount <= 100 * 1e18, 'Max per block 100 LC'); require(newAmount >= 1 * 1e15, 'Min per block 0.001 LC'); LCPerBlock = newAmount; } // Update referral commission rate by the owner function setReferralCommissionRate(uint16 _referralCommissionRate) public onlyOwner { require(_referralCommissionRate <= MAXIMUM_REFERRAL_COMMISSION_RATE, "setReferralCommissionRate: invalid referral commission rate basis points"); referralCommissionRate = _referralCommissionRate; } // Pay referral commission to the referrer who referred this user. function payReferralCommission(address _user, uint256 _pending) internal { if (referralCommissionRate > 0) { if (address(luckychipReferral) != address(0)){ address referrer = luckychipReferral.getReferrer(_user); uint256 commissionAmount = _pending.mul(referralCommissionRate).div(10000); if (commissionAmount > 0) { if (referrer != address(0)){ LC.mint(referrer, commissionAmount); luckychipReferral.recordReferralCommission(referrer, commissionAmount); emit ReferralCommissionPaid(_user, referrer, commissionAmount); }else{ LC.mint(treasuryaddr, commissionAmount); luckychipReferral.recordReferralCommission(treasuryaddr, commissionAmount); emit ReferralCommissionPaid(_user, treasuryaddr, commissionAmount); } } }else{ uint256 commissionAmount = _pending.mul(referralCommissionRate).div(10000); if (commissionAmount > 0){ LC.mint(treasuryaddr, commissionAmount); emit ReferralCommissionPaid(_user, treasuryaddr, commissionAmount); } } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/IBEP20.sol"; import "./libs/SafeBEP20.sol"; import "./libs/ILuckyChipReferral.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LuckyChipReferral is ILuckyChipReferral, Ownable { using SafeBEP20 for IBEP20; mapping(address => bool) public operators; mapping(address => address) public referrers; // user address => referrer address mapping(address => uint256) public referralsCount; // referrer address => referrals count mapping(address => uint256) public totalReferralCommissions; // referrer address => total referral commissions event ReferralRecorded(address indexed user, address indexed referrer); event ReferralCommissionRecorded(address indexed referrer, uint256 commission); event OperatorUpdated(address indexed operator, bool indexed status); modifier onlyOperator { require(operators[msg.sender], "Operator: caller is not the operator"); _; } function recordReferral(address _user, address _referrer) public override onlyOperator { if (_user != address(0) && _referrer != address(0) && _user != _referrer && referrers[_user] == address(0) ) { referrers[_user] = _referrer; referralsCount[_referrer] += 1; emit ReferralRecorded(_user, _referrer); } } function recordReferralCommission(address _referrer, uint256 _commission) public override onlyOperator { if (_referrer != address(0) && _commission > 0) { totalReferralCommissions[_referrer] += _commission; emit ReferralCommissionRecorded(_referrer, _commission); } } // Get the referrer address that referred the user function getReferrer(address _user) public override view returns (address) { return referrers[_user]; } // Update the status of the operator function updateOperator(address _operator, bool _status) external onlyOwner { operators[_operator] = _status; emit OperatorUpdated(_operator, _status); } // Owner can drain tokens that are sent here by mistake function drainBEP20Token(IBEP20 _token, uint256 _amount, address _to) external onlyOwner { _token.safeTransfer(_to, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./LCBEP20.sol"; // LuckyChip token with Governance. contract LCToken is LCBEP20('LuckyChip', 'LC') { /// @notice Creates `_amount` token to `_to`. function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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 Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { 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 ) external { 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), "LC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "LC::delegateBySig: invalid nonce"); require(now <= expiry, "LC::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 (uint256) { 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) external view returns (uint256) { require(blockNumber < block.number, "LC::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]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying LCs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "LC::_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 getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Public SMART CONTRACT AUDIT REPORT for Lucky Dice Prepared By: Yiqun Chen PeckShield September 5, 2021 1/26 PeckShield Audit Report #: 2021-262Public Document Properties Client LuckyChip Title Smart Contract Audit Report Target Lucky Dice Version 1.0 Author Xuxian Jiang Auditors Jing Wang, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 September 5, 2021 Xuxian Jiang Final Release 1.0-rc1 September 1, 2021 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/26 PeckShield Audit Report #: 2021-262Public Contents 1 Introduction 4 1.1 About Lucky Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Predictable Results For Dice Rolling . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 Logic Error For MaxExposure Limit Check . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Improved Validation Of manualStartRound() . . . . . . . . . . . . . . . . . . . . . . 14 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.5 Suggested Event Generation For setAdmin() . . . . . . . . . . . . . . . . . . . . . . 16 3.6 Possible Sandwich/MEV Attacks For Reduced Returns . . . . . . . . . . . . . . . . 17 3.7 Timely massUpdatePools During Pool Weight Changes . . . . . . . . . . . . . . . . 18 3.8 Duplicate Pool/Bonus Detection and Prevention . . . . . . . . . . . . . . . . . . . . 19 3.9 Incompatibility with Deflationary Tokens . . . . . . . . . . . . . . . . . . . . . . . . 21 4 Conclusion 24 References 25 3/26 PeckShield Audit Report #: 2021-262Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the Lucky Dice 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 Lucky Dice LuckyChip is a Defi Casino that everyone can play-to-win and bank-to-earn . Users can participate as PlayerorBankerin the PLAYpart of LuckyChip . In each game, a small amount of betting reward is collected from the winners as Lucky Bonus .Lucky Bonus is the only income of the LuckyChip protocol, and will be totally distributed to all LCbuilders. The first game in the PLAYpart is Lucky Dice . The basic information of audited contracts is as follows: Table 1.1: Basic Information of Lucky Dice ItemDescription Target Lucky Dice TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report September 5, 2021 In the following, we list the reviewed files and the commit hash values used in this audit. •https://github.com/luckychip-io/dice/blob/master/contracts/Dice.sol (70e4405) •https://github.com/luckychip-io/staking/blob/master/contracts/MasterChef.sol (23e5db6) 4/26 PeckShield Audit Report #: 2021-262Public And here are the commit IDs after all fixes for the issues found in the audit have been checked in: •https://github.com/luckychip-io/dice/blob/master/contracts/Dice.sol (de3090c) •https://github.com/luckychip-io/staking/blob/master/contracts/MasterChef.sol (6e43aa1) 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 accordingly classified into four categories, i.e., Critical,High,Medium,Lowshown in Table 1.2. 5/26 PeckShield Audit Report #: 2021-262Public 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/26 PeckShield Audit Report #: 2021-262Public 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) [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. 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/26 PeckShield Audit Report #: 2021-262Public 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/26 PeckShield Audit Report #: 2021-262Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the Lucky Dice protocol. 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 5 Informational 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/26 PeckShield Audit Report #: 2021-262Public 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, 5low-severity vulnerabilities, and 1informational recommendation. Table 2.1: Key Audit Findings ID Severity Title Category Status PVE-001 High Predictable Results For Dice Rolling Business Logic Fixed PVE-002 Medium Logic Error For MaxExposure Limit Check Business Logic Fixed PVE-003 Low Improved Validation of manual- StartRound()Coding Practices Fixed PVE-004 Medium Trust Issue of Admin Keys Security Features Mitigated PVE-005 Informational Suggested Event Generation For setAd- min()/setBlocks()Coding Practices Fixed PVE-006 Low Possible Sandwich/MEV Attacks For Re- duced ReturnTime and State Fixed PVE-007 Low Timely massUpdatePools During Pool Weight ChangesBusiness Logic Fixed PVE-008 Low Duplicate Pool/Bonus Detection and Pre- ventionBusiness Logics Fixed PVE-009 Low Incompatibility With Deflationary Tokens Business Logics 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/26 PeckShield Audit Report #: 2021-262Public 3 | Detailed Results 3.1 Predictable Results For Dice Rolling •ID: PVE-001 •Severity: High •Likelihood: Medium •Impact: High•Target: Dice •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description In the Dicecontract, there is an Adminaccount acting as croupier for the game. The Adminplays a critical role in starting/ending a dice rolling round and sending the secretto reveal the dice rolling result. To elaborate, we show below the sendSecret() and _safeSendSecret() routines in the Dice contract. 247 function sendSecret ( uint256 epoch , uint256 bankSecret ) public onlyAdmin whenNotPaused { 248 Round storage round = rounds [ epoch ]; 249 require ( round . lockBlock != 0, " End round after round has locked "); 250 require ( round . status == Status .Lock , "End round after round has locked "); 251 require ( block . number >= round . lockBlock , " Send secret after lockBlock "); 252 require ( block . number <= round . lockBlock . add ( intervalBlocks ), " Send secret within intervalBlocks "); 253 require ( round . bankSecret == 0, " Already revealed "); 254 require ( keccak256 ( abi. encodePacked ( bankSecret )) == round . bankHash , " Bank reveal not matching commitment "); 255 256 _safeSendSecret (epoch , bankSecret ); 257 _calculateRewards ( epoch ); 258 } 259 260 function _safeSendSecret ( uint256 epoch , uint256 bankSecret ) internal whenNotPaused { 261 Round storage round = rounds [ epoch ]; 262 round . secretSentBlock = block . number ; 263 round . bankSecret = bankSecret ; 264 uint256 random = round . bankSecret ^ round . betUsers ^ block . difficulty ; 11/26 PeckShield Audit Report #: 2021-262Public 265 round . finalNumber = uint32 ( random % 6); 266 round . status = Status . Claimable ; 267 268 emit SendSecretRound (epoch , block .number , bankSecret , round . finalNumber ); 269 } Listing 3.1: dice::sendSecret()and dice::_safeSendSecret() Before each round, the Adminwill provide a hashed secretand the value will be stored at round. bankHash. Aftertheroundislocked, the Adminwillsendthe bankSecret bycalling sendSecret() tocheck if the hashed value of bankSecret matches the the stored round.bankHash , and then it would trigger the_safeSendSecret() to reveal the finalNumber . However, if we take a close look at _safeSendSecret (), this specific routine computes the round.finalNumber based on a random number generated from round.bankSecret ^ round.betUsers ^ block.difficulty . Sincethe round.bankSecret isprovidedbythe Admin, the block.difficulty is hard-coded in certain blockchains (e.g. BSC), and the round.betUsers is possibly colluding with Admin, the result for the dice rolling may become predictable. If so, the game will become unfair and Banker’s funds may be be drained round by round as the Adminwould inform the colluding users to bet a maximum amount allowed on the finalNumber . Recommendation Add the block.timestamp to feed the random seed. Status This issue has been fixed in the commit: de3090c. Although there is no real randomness on Ethereum, the change could ensure that the Dice Rolling results are not predictable from the Admin’s side. 3.2 Logic Error For MaxExposure Limit Check •ID: PVE-002 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Dice •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description There are two roles of users in the Lucky Dice contract: Bankerand Player. In Bankertime, the users can bank/unbank certain tokens into the protocol to receive LP tokens. In Playertime, the users can bet on the dice rolling result and claim the betting rewards if they bet on the correct finalNumber . However, since the betting rewards would be 5times the amount of the user’s betting amounts, if we do not limit the user’s betting amounts, the banker may face a big lost and what’s more, the protocol may fail to pay the rewards to the winners. 12/26 PeckShield Audit Report #: 2021-262Public While reviewing the betNumber() routine, we do see there are some logic checks that are in place to constrain the betAmount by checking if the banker’s maxExposureRatio is exceeded (line 292 from betNumber() ). However, there is a missing multiplication of 5for the betAmount so the current limitation may not work properly in preventing above situation. 272 function betNumber ( bool [6] calldata numbers , uint256 amount ) external payable whenNotPaused notContract nonReentrant { 273 Round storage round = rounds [ currentEpoch ]; 274 require ( msg . value >= feeAmount , " msg. value > feeAmount "); 275 require ( round . status == Status .Open , " Round not Open "); 276 require ( block . number > round . startBlock && block . number < round . lockBlock , " Round not bettable "); 277 require ( ledger [ currentEpoch ][ msg . sender ]. amount == 0, " Bet once per round "); 278 uint16 numberCount = 0; 279 uint256 maxSingleBetAmount = 0; 280 for ( uint32 i = 0; i < 6; i ++) { 281 if ( numbers [i]) { 282 numberCount = numberCount + 1; 283 if( round . betAmounts [i] > maxSingleBetAmount ){ 284 maxSingleBetAmount = round . betAmounts [i]; 285 } 286 } 287 } 288 require ( numberCount > 0, " numberCount > 0"); 289 require ( amount >= minBetAmount . mul ( uint256 ( numberCount )), " BetAmount >= minBetAmount * numberCount "); 290 require ( amount <= round . maxBetAmount . mul ( uint256 ( numberCount )), " BetAmount <= round . maxBetAmount * numberCount "); 291 if( numberCount == 1){ 292 require ( maxSingleBetAmount .add ( amount ).sub ( round . totalAmount . sub ( maxSingleBetAmount )) < bankerAmount . mul( maxExposureRatio ). div ( TOTAL_RATE ), ’MaxExposure Limit ’); 293 } 294 ... 295 } Listing 3.2: Dice::betNumber() Recommendation Improved the betNumber() routine to properly check BetAmount against maxExposureRatio . Status This issue has been fixed in the commit: de3090c. 13/26 PeckShield Audit Report #: 2021-262Public 3.3 Improved Validation Of manualStartRound() •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: Dice •Category: Coding Practices [7] •CWE subcategory: CWE-1041 [1] Description In the Dicecontract, there is a public function manualStartRound() which is used by the Adminof the contract to start a new round manually. To elaborate, we show below the related code snippet. 449 function manualStartRound ( bytes32 bankHash ) external onlyAdmin whenNotPaused { 450 require ( block . number >= rounds [ currentEpoch ]. lockBlock , " Manual start new round after current round lock "); 451 currentEpoch = currentEpoch + 1; 452 _startRound ( currentEpoch , bankHash ); 453 } Listing 3.3: Dice::manualStartRound() 207 // Start the next round n, lock for round n -1 208 function executeRound ( uint256 epoch , bytes32 bankHash ) external onlyAdmin whenNotPaused { 209 require ( epoch == currentEpoch , " epoch == currentEpoch "); 210 211 // CurrentEpoch refers to previous round (n -1) 212 lockRound ( currentEpoch ); 213 214 // Increment currentEpoch to current round (n) 215 currentEpoch = currentEpoch + 1; 216 _startRound ( currentEpoch , bankHash ); 217 require ( rounds [ currentEpoch ]. startBlock < playerEndBlock , " startBlock < playerEndBlock "); 218 require ( rounds [ currentEpoch ]. lockBlock <= playerEndBlock , " lockBlock < playerEndBlock "); 219 } Listing 3.4: Dice::executeRound() It comes to our attention that the manualStartRound() function has the inherent assumption that the Player’s time is not ended. However, this is only enforced inside the executeRound() function (line 217). We suggest to add the rounds[currentEpoch].startBlock < playerEndBlock check also in the manualStartRound() function. Recommendation Improve the validation of of manualStartRound() following above suggestion. Status This issue has been fixed in the commit: de3090c. 14/26 PeckShield Audit Report #: 2021-262Public 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Dice •Category: Security Features [6] •CWE subcategory: CWE-287 [2] Description In the Diceprotocol, there is a privileged Adminaccount that plays a critical role in governing and regulating the system-wide operations (e.g., parameter setting and game management). 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 setRatios() routine in the Dicecontract. This routine allows the Adminaccount to adjust the maxBetRatio and maxExposureRatio without any limitations. 180 function setRatios ( uint256 _maxBetRatio , uint256 _maxExposureRatio ) external onlyAdmin { 181 maxBetRatio = _maxBetRatio ; 182 maxExposureRatio = _maxExposureRatio ; 183 emit RatiosUpdated ( block . number , maxBetRatio , maxExposureRatio ); 184 } Listing 3.5: Dice::setRatios() We emphasize that the privilege assignments are necessary and required for proper protocol operations. However, it is worrisome if the Adminis not governed by a DAO-like structure. We point out that a compromised Adminaccount would set the value of maxExposureRatio toTOTAL_RATE , which puts the Banker’s funds in big risk. Note that a multi-sig account or adding the maximum limitation of these parameters 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. And add the limitation of maximum value for maxBetRatio and maxExposureRatio . Status This issue has been fixed in the commit: de3090c. 15/26 PeckShield Audit Report #: 2021-262Public 3.5 Suggested Event Generation For setAdmin() •ID: PVE-005 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Dice •Category: Coding Practices [7] •CWE subcategory: CWE-563 [3] 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. While examining the events that reflect the Dicedynamics, we notice there is a lack of emitting an event to reflect adminAddress changes and playerTimeBlocks changes. To elaborate, we show below the related code snippet of the contract. 187 // set admin address 188 function setAdmin ( address _adminAddress , address _lcAdminAddress ) external onlyOwner { 189 require ( _adminAddress != address (0) && _lcAdminAddress != address (0) , " Cannot be zero address "); 190 adminAddress = _adminAddress ; 191 lcAdminAddress = _lcAdminAddress ; 192 } Listing 3.6: Dice::setAdmin() 153 // set blocks 154 function setBlocks ( uint256 _intervalBlocks , uint256 _playerTimeBlocks , uint256 _bankerTimeBlocks ) external onlyAdmin { 155 intervalBlocks = _intervalBlocks ; 156 playerTimeBlocks = _playerTimeBlocks ; 157 bankerTimeBlocks = _bankerTimeBlocks ; 158 } Listing 3.7: Dice::setBlocks() Recommendation Properly emit the above-mentioned events with accurate information to timely reflect state changes. This is very helpful for external analytics and reporting tools. Status This issue has been fixed in the commit: de3090c. 16/26 PeckShield Audit Report #: 2021-262Public 3.6 Possible Sandwich/MEV Attacks For Reduced Returns •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Low•Target: Dice •Category: Time and State [9] •CWE subcategory: CWE-682 [4] Description The Dicecontract has a helper routine, i.e., _calculateRewards() , that is designed to calculate rewards for a round. It has a rather straightforward logic in swapping the tokentolcTokenwhen calculating the lcBackAmount . 478 function _calculateRewards ( uint256 epoch ) internal { 479 require ( lcBackRate .add ( bonusRate ) <= TOTAL_RATE , " lcBackRate + bonusRate <= TOTAL_RATE "); 480 require ( rounds [ epoch ]. bonusAmount == 0, " Rewards calculated "); 481 Round storage round = rounds [ epoch ]; 482 ... 483 if( address ( token ) == address ( lcToken )){ 484 round . swapLcAmount = lcBackAmount ; 485 } else if( address ( swapRouter ) != address (0) ){ 486 address [] memory path = new address [](2) ; 487 path [0] = address ( token ); 488 path [1] = address ( lcToken ); 489 uint256 lcAmout = swapRouter . swapExactTokensForTokens ( round . lcBackAmount , 0, path , address ( this ), block . timestamp + (5 minutes )) [1]; 490 round . swapLcAmount = lcAmout ; 491 } 492 totalBonusAmount = totalBonusAmount . add ( bonusAmount ); 493 ... 494 } Listing 3.8: Dice::_calculateRewards() Toelaborate, weshowabovethe _calculateRewards() routine. Wenoticethetokenswapisrouted toswapRouter and the actual swap operation swapExactTokensForTokens() essentially does not specify any restriction (with amountOutMin=0 ) on possible slippage 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 17/26 PeckShield Audit Report #: 2021-262Public 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 This issue has been fixed in the commit: de3090c. 3.7 Timely massUpdatePools During Pool Weight Changes •ID: PVE-007 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterChef •Category: Business Logic [8] •CWE subcategory: CWE-841 [5] Description As mentioned in Section 3.6, the Diceprotocol provides incentive mechanisms that reward the staking of supported assets. The rewards are carried out by designating a number of staking pools into which supported assets can be staked. And staking users are rewarded in proportional to their share of LP tokens in the reward pool. The reward pools can be dynamically added via add()and the weights of supported pools can be adjusted via set(). When analyzing the pool weight update routine set(), we notice the need of timely invoking massUpdatePools() to update the reward distribution before the new pool weight becomes effective. 204 // Update the given pool ’s LC allocation point . Can only be called by the owner . 205 function set ( uint256 _pid , uint256 _allocPoint , bool _withUpdate ) public onlyOwner { 206 if ( _withUpdate ) { 207 massUpdatePools (); 208 } 209 totalAllocPoint = totalAllocPoint . sub ( poolInfo [ _pid ]. allocPoint ). add ( _allocPoint ); 210 poolInfo [ _pid ]. allocPoint = _allocPoint ; 211 } Listing 3.9: MasterChef::set() If the call to massUpdatePools() is not immediately invoked before updating the pool weights, certain situations may be crafted to create an unfair reward distribution. Moreover, a hidden pool withoutanyweightcansuddenlysurfacetoclaimunreasonableshareofrewardedtokens. Fortunately, 18/26 PeckShield Audit Report #: 2021-262Public this interface is restricted to the owner (via the onlyOwner modifier), which greatly alleviates the concern. Recommendation Timely invoke massUpdatePools() when any pool’s weight has been updated. In fact, the third parameter ( _withUpdate ) to the set()routine can be simply ignored or removed. 204 // Update the given pool ’s LC allocation point . Can only be called by the owner . 205 function set ( uint256 _pid , uint256 _allocPoint , bool _withUpdate ) public onlyOwner { 206 massUpdatePools (); 207 totalAllocPoint = totalAllocPoint . sub ( poolInfo [ _pid ]. allocPoint ). add ( _allocPoint ); 208 poolInfo [ _pid ]. allocPoint = _allocPoint ; 209 } Listing 3.10: MasterChef::set() Status This issue has been fixed in the commit: 6e43aa1. 3.8 Duplicate Pool/Bonus Detection and Prevention •ID: PVE-008 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterChef •Category: Business Logics [8] •CWE subcategory: CWE-841 [5] Description The MasterChef protocol provides incentive mechanisms that reward the staking of supported assets with certain reward tokens. The rewards are carried out by designating a number of staking pools into which supported assets can be staked. Each pool has its allocPoint*100%/totalAllocPoint share of scheduled rewards and the rewards for stakers are proportional to their share of LP tokens in the pool. In current implementation, there are a number of concurrent pools that share the rewarded tokens and more can be scheduled for addition (via a proper governance procedure). To accommodate these new pools, the design has the necessary mechanism in place that allows for dynamic additions of new staking pools that can participate in being incentivized as well. The addition of a new pool is implemented in add(), whose code logic is shown below. It turns out it did not perform necessary sanity checks in preventing a new pool but with a duplicate token from being added. Though it is a privileged interface (protected with the modifier onlyOwner ), it is still desirable to enforce it at the smart contract code level, eliminating the concern of wrong pool introduction from human omissions. 19/26 PeckShield Audit Report #: 2021-262Public 173 // Add a new lp to the pool . Can only be called by the owner . 174 // XXX DO NOT add the same LP token more than once . Rewards will be messed up if you do. 175 function add ( uint256 _allocPoint , uint256 _bonusPoint , IBEP20 _lpToken , bool _withUpdate ) public onlyOwner { 176 if ( _withUpdate ) { 177 massUpdatePools (); 178 } 179 uint256 lastRewardBlock = block . number > startBlock ? block . number : startBlock ; 180 totalAllocPoint = totalAllocPoint . add ( _allocPoint ); 181 totalBonusPoint = totalBonusPoint . add ( _bonusPoint ); 182 183 poolInfo . push ( 184 PoolInfo ({ 185 lpToken : _lpToken , 186 allocPoint : _allocPoint , 187 bonusPoint : _bonusPoint , 188 lastRewardBlock : lastRewardBlock , 189 accLCPerShare : 0 190 }) 191 ); 192 } Listing 3.11: MasterChef::add() Recommendation Detect whether the given pool for addition is a duplicate of an existing pool. The pool addition is only successful when there is no duplicate. 173 function checkPoolDuplicate ( IBEP20 _lpToken ) public { 174 uint256 length = poolInfo . length ; 175 for ( uint256 pid = 0; pid < length ; ++ pid) { 176 require ( poolInfo [ _pid ]. lpToken != _lpToken , " add: existing pool ?"); 177 } 178 } 179 180 // Add a new lp to the pool . Can only be called by the owner . 181 // XXX DO NOT add the same LP token more than once . Rewards will be messed up if you do. 182 function add ( uint256 _allocPoint , IBEP20 _lpToken , bool _withUpdate ) public onlyOwner { 183 if ( _withUpdate ) { 184 massUpdatePools (); 185 } 186 checkPoolDuplicate ( _lpToken ); 187 uint256 lastRewardBlock = block . number > startBlock ? block . number : startBlock ; 188 totalAllocPoint = totalAllocPoint . add ( _allocPoint ); 189 totalBonusPoint = totalBonusPoint . add ( _bonusPoint ); 190 191 poolInfo . push ( 192 PoolInfo ({ 193 lpToken : _lpToken , 194 allocPoint : _allocPoint , 20/26 PeckShield Audit Report #: 2021-262Public 195 bonusPoint : _bonusPoint , 196 lastRewardBlock : lastRewardBlock , 197 accLCPerShare : 0 198 }) 199 ); 200 } Listing 3.12: Revised MasterChef::add() We point out that if a new pool with a duplicate LP token can be added, it will likely cause a havoc in the distribution of rewards to the pools and the stakers. Note that addBonus() shares the very same issue. Status This issue has been fixed in the commit: 6e43aa1. 3.9 Incompatibility with Deflationary Tokens •ID: PVE-009 •Severity: Low •Likelihood: Low •Impact: Low•Target: MasterChef •Category: Business Logics [8] •CWE subcategory: CWE-841 [5] Description In the LuckyChip protocol, the MasterChef contract is designed to take user’s asset and deliver rewards depending on the user’s 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. 322 function deposit ( uint256 _pid , uint256 _amount , address _referrer ) public nonReentrant { 323 PoolInfo storage pool = poolInfo [ _pid ]; 324 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 325 updatePool ( _pid ); 326 if( _amount > 0 && address ( luckychipReferral ) != address (0) && _referrer != address (0) && _referrer != msg . sender ){ 327 luckychipReferral . recordReferral ( msg . sender , _referrer ); 328 } 329 payPendingLC (_pid , msg . sender ); 330 if ( pool . bonusPoint > 0){ 21/26 PeckShield Audit Report #: 2021-262Public 331 payPendingBonus (_pid , msg . sender ); 332 } 333 if( _amount > 0){ 334 pool . lpToken . safeTransferFrom ( address ( msg. sender ), address ( this ), _amount ); 335 user . amount = user . amount .add ( _amount ); 336 } 337 user . rewardDebt = user . amount .mul ( pool . accLCPerShare ).div (1 e12 ); 338 if ( pool . bonusPoint > 0){ 339 for ( uint256 i = 0; i < bonusInfo . length ; i ++) { 340 userBonusDebt [i][ msg. sender ] = user . amount . mul ( poolBonusPerShare [ _pid ][i]). div (1 e12) ; 341 } 342 } 344 emit Deposit ( msg . sender , _pid , _amount ); 345 } 347 // Withdraw LP tokens from MasterChef . 348 function withdraw ( uint256 _pid , uint256 _amount ) public nonReentrant { 350 PoolInfo storage pool = poolInfo [ _pid ]; 351 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 352 require ( user . amount >= _amount , " withdraw : not good "); 353 updatePool ( _pid ); 354 payPendingLC (_pid , msg . sender ); 355 if ( pool . bonusPoint > 0){ 356 payPendingBonus (_pid , msg . sender ); 357 } 358 if( _amount > 0){ 359 user . amount = user . amount .sub ( _amount ); 360 pool . lpToken . safeTransfer ( address ( msg. sender ), _amount ); 361 } 362 user . rewardDebt = user . amount .mul ( pool . accLCPerShare ).div (1 e12 ); 363 if ( pool . bonusPoint > 0){ 364 for ( uint256 i = 0; i < bonusInfo . length ; i ++) { 365 userBonusDebt [i][ msg. sender ] = user . amount . mul ( poolBonusPerShare [ _pid ][i]). div (1 e12) ; 366 } 367 } 368 emit Withdraw (msg. sender , _pid , _amount ); 369 } Listing 3.13: MasterChef::deposit()and MasterChef::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 or transferFrom. 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 balance inconsistencies when comparing internal asset records with external ERC20 token contracts. Apparently, these balance inconsistencies are damaging to accurate and precise portfolio management 22/26 PeckShield Audit Report #: 2021-262Public of the pool and affects protocol-wide operation and maintenance. Specially, ifwetakealookatthe updatePool() routine. Thisroutinecalculates pool.accLCPerShare via dividing LCReward bylpSupply, where the lpSupply is derived from pool.lpToken.balanceOf(address (this))(line 259). Because the balance inconsistencies of the pool, the lpSupply could be 1Weiand may give a big pool.accLCPerShare as the final result, which dramatically inflates the pool’s reward. 253 // Update reward variables of the given pool to be up -to - date . 254 function updatePool ( uint256 _pid ) public { 255 PoolInfo storage pool = poolInfo [ _pid ]; 256 if ( block . number <= pool . lastRewardBlock ) { 257 return ; 258 } 259 uint256 lpSupply = pool . lpToken . balanceOf ( address ( this )); 260 if ( lpSupply <= 0) { 261 pool . lastRewardBlock = block . number ; 262 return ; 263 } 264 uint256 multiplier = getMultiplier ( pool . lastRewardBlock , block . number ); 265 uint256 LCReward = multiplier .mul ( LCPerBlock ).mul ( pool . allocPoint ). div ( totalAllocPoint ).mul ( stakingPercent ). div( percentDec ); 266 LC. mint ( address ( this ), LCReward ); 267 pool . accLCPerShare = pool . accLCPerShare . add ( LCReward . mul (1 e12 ). div ( lpSupply )); 268 pool . lastRewardBlock = block . number ; 269 } Listing 3.14: MasterChef::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 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. Another mitigation is to regulate the set of ERC20 tokens that are permitted into Lucky Dice for indexing. However, certain existing stable coins may exhibit control switches that can be dynamically exercised to convert into deflationary. Recommendation Checkthebalancebeforeandafterthe safeTransfer() orsafeTransferFrom() call to ensure the book-keeping amount is accurate. An alternative solution is using non-deflationary tokens as collateral but some tokens (e.g., USDT) allow the admin to have the deflationary-like features kicked in later, which should be verified carefully. Status This issue has been confirmed. 23/26 PeckShield Audit Report #: 2021-262Public 4 | Conclusion In this audit, we have analyzed the Lucky Dice design and implementation. The system presents a unique play-to-win ,bank-to-earn Defi Casino on blockchain, where users can participate in as PlayerorBanker. The current code base is clearly organized and those identified issues are promptly confirmed and resolved. 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. 24/26 PeckShield Audit Report #: 2021-262Public 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-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. 25/26 PeckShield Audit Report #: 2021-262Public [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. 26/26 PeckShield Audit Report #: 2021-262
Issues Count of Minor/Moderate/Major/Critical Minor: 3 Moderate: 2 Major: 1 Critical: 0 Minor Issues 2.a Problem (one line with code reference) The function setAdmin() does not emit an event (line 545). 2.b Fix (one line with code reference) Emit an event when setAdmin() is called (line 545). Moderate 3.a Problem (one line with code reference) The function manualStartRound() does not check the current round (line 517). 3.b Fix (one line with code reference) Add a check to ensure that the current round is not already started (line 517). Major 4.a Problem (one line with code reference) The function maxExposureLimit() does not check the current round (line 517). 4.b Fix (one line with code reference) Add a check to ensure that the current round is not already started (line 517). Critical None Observations The Lucky Dice protocol has several issues related to either security or performance. The most critical issue is the lack of a check in 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 'withdraw' in Dice.sol (70e4405). 2.b Fix (one line with code reference): Checked return value in the function 'withdraw' in Dice.sol (de3090c). Moderate: 0 Major: 0 Critical: 0 Observations - The audit was conducted using the whitebox method. - The audit was conducted on the Lucky Dice smart contract and the MasterChef smart contract. - The audit was conducted using the OWASP Risk Rating Methodology. Conclusion The audit of the Lucky Dice and MasterChef smart contracts was conducted using the whitebox method and the OWASP Risk Rating Methodology. The audit found two minor issues, which were fixed in the latest commit. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 4 Major: 3 Critical: 0 Minor Issues: 2.a Problem: Constructor Mismatch (CWE-699) 2.b Fix: Ensure that the constructor is properly defined and called. Moderate Issues: 3.a Problem: Ownership Takeover (CWE-699) 3.b Fix: Ensure that the ownership of the contract is properly managed. 3.c Problem: Redundant Fallback Function (CWE-699) 3.d Fix: Remove redundant fallback functions. 3.e Problem: Overflows & Underflows (CWE-699) 3.f Fix: Ensure that all arithmetic operations are properly checked for overflows and underflows. 3.g Problem: Reentrancy (CWE-699) 3.h Fix: Ensure that all external calls are properly checked for reentrancy. Major Issues: 4.a Problem: Money-Giving Bug (CWE-699) 4.b Fix: Ensure that all external calls are properly checked for money-giving bugs.
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 "./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; } } //SWC-Floating Pragma: L2 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 ComptrollerV5Storage, 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 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 COMP vesting period is changed event NewVestingPeriod(uint oldVestingPeriod, uint newVestingPeriod); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when a new COMP speed is calculated for a contributor event ContributorCompSpeedUpdated(address indexed contributor, 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 Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when COMP is granted by admin event CompGranted(address recipient, uint amount); /// @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; } // 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 updateLastVestingBlockInternal(); 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 updateLastVestingBlockInternal(); 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); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (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()}); updateLastVestingBlockInternal(); 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()}); updateLastVestingBlockInternal(); 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); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); 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 updateLastVestingBlockInternal(); 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 updateLastVestingBlockInternal(); 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; // 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) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); } } // 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; numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); 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 */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); 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); } // 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 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); } // 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 Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @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 vestingPeriod_) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); Comptroller(address(unitroller))._becomeG6(vestingPeriod_); } function _becomeG6(uint vestingPeriod_) public { require(msg.sender == comptrollerImplementation, "only brains can become itself"); for (uint i = 0; i < allMarkets.length; i++) { address cToken = address(allMarkets[i]); compSupplyVestingState[cToken] = compSupplyState[cToken]; compBorrowVestingState[cToken] = compBorrowState[cToken]; } _setVestingPeriod(vestingPeriod_); } /** * @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 Set COMP speed for a single market * @param cToken The market whose COMP speed to update * @param compSpeed New COMP speed for market */ function setCompSpeedInternal(CToken cToken, uint compSpeed) internal { // note that COMP speed could be set to 0 to halt liquidity rewards for a market compSpeeds[address(cToken)] = compSpeed; emit CompSpeedUpdated(cToken, compSpeed); } /** * @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 { updateCompMarketIndex(cToken, compSupplyState[cToken], compSupplyVestingState[cToken], true, Exp({mantissa: 0})); } /** * @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 { updateCompMarketIndex(cToken, compBorrowState[cToken], compBorrowVestingState[cToken], false, marketBorrowIndex); } /** * @notice Accrue COMP to the market by updating the supply or borrow index * @param cToken The market whose index to update * @param marketState The market state whose index to update * @param vestingState The market vesting state whose index to update * @param isSupply True if this implements the supply update, false if the borrow update */ function updateCompMarketIndex(address cToken, CompMarketState storage marketState, CompMarketState storage vestingState, bool isSupply, Exp memory marketBorrowIndex) internal { uint compSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(marketState.block)); if (deltaBlocks > 0 && compSpeed > 0) { uint marketSize; if (isSupply) { marketSize = CToken(cToken).totalSupply(); } else { marketSize = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); } uint compAccrued; Double memory ratio; Double memory index; if (lastVestingBlock > vestingState.block) { uint deltaVestingBlocks = sub_(lastVestingBlock, uint(marketState.block)); compAccrued = mul_(deltaVestingBlocks, compSpeed); ratio = marketSize > 0 ? fraction(compAccrued, marketSize) : Double({mantissa: 0}); // important reference to marketState index below as vesting index is not kept "up to date" index = add_(Double({mantissa: marketState.index}), ratio); vestingState.index = safe224(index.mantissa, "new index exceeds 224 bits"); vestingState.block = safe32(lastVestingBlock, "block number exceeds 32 bits"); } compAccrued = mul_(deltaBlocks, compSpeed); ratio = marketSize > 0 ? fraction(compAccrued, marketSize) : Double({mantissa: 0}); index = add_(Double({mantissa: marketState.index}), ratio); marketState.index = safe224(index.mantissa, "new index exceeds 224 bits"); marketState.block = safe32(blockNumber, "block number exceeds 32 bits"); } else if (deltaBlocks > 0) { if (lastVestingBlock > vestingState.block) { vestingState.block = safe32(blockNumber, "block number exceeds 32 bits"); } marketState.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 * @param distribute Whether to distribute accrued COMP */ function distributeSupplierComp(address cToken, address supplier, bool distribute) internal { distributeMarketComp(cToken, supplier, distribute, compSupplyState[cToken], compSupplyVestingState[cToken], true, Exp({mantissa: 0})); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to vest & 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 * @param distribute Whether to distribute accrued COMP */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distribute) internal { distributeMarketComp(cToken, borrower, distribute, compBorrowState[cToken], compBorrowVestingState[cToken], false, marketBorrowIndex); } /** * @notice Calculate COMP accrued by a holder (supplier or borrower) and possibly transfer it to them * @param cToken The market in which the holder is interacting * @param holder The address of the holder to distribute COMP to */ function distributeMarketComp(address cToken, address holder, bool distribute, CompMarketState storage marketState, CompMarketState storage vestingState, bool isSupply, Exp memory marketBorrowIndex) internal { Double memory marketIndex = Double({mantissa: marketState.index}); Double memory holderIndex; if (isSupply) { holderIndex = Double({mantissa: compSupplierIndex[cToken][holder]}); compSupplierIndex[cToken][holder] = marketIndex.mantissa; if (holderIndex.mantissa == 0 && marketIndex.mantissa > 0) { holderIndex.mantissa = compInitialIndex; } } else { holderIndex = Double({mantissa: compBorrowerIndex[cToken][holder]}); compBorrowerIndex[cToken][holder] = marketIndex.mantissa; } // Accrue vested COMP uint holderAccrued = compAccrued[holder]; if (lastVestingBlock > vestingBlock[holder]) { vestingBlock[holder] = lastVestingBlock; holderAccrued = add_(holderAccrued, compVesting[holder]); compVesting[holder] = 0; } Double memory marketVestingIndex = holderIndex; if (vestingState.index > holderIndex.mantissa) { marketVestingIndex = Double({mantissa: vestingState.index}); } if (isSupply || holderIndex.mantissa > 0) { // Accrue COMP that was earned leading up to vesting event Double memory deltaIndex; uint holderDelta; uint holderHoldings; if (isSupply) { holderHoldings = CToken(cToken).balanceOf(holder); } else { holderHoldings = div_(CToken(cToken).borrowBalanceStored(holder), marketBorrowIndex); } if (marketVestingIndex.mantissa > holderIndex.mantissa) { deltaIndex = sub_(marketVestingIndex, holderIndex); holderDelta = mul_(holderHoldings, deltaIndex); holderAccrued = add_(holderAccrued, holderDelta); } // Vest any new COMP earned after vesting event deltaIndex = sub_(marketIndex, marketVestingIndex); holderDelta = mul_(holderHoldings, deltaIndex); compVesting[holder] = add_(compVesting[holder], holderDelta); } uint compDelta = holderAccrued - compAccrued[holder]; if (distribute) { compAccrued[holder] = grantCompInternal(holder, holderAccrued); } else { compAccrued[holder] = holderAccrued; } if (isSupply) { emit DistributedSupplierComp(CToken(cToken), holder, compDelta, marketIndex.mantissa); } else { emit DistributedBorrowerComp(CToken(cToken), holder, compDelta, marketIndex.mantissa); } } /** * @notice Calculate additional accrued COMP for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint compSpeed = compContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && compSpeed > 0) { uint newAccrued = mul_(deltaBlocks, compSpeed); uint contributorAccrued = add_(compAccrued[contributor], newAccrued); compAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @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 < holders.length; i++) { updateContributorRewards(holders[i]); } updateLastVestingBlockInternal(); 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); } } } } /** * @notice Transfer COMP to the user * @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 amount The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function grantCompInternal(address user, uint amount) internal returns (uint) { Comp comp = Comp(getCompAddress()); uint compRemaining = comp.balanceOf(address(this)); if (amount <= compRemaining) { comp.transfer(user, amount); return 0; } return amount; } /*** Comp Distribution Admin ***/ /** * @notice Transfer COMP to the recipient * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param recipient The address of the recipient to transfer COMP to * @param amount The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the recipient */ function _grantComp(address recipient, uint amount) public returns (uint) { require(adminOrInitializing(), "only admin can grant comp"); uint amountLeft = grantCompInternal(recipient, amount); if (amountLeft == 0) { emit CompGranted(recipient, amount); } } /** * @notice Set COMP speed for a single market * @param cToken The market whose COMP speed to update * @param compSpeed New COMP speed for market */ function _setCompSpeed(CToken cToken, uint compSpeed) public { require(adminOrInitializing(), "only admin can set comp speed"); setCompSpeedInternal(cToken, compSpeed); } /** * @notice Set COMP speed for a single contributor * @param contributor The contributor whose COMP speed to update * @param compSpeed New COMP speed for contributor */ function _setContributorCompSpeed(address contributor, uint compSpeed) public { require(adminOrInitializing(), "only admin can set comp speed"); // note that COMP speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (compSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } lastContributorBlock[contributor] = getBlockNumber(); compContributorSpeeds[contributor] = compSpeed; emit ContributorCompSpeedUpdated(contributor, compSpeed); } /** * @notice Set the time period at which COMP becomes vested * @param vestingPeriod_ The time period at which COMP will be vested in blocks */ function _setVestingPeriod(uint vestingPeriod_) public { require(adminOrInitializing(), "only admin can change vesting period"); require(vestingPeriod_ > 0, "vesting period cannot be 0"); uint oldVestingPeriod = vestingPeriod; vestingPeriod = vestingPeriod_; emit NewVestingPeriod(oldVestingPeriod, vestingPeriod_); // Change vesting offset to current block - this has the side effect of vesting all COMP uint blockNumber = getBlockNumber(); lastVestingBlock = blockNumber; } /** * @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]); } } 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); setCompSpeedInternal(CToken(cToken), 0); } /** * @notice Update the last block where a vesting event happened */ function updateLastVestingBlockInternal() internal { uint blockNumber = getBlockNumber(); uint newLastVestingBlock = lastVestingBlockBeforeInternal(blockNumber); lastVestingBlock = newLastVestingBlock; } /** * @notice Return last block where vesting happened before or at the provided block * @return Last block which was vested */ function lastVestingBlockBeforeInternal(uint blockNumber) internal view returns (uint) { uint vestingOffset = mod_(lastVestingBlock, vestingPeriod); uint currentBlockOffset = mod_(blockNumber, vestingPeriod); uint vestingBlock = add_(sub_(blockNumber, currentBlockOffset), vestingOffset); if (currentBlockOffset < vestingOffset) { vestingBlock = sub_(vestingBlock, vestingPeriod); } return vestingBlock; } /** * @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"; /** * @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 Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(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 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 mod_(uint a, uint b) pure internal returns (uint) { return mod_(a, b, "modulo by zero"); } function mod_(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; /** * @title Compound's Legacy InterestRateModel Interface * @author Compound (modified by Arr00) */ contract LegacyInterestRateModel { /// @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 error code (0 = no error), The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint,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 "./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 "./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 (modified by Arr00) */ contract ComptrollerG5 is ComptrollerV4Storage, 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 Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @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); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); (MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount); require(mathErr == MathError.NO_ERROR, "total borrows overflow"); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (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 Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @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 0xc00e94Cb662C3520282E6f5717214004A7f26888; } } pragma solidity ^0.5.16; import "./BaseJumpRateModelV2.sol"; import "./LegacyInterestRateModel.sol"; /** * @title Compound's JumpRateModel Contract V2 for legacy cTokens * @author Arr00 * @notice Supports only legacy cTokens */ contract LegacyJumpRateModelV2 is LegacyInterestRateModel, BaseJumpRateModelV2 { /** * @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 (Error, The borrow rate percentage per block as a mantissa (scaled by 1e18)) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint, uint) { return (0,getBorrowRateInternal(cash, borrows, reserves)); } constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) BaseJumpRateModelV2(baseRatePerYear,multiplierPerYear,jumpMultiplierPerYear,kink_,owner_) public {} } 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 ComptrollerG4 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 0xc00e94Cb662C3520282E6f5717214004A7f26888; } } 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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("mint(uint256)", mintAmount)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeem(uint256)", redeemTokens)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeemUnderlying(uint256)", redeemAmount)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrow(uint256)", borrowAmount)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrow(uint256)", repayAmount)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrowBehalf(address,uint256)", borrower, repayAmount)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("liquidateBorrow(address,uint256,address)", borrower, repayAmount, cTokenCollateral)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("transfer(address,uint256)", dst, amount)); return abi.decode(data, (bool)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("transferFrom(address,address,uint256)", src, dst, amount)); return abi.decode(data, (bool)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("approve(address,uint256)", spender, amount)); return abi.decode(data, (bool)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("allowance(address,address)", owner, spender)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("balanceOf(address)", owner)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("balanceOfUnderlying(address)", owner)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getAccountSnapshot(address)", account)); return abi.decode(data, (uint, uint, uint, uint)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowRatePerBlock()")); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("supplyRatePerBlock()")); return abi.decode(data, (uint)); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("totalBorrowsCurrent()")); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrowBalanceCurrent(address)", account)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowBalanceStored(address)", account)); return abi.decode(data, (uint)); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("exchangeRateCurrent()")); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("exchangeRateStored()")); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getCash()")); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("accrueInterest()")); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("seize(address,address,uint256)", liquidator, borrower, seizeTokens)); return abi.decode(data, (uint)); } /*** 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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setPendingAdmin(address)", newPendingAdmin)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setComptroller(address)", newComptroller)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setReserveFactor(uint256)", newReserveFactorMantissa)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_acceptAdmin()")); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_addReserves(uint256)", addAmount)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_reduceReserves(uint256)", reduceAmount)); return abi.decode(data, (uint)); } /** * @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) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setInterestRateModel(address)", newInterestRateModel)); return abi.decode(data, (uint)); } /** * @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)); } /** * @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 (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) } } } } 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; 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::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } 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 { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); 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 "./BaseJumpRateModelV2.sol"; import "./InterestRateModel.sol"; /** * @title Compound's JumpRateModel Contract V2 for V2 cTokens * @author Arr00 * @notice Supports only for V2 cTokens */ contract JumpRateModelV2 is InterestRateModel, BaseJumpRateModelV2 { /** * @notice Calculates the current borrow 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 * @return The borrow rate percentage per block as a mantissa (scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint) { return getBorrowRateInternal(cash, borrows, reserves); } constructor(uint baseRatePerYear, uint multiplierPerYear, uint jumpMultiplierPerYear, uint kink_, address owner_) BaseJumpRateModelV2(baseRatePerYear,multiplierPerYear,jumpMultiplierPerYear,kink_,owner_) public {} } 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 supply 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; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage { /// @notice The vesting period at which all vested COMP is distributed, in blocks uint public vestingPeriod; /** * @notice Last block at which COMP vested * @dev This is the "precise" vesting block and may not contain any Compound interactions */ uint public lastVestingBlock; /// @notice The COMP market supply state for each market (only fully vested) mapping(address => CompMarketState) public compSupplyVestingState; /// @notice The COMP market borrow state for each market (only fully vested) mapping(address => CompMarketState) public compBorrowVestingState; /** * @notice The last block where each user accrued vested COMP * @dev This is the "precise" vesting block and may not contain any Compound interactions */ mapping(address => uint) public vestingBlock; /// @notice The COMP that has been earned but not yet accrued to each user mapping(address => uint) public compVesting; // New continuous rewards patch /// @notice The portion of COMP that each contributor receives per block mapping(address => uint) public compContributorSpeeds; /// @notice Last block at which a contributor's COMP rewards have been allocated mapping(address => uint) public lastContributorBlock; } 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"; pragma solidity ^0.5.16; import "./CErc20Delegate.sol"; interface CompLike { function delegate(address delegatee) external; } /** * @title Compound's CCompLikeDelegate Contract * @notice CTokens which can 'delegate votes' of their underlying ERC-20 * @author Compound */ contract CCompLikeDelegate is CErc20Delegate { /** * @notice Construct an empty delegate */ constructor() public CErc20Delegate() {} /** * @notice Admin call to delegate the votes of the COMP-like underlying * @param compLikeDelegatee The address to delegate votes to */ function _delegateCompLikeTo(address compLikeDelegatee) external { require(msg.sender == admin, "only the admin may set the comp-like delegate"); CompLike(underlying).delegate(compLikeDelegatee); } } 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 "./SafeMath.sol"; /** * @title Logic for Compound's JumpRateModel Contract V2. * @author Compound (modified by Dharma Labs, refactored by Arr00) * @notice Version 2 modifies Version 1 by enabling updateable parameters. */ contract BaseJumpRateModelV2 { 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_) internal { 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 getBorrowRateInternal(uint cash, uint borrows, uint reserves) internal 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 = getBorrowRateInternal(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 "./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; }
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
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 0 - Moderate Issues: 1 (1 Resolved) - Major Issues: 0 - Critical Issues: 0 Observations - High Documentation Quality - High Test Quality - All Low/Medium Severity Issues Addressed Conclusion The code was found to be of high quality with no critical or major issues. All low/medium severity issues have been addressed as recommended. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The implemented internal method does not update the related market staking indexes. 2.b Fix: Changing the value of "Comp token distribution speed" for a specific market before updating its supply and borrow indexes. Observations: The Quantstamp auditing process follows a routine series of steps including code review, testing and automated analysis, and best practices review. Conclusion: The audit was successful in finding one minor issue which was fixed. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The method only succeeds when the amount requested is less than or equal to the remaining Comp balance, as implemented in Comptroller.sol. However, when the amount is more than that, the method fails silently without emitting an event or throwing. 2.b Fix: Check the returned value of Comptroller._grantComp and throw the transaction if it is different than zero. Moderate Issues: 3.a Problem: Every Solidity file specifies in the header a version number of the format pragma solidity (^)0.*.* ^ and above. 3.b Fix: 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. Observations: Slither raised multiple high and medium issues. However, all issues were classified as false positives. Outdated NatSpec: Documentation in Comptroller.sol is missing description for updateCompMarketIndex @param marketBorrowIndex. Documentation in
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
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 0 - Moderate Issues: 1 (1 Resolved) - Major Issues: 0 - Critical Issues: 0 Observations - High Documentation Quality - High Test Quality - All Low/Medium Severity Issues Addressed Conclusion The code was found to be of high quality with no critical or major issues. All low/medium severity issues have been addressed as recommended. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The implemented internal method does not update the related market staking indexes. 2.b Fix: Comptroller.setCompSpeedInternal cToken should be called before updating value for any given market. Moderate: None Major: None Critical: None Observations: The Quantstamp auditing process follows a routine series of steps: code review, testing and automated analysis, and best practices review. Conclusion: The audit was successful in finding one minor issue and providing a fix for it. No moderate, 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 method only succeeds when the amount requested is less than or equal to the remaining Comp balance, as implemented in Comptroller.sol. However, when the amount is more than that, the method fails silently without emitting an event or throwing. 2.b Fix: Check the returned value of Comptroller._grantComp and throw the transaction if it is different than zero. Moderate Issues: 3.a Problem: Every Solidity file specifies in the header a version number of the format pragma solidity (^)0.*.* ^ and above. 3.b Fix: 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. Observations: Slither raised multiple high and medium issues. However, all issues were classified as false positives. Outdated NatSpec: Documentation in Comptroller.sol is missing description for updateCompMarketIndex @param marketBorrowIndex. Documentation in Comptroller
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
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 0 - Moderate Issues: 1 (1 Resolved) - Major Issues: 0 - Critical Issues: 0 Observations - High Documentation Quality - High Test Quality - All Low/Medium Severity Issues Addressed Conclusion The code was found to be of high quality with no critical or major issues. All low/medium severity issues have been addressed as recommended. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The implemented internal method does not update the related market staking indexes. 2.b Fix: Comptroller.setCompSpeedInternal cToken should be called before updating value for any given market. Moderate: None Major: None Critical: None Observations: The Quantstamp auditing process follows a routine series of steps: code review, testing and automated analysis, and best practices review. Conclusion: The audit was successful in finding one minor issue and providing a fix for it. No moderate, 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 method only succeeds when the amount requested is less than or equal to the remaining Comp balance, as implemented in Comptroller.sol. However, when the amount is more than that, the method fails silently without emitting an event or throwing. 2.b Fix: Check the returned value of Comptroller._grantComp and throw the transaction if it is different than zero. Moderate Issues: 3.a Problem: Every Solidity file specifies in the header a version number of the format pragma solidity (^)0.*.* ^ and above. 3.b Fix: 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. Observations: Slither raised multiple high and medium issues. However, all issues were classified as false positives. Outdated NatSpec: Documentation in Comptroller.sol is missing description for updateCompMarketIndex @param marketBorrowIndex. Documentation in Comptroller
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
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 0 - Moderate Issues: 1 (1 Resolved) - Major Issues: 0 - Critical Issues: 0 Observations - High Documentation Quality - High Test Quality - All Low/Medium Severity Issues Addressed Conclusion The code was found to be of high quality with no critical or major issues. All low/medium severity issues have been addressed as recommended. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The implemented internal method does not update the related market staking indexes. 2.b Fix: Comptroller.setCompSpeedInternal cToken should be called before updating value for any given market. Moderate: None Major: None Critical: None Observations: The Quantstamp auditing process follows a routine series of steps: code review, testing and automated analysis, and best practices review. Conclusion: The audit was successful in finding one minor issue and providing a fix for it. No moderate, 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 method only succeeds when the amount requested is less than or equal to the remaining Comp balance, as implemented in Comptroller.sol. However, when the amount is more than that, the method fails silently without emitting an event or throwing. 2.b Fix: Check the returned value of Comptroller._grantComp and throw the transaction if it is different than zero. Moderate Issues: 3.a Problem: Every Solidity file specifies in the header a version number of the format pragma solidity (^)0.*.* ^ and above. 3.b Fix: 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. Observations: Slither raised multiple high and medium issues. However, all issues were classified as false positives. Outdated NatSpec: Documentation in Comptroller.sol is missing description for updateCompMarketIndex @param marketBorrowIndex. Documentation in Comptroller
// SPDX-License-Identifier: MIT pragma solidity =0.5.16; import './interfaces/IShibaERC20.sol'; import './libs/SafeMath.sol'; contract ShibaERC20 is IShibaERC20 { using SafeMath for uint; string public constant name = 'ShibaNova LPs'; string public constant symbol = 'SHIBA-LP'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { uint chainId; assembly { chainId := chainid } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'ShibaNovaSwap: EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'ShibaNovaSwap: INVALID_SIGNATURE'); _approve(owner, spender, value); } }// 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; } } // SPDX-License-Identifier: MIT pragma solidity =0.5.16; import './interfaces/IShibaFactory.sol'; import './ShibaPair.sol'; contract ShibaFactory is IShibaFactory { bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(ShibaPair).creationCode)); address public feeTo; address public feeToSetter; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; address private _owner; uint16 private _feeAmount; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeTo, address owner, uint16 _feePercent) public { feeToSetter = owner; feeTo = _feeTo; _owner = owner; _feeAmount = _feePercent; } function owner() public view returns (address) { return _owner; } function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(tokenA != tokenB, 'ShibaSwap: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'ShibaSwap: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'ShibaSwap: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(ShibaPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IShibaPair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external { require(msg.sender == feeToSetter, 'ShibaSwap: FORBIDDEN'); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external { require(msg.sender == feeToSetter, 'ShibaSwap: FORBIDDEN'); feeToSetter = _feeToSetter; } function feeAmount() external view returns (uint16){ return _feeAmount; } function setFeeAmount(uint16 _newFeeAmount) external{ // This parameter allow us to lower the fee which will be send to the feeManager // 20 = 0.20% (all fee goes directly to the feeManager) // If we update it to 10 for example, 0.10% are going to LP holder and 0.10% to the feeManager require(msg.sender == owner(), "caller is not the owner"); require (_newFeeAmount <= 20, "amount too big"); _feeAmount = _newFeeAmount; } } // SPDX-License-Identifier: MIT pragma solidity =0.5.16; import './interfaces/IShibaPair.sol'; import './ShibaERC20.sol'; import './libs/Math.sol'; import './libs/UQ112x112.sol'; import './interfaces/IERC20.sol'; import './interfaces/IShibaFactory.sol'; import './interfaces/IShibaCallee.sol'; contract ShibaPair is IShibaPair, ShibaERC20 { using SafeMath for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'ShibaSwap: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ShibaSwap: TRANSFER_FAILED'); } 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); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'ShibaSwap: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'ShibaSwap: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IShibaFactory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul( IShibaFactory(factory).feeAmount() ).add(rootKLast); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } // this low-level function should be called from a contract which performs important safety checks function mint(address to) external lock returns (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'ShibaSwap: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amount0, amount1); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock returns (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20(_token0).balanceOf(address(this)); uint balance1 = IERC20(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'ShibaSwap: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'ShibaSwap: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'ShibaSwap: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'ShibaSwap: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IShibaCallee(to).shibaCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'ShibaSwap: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(10000).sub(amount0In.mul(20)); uint balance1Adjusted = balance1.mul(10000).sub(amount1In.mul(20)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(10000**2), 'ShibaSwap: K'); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } // force balances to match reserves function skim(address to) external lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } }
Public SMART CONTRACT AUDIT REPORT for ShibaNova Prepared By: Yiqun Chen PeckShield July 20, 2021 1/26 PeckShield Audit Report #: 2021-195Public Document Properties Client ShibaNova Title Smart Contract Audit Report Target ShibaNova Version 1.0 Author Xuxian Jiang Auditors Jing Wang, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 July 20, 2021 Xuxian Jiang Final Release 1.0-rc1 July 13, 2021 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/26 PeckShield Audit Report #: 2021-195Public Contents 1 Introduction 4 1.1 About ShibaNova . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Trading Fee Discrepancy Between ShibaSwap And ShibaNova . . . . . . . . . . . . . 12 3.2 Sybil Attacks on sNova Voting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.3 Accommodation of Non-Compliant ERC20 Tokens . . . . . . . . . . . . . . . . . . . 16 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.5 Timely massUpdatePools During Pool Weight Changes . . . . . . . . . . . . . . . . 19 3.6 Inconsistency Between Document and Implementation . . . . . . . . . . . . . . . . . 20 3.7 Redundant Code Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.8 Reentrancy Risk in deposit()/withdraw()/harvestReward() . . . . . . . . . . . . . . . 22 4 Conclusion 24 References 25 3/26 PeckShield Audit Report #: 2021-195Public 1 | Introduction Given the opportunity to review the ShibaNova design document and related smart contract source code, we outline in the report our systematic approach to evaluate potential security issues in the smartcontractimplementation,exposepossiblesemanticinconsistenciesbetweensmartcontractcode 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 ShibaNova ShibaNova is a decentralized exchange and automatic market maker built on the Binance Smart Chain (BSC). The goal is to solve one of the fundamental problems in decentralized finance (DeFi), where the project’s native token rises in value at launch only to incrementally decrease in value day after day until it ultimately goes down to zero. The solution is effectively turning our investors into valued shareholders - eligible to get their share of 75~of fees collected in the dApp. By providing liquidity to the project and creating/holding the related dividend tokens, the shareholders are able to earn daily passive income. This daily dividends system not only incentivizes long-term holding but promotes ownership of the project by the entire community. The basic information of ShibaNova is as follows: Table 1.1: Basic Information of ShibaNova ItemDescription IssuerShibaNova Website http://www.ShibaNova.io TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report July 20, 2021 4/26 PeckShield Audit Report #: 2021-195Public In the following, we show the Git repository of reviewed files and the commit hash values used in this audit. •https://github.com/ShibaNova/Contracts.git (b6b1ce1) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/ShibaNova/Contracts.git (6b221ae) 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 the 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. 5/26 PeckShield Audit Report #: 2021-195Public 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 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) [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. 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 6/26 PeckShield Audit Report #: 2021-195Public 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 7/26 PeckShield Audit Report #: 2021-195Public 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/26 PeckShield Audit Report #: 2021-195Public 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/26 PeckShield Audit Report #: 2021-195Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the implementation of the ShibaNova protocol. 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 1 Medium 1 Low 4 Informational 2 Total 8 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/26 PeckShield Audit Report #: 2021-195Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improvedbyresolvingtheidentifiedissues(showninTable2.1), including 1high-severityvulnerability, 1medium-severity vulnerability, 4low-severity vulnerabilities, and 2informational recommendations. Table 2.1: Key ShibaNova Audit Findings ID Severity Title Category Status PVE-001 High Trading Fee Discrepancy Between ShibaSwap And ShibaNovaBusiness Logic Fixed PVE-002 Low Sybil Attacks on sNova Voting Business Logic Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensCoding Practices Confirmed PVE-004 Medium Trust Issue of Admin Keys Security Features Confirmed PVE-005 Low Timely massUpdatePools During Pool Weight ChangesBusiness Logic Fixed PVE-006 Informational Inconsistency Between Document And ImplementationCoding Practices Fixed PVE-007 Informational Redundant Code Removal Coding Practices Fixed PVE-008 Low Reentrancy Risk in de- posit()/withdraw()/harvestReward()Coding Practices Fixed 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. 11/26 PeckShield Audit Report #: 2021-195Public 3 | Detailed Results 3.1 Trading Fee Discrepancy Between ShibaSwap And ShibaNova •ID: PVE-001 •Severity: High •Likelihood: High •Impact: Medium•Target: Multiple Contracts •Category: Business Logic [9] •CWE subcategory: CWE-841 [6] Description As a decentralized exchange and automatic market maker, the ShibaNova protocol has a constant need to convert one token to another. With the built-in ShibaSwap , if you make a token swap or trade on the exchange, you will need to pay a 0:2~trading fee, which is split into two parts. The first part is returned to liquidity pools in the form of a fee reward for liquidity providers while the second part is sent to the feeManager for distribution. To elaborate, we show below the getAmountOut() routine inside the the ShibaLibrary . For com- parison, we also show the swap()routine in ShibaPair . It is interesting to note that ShibaPair has implicitly assumed the trading fee is 0:2~, instead of 0:16~inShibaLibrary . The difference in the built-in trading fee may deviate the normal operations of a number of helper routines in ShibaRouter . 43 // given an input amount of an asset and pair reserves , returns the maximum output amount of the other asset 44 function getAmountOut ( uint amountIn , uint reserveIn , uint reserveOut ) internal pure returns ( uint amountOut ) { 45 require ( amountIn > 0, ’ ShibaLibrary : INSUFFICIENT_INPUT_AMOUNT ’); 46 require ( reserveIn > 0 && reserveOut > 0, ’ ShibaLibrary : INSUFFICIENT_LIQUIDITY ’) ; 47 uint amountInWithFee = amountIn . mul (9984) ; 48 uint numerator = amountInWithFee . mul( reserveOut ); 49 uint denominator = reserveIn . mul (10000) . add ( amountInWithFee ); 50 amountOut = numerator / denominator ; 51 } 12/26 PeckShield Audit Report #: 2021-195Public 52 53 // given an output amount of an asset and pair reserves , returns a required input amount of the other asset 54 function getAmountIn ( uint amountOut , uint reserveIn , uint reserveOut ) internal pure returns ( uint amountIn ) { 55 require ( amountOut > 0, ’ ShibaLibrary : INSUFFICIENT_OUTPUT_AMOUNT ’); 56 require ( reserveIn > 0 && reserveOut > 0, ’ ShibaLibrary : INSUFFICIENT_LIQUIDITY ’) ; 57 uint numerator = reserveIn . mul ( amountOut ).mul (10000) ; 58 uint denominator = reserveOut . sub ( amountOut ). mul (9984) ; 59 amountIn = ( numerator / denominator ). add (1) ; 60 } Listing 3.1: ShibaLibrary::getAmountOut() 160 function swap ( uint amount0Out , uint amount1Out , address to , bytes calldata data ) external lock { 161 require ( amount0Out > 0 amount1Out > 0, ’ShibaSwap : INSUFFICIENT_OUTPUT_AMOUNT ’) ; 162 ( uint112 _reserve0 , uint112 _reserve1 ,) = getReserves (); // gas savings 163 require ( amount0Out < _reserve0 && amount1Out < _reserve1 , ’ShibaSwap : INSUFFICIENT_LIQUIDITY ’); 164 165 uint balance0 ; 166 uint balance1 ; 167 { // scope for _token {0 ,1} , avoids stack too deep errors 168 address _token0 = token0 ; 169 address _token1 = token1 ; 170 require (to != _token0 && to != _token1 , ’ShibaSwap : INVALID_TO ’); 171 if ( amount0Out > 0) _safeTransfer ( _token0 , to , amount0Out ); // optimistically transfer tokens 172 if ( amount1Out > 0) _safeTransfer ( _token1 , to , amount1Out ); // optimistically transfer tokens 173 if ( data . length > 0) IShibaCallee (to). shibaCall ( msg. sender , amount0Out , amount1Out , data ); 174 balance0 = IERC20 ( _token0 ). balanceOf ( address ( this )); 175 balance1 = IERC20 ( _token1 ). balanceOf ( address ( this )); 176 } 177 uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - ( _reserve0 - amount0Out ) : 0; 178 uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - ( _reserve1 - amount1Out ) : 0; 179 require ( amount0In > 0 amount1In > 0, ’ShibaSwap : INSUFFICIENT_INPUT_AMOUNT ’); 180 { // scope for reserve {0 ,1} Adjusted , avoids stack too deep errors 181 uint balance0Adjusted = balance0 . mul (10000) . sub ( amount0In .mul (20) ); 182 uint balance1Adjusted = balance1 . mul (10000) . sub ( amount1In .mul (20) ); 183 require ( balance0Adjusted . mul ( balance1Adjusted ) >= uint ( _reserve0 ).mul ( _reserve1 ) . mul (10000**2) , ’ShibaSwap : K’); 184 } 185 186 _update ( balance0 , balance1 , _reserve0 , _reserve1 ); 187 emit Swap (msg. sender , amount0In , amount1In , amount0Out , amount1Out , to); 13/26 PeckShield Audit Report #: 2021-195Public 188 } Listing 3.2: ShibaPair::swap() Recommendation Make the built-in trading fee in ShibaNova consistent with the actual trading fee in ShibaPair . Status This issue has been fixed in this commit: e7041e5. 3.2 Sybil Attacks on sNova Voting •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: SNovaToken •Category: Business Logic [9] •CWE subcategory: CWE-841 [6] Description InShibaNova , there is a protocol-related token, i.e., SNovaToken (sNova) , which has been enhanced with the functionality to cast and record the votes. Moreover, the sNovacontract allows for dynamic delegation of a voter to another, though the delegation is not transitive. When a submitted proposal is being tallied, the votes are counted prior to the proposal’s activation. Our analysis with the sNovatoken shows that the current token contract is vulnerable to a so- called Sybilattacks1. For elaboration, let’s assume at the very beginning there is a malicious actor named Malice, who owns 100 sNovatokens. Malicehas an accomplice named Trudywho currently has0balance of sNova. This Sybilattack can be launched as follows: 319 function _delegate ( address delegator , address delegatee ) 320 internal 321 { 322 address currentDelegate = _delegates [ delegator ]; 323 uint256 delegatorBalance = balanceOf ( delegator ); 324 // balance of underlying Novas (not scaled ); 325 _delegates [ delegator ] = delegatee ; 326 327 emit DelegateChanged ( delegator , currentDelegate , delegatee ); 328 329 _moveDelegates ( currentDelegate , delegatee , delegatorBalance ); 330 } 331 332 function _moveDelegates ( address srcRep , address dstRep , uint256 amount ) internal { 333 if ( srcRep != dstRep && amount > 0) { 1The same issue occurs to the SUSHI token and the credit goes to Jong Seok Park[12]. 14/26 PeckShield Audit Report #: 2021-195Public 334 if ( srcRep != address (0) ) { 335 // decrease old representative 336 uint32 srcRepNum = numCheckpoints [ srcRep ]; 337 uint256 srcRepOld = srcRepNum > 0 ? checkpoints [ srcRep ][ srcRepNum - 1]. votes : 0; 338 uint256 srcRepNew = srcRepOld .sub ( amount ); 339 _writeCheckpoint ( srcRep , srcRepNum , srcRepOld , srcRepNew ); 340 } 341 342 if ( dstRep != address (0) ) { 343 // increase new representative 344 uint32 dstRepNum = numCheckpoints [ dstRep ]; 345 uint256 dstRepOld = dstRepNum > 0 ? checkpoints [ dstRep ][ dstRepNum - 1]. votes : 0; 346 uint256 dstRepNew = dstRepOld .add ( amount ); 347 _writeCheckpoint ( dstRep , dstRepNum , dstRepOld , dstRepNew ); 348 } 349 } 350 } Listing 3.3: SNovaToken.sol 1.Maliceinitially delegates the voting to Trudy. Right after the initial delegation, Trudycan have 100votes if he chooses to cast the vote. 2.Malicetransfers the full 100balance to M1who also delegates the voting to Trudy. Right after this delegation, Trudycan have 200votes if he chooses to cast the vote. The reason is that the SushiToken contract’s transfer() does NOT _moveDelegates() together. In other words, even now Malicehas0balance, the initial delegation (of Malice) to Trudywill not be affected, therefore Trudystill retains the voting power of 100 sNova. When M1delegates to Trudy, since M1now has 100 sNova,Trudywill get additional 100votes, totaling 200votes. 3. We can repeat by transferring Mi’s100 sNovabalance to Mi+1who also delegates the votes toTrudy. Every iteration will essentially add 100voting power to Trudy. In other words, we can effectively amplify the voting powers of Trudyarbitrarily with new accounts created and iterated! Recommendation To mitigate, it is necessary to accompany every single transfer() and transferFrom() with the _moveDelegates() so that the voting power of the sender’s delegate will be movedto thedestination’sdelegate. Bydoingso, wecaneffectivelymitigate theabove Sybilattacks. Status This issue has been fixed in this commit: e7041e5. 15/26 PeckShield Audit Report #: 2021-195Public 3.3 Accommodation of Non-Compliant ERC20 Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [8] •CWE subcategory: CWE-1126 [2] Description ThoughthereisastandardizedERC-20specification, manytokencontractsmaynotstrictlyfollowthe specification or have additional functionalities beyond the specification. In this section, we examine the transfer() routine and 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. Specifically, the transfer() routine does not have a return value defined and implemented. However, the IERC20interface has defined the transfer() interface with a boolreturn value. As a result, the call to transfer() may expect a return value. With the lack of return value ofUSDT’stransfer() , the call will be unfortunately reverted. 126 function transfer ( address _to , uint _value ) public onlyPayloadSize (2 * 32) { 127 uint fee = ( _value . mul ( basisPointsRate )). div (10000) ; 128 if ( fee > maximumFee ) { 129 fee = maximumFee ; 130 } 131 uint sendAmount = _value . sub( fee); 132 balances [msg . sender ] = balances [msg . sender ]. sub ( _value ); 133 balances [_to ] = balances [ _to ]. add ( sendAmount ); 134 if ( fee > 0) { 135 balances [ owner ] = balances [ owner ]. add ( fee ); 136 Transfer (msg .sender , owner , fee ); 137 } 138 Transfer (msg .sender , _to , sendAmount ); 139 } Listing 3.4: USDT::transfer() Because of that, a normal call to transfer() is suggested to use the safe version, i.e., safeTransfer (), Inessence, itisawrapperaroundERC20operationsthatmayeitherthrowonfailureorreturnfalse 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 approve()/transferFrom() as well, i.e., safeApprove()/safeTransferFrom() . In current implementation, if we examine the PresaleContract::swap() routine that is designed to fund-raising by swapping the input token0totoken1To accommodate the specific idiosyncrasy, 16/26 PeckShield Audit Report #: 2021-195Public there is a need to use safeTransferFrom() (instead of transferFrom() - line 172) and safeTransfer() (instead of transfer() - line 176). 161 function swap ( uint256 inAmount ) public onlyWhitelisted { 162 uint256 quota = token1 . balanceOf ( address ( this )); 163 uint256 total = token0 . balanceOf ( msg. sender ); 164 uint256 outAmount = inAmount . mul (1000) . div ( swapRate ); 167 require ( isSwapStarted == true , ’ ShibanovaSwap :: Swap not started ’); 168 require ( inAmount <= total , " ShibanovaSwap :: Insufficient funds "); 169 require ( outAmount <= quota , " ShibanovaSwap :: Quota not enough "); 170 require ( spent [ msg. sender ]. add( inAmount ) <= maxBuy , " ShibanovaSwap : : Reached Max Buy "); 172 token0 . transferFrom ( msg . sender , address ( Payee ), inAmount ); 174 spent [ msg . sender ] = spent [ msg . sender ] + inAmount ; 176 token1 . transfer ( msg . sender , outAmount ); 178 emit Swap (msg. sender , inAmount , outAmount ); 179 } Listing 3.5: PresaleContract::swap() Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related approve()/transfer()/transferFrom() . Status This issue has been confirmed. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Security Features [7] •CWE subcategory: CWE-287 [3] Description In the ShibaNova protocol, there is a special owneraccount that plays a critical role in governing and regulating the protocol-wide operations (e.g., set various parameters and add/remove reward pools). 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 owneraccount as well as related privileged opeations. 17/26 PeckShield Audit Report #: 2021-195Public To elaborate, we show below two example functions, i.e., setFeeAmount() and set(). The first one allows for dynamic allocation on the trading fee between liquidity providers and feeManager while the second one may specify deposit fee for staking. 66 function setFeeAmount ( uint16 _newFeeAmount ) external { 67 // This parameter allow us to lower the fee which will be send to the feeManager 68 // 20 = 0.20% ( all fee goes directly to the feeManager ) 69 // If we update it to 10 for example , 0.10% are going to LP holder and 0.10% to the feeManager 70 require ( msg . sender == owner () , " caller is not the owner "); 71 require ( _newFeeAmount <= 20, " amount too big "); 72 _feeAmount = _newFeeAmount ; 73 } Listing 3.6: ShibaFactory::setFeeAmount() 158 // Update the given pool ’s Nova allocation point . Can only be called by the owner . 159 function set ( uint256 _pid , uint256 _allocPoint , uint256 _depositFeeBP , bool _isSNovaRewards , bool _withUpdate ) external onlyOwner { 160 require ( _depositFeeBP <= 400 , " set : invalid deposit fee basis points "); 161 massUpdatePools (); 162 uint256 prevAllocPoint = poolInfo [ _pid ]. allocPoint ; 163 poolInfo [ _pid ]. allocPoint = _allocPoint ; 164 poolInfo [ _pid ]. depositFeeBP = _depositFeeBP ; 165 poolInfo [ _pid ]. isSNovaRewards = _isSNovaRewards ; 166 if ( prevAllocPoint != _allocPoint ) { 167 totalAllocPoint = totalAllocPoint . sub ( prevAllocPoint ). add ( _allocPoint ); 168 } 169 } Listing 3.7: MasterShiba::set() We understand the need of the privileged functions for contract maintenance, but at the same time the extra power to the owner may also be a counter-party risk to the protocol users. It is worrisome if the privileged owneraccount 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. 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. 18/26 PeckShield Audit Report #: 2021-195Public 3.5 Timely massUpdatePools During Pool Weight Changes •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterShiba •Category: Business Logic [9] •CWE subcategory: CWE-841 [6] Description The ShibaNova protocol provides incentive mechanisms that reward the staking of supported assets. The rewards are carried out by designating a number of staking pools into which supported assets can be staked. And staking users are rewarded in proportional to their share of LP tokens in the reward pool. The reward pools can be dynamically added via add()and the weights of supported pools can be adjusted via set(). When analyzing the pool weight update routine set(), we notice the need of timely invoking massUpdatePools() to update the reward distribution before the new pool weight becomes effective. 158 // Update the given pool ’s Nova allocation point . Can only be called by the owner . 159 function set ( uint256 _pid , uint256 _allocPoint , uint256 _depositFeeBP , bool _isSNovaRewards , bool _withUpdate ) external onlyOwner { 160 require ( _depositFeeBP <= 400 , " set : invalid deposit fee basis points "); 161 if ( _withUpdate ) { 162 massUpdatePools (); 163 } 164 uint256 prevAllocPoint = poolInfo [ _pid ]. allocPoint ; 165 poolInfo [ _pid ]. allocPoint = _allocPoint ; 166 poolInfo [ _pid ]. depositFeeBP = _depositFeeBP ; 167 poolInfo [ _pid ]. isSNovaRewards = _isSNovaRewards ; 168 if ( prevAllocPoint != _allocPoint ) { 169 totalAllocPoint = totalAllocPoint . sub ( prevAllocPoint ). add ( _allocPoint ); 170 } 171 } Listing 3.8: MasterShiba::set() If the call to massUpdatePools() is not immediately invoked before updating the pool weights, certain situations may be crafted to create an unfair reward distribution. Moreover, a hidden pool withoutanyweightcansuddenlysurfacetoclaimunreasonableshareofrewardedtokens. Fortunately, this interface is restricted to the owner (via the onlyOwner modifier), which greatly alleviates the concern. Recommendation Timely invoke massUpdatePools() when any pool’s weight has been updated. In fact, the third parameter ( _withUpdate ) to the set()routine can be simply ignored or removed. 19/26 PeckShield Audit Report #: 2021-195Public 158 // Update the given pool ’s Nova allocation point . Can only be called by the owner . 159 function set ( uint256 _pid , uint256 _allocPoint , uint256 _depositFeeBP , bool _isSNovaRewards , bool _withUpdate ) external onlyOwner { 160 require ( _depositFeeBP <= 400 , " set : invalid deposit fee basis points "); 161 massUpdatePools (); 162 uint256 prevAllocPoint = poolInfo [ _pid ]. allocPoint ; 163 poolInfo [ _pid ]. allocPoint = _allocPoint ; 164 poolInfo [ _pid ]. depositFeeBP = _depositFeeBP ; 165 poolInfo [ _pid ]. isSNovaRewards = _isSNovaRewards ; 166 if ( prevAllocPoint != _allocPoint ) { 167 totalAllocPoint = totalAllocPoint . sub ( prevAllocPoint ). add ( _allocPoint ); 168 } 169 } Listing 3.9: MasterShiba::set() Status This issue has been fixed in this commit: e7041e5. 3.6 Inconsistency Between Document and Implementation •ID: PVE-006 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: ShibaPair •Category: Coding Practices [8] •CWE subcategory: CWE-1041 [1] Description Thereisamisleadingcommentembeddedinthe ShibaPair contract, whichbringsunnecessaryhurdles to understand and/or maintain the software. The preceding function summary indicates that this function is supposed to mint liquidity "equiv- alent to 1/6th of the growth in sqrt(k)" However, the implementation logic (line 98 * 103) indicates the minted liquidity should be equal to 1/(IShibaFactory(factory).feeAmount()+1) of the growth in sqrt(k). 89 // if fee is on , mint liquidity equivalent to 1/6 th of the growth in sqrt (k) 90 function _mintFee ( uint112 _reserve0 , uint112 _reserve1 ) private returns ( bool feeOn ) { 91 address feeTo = IShibaFactory ( factory ). feeTo (); 92 feeOn = feeTo != address (0) ; 93 uint _kLast = kLast ; // gas savings 94 if ( feeOn ) { 95 if ( _kLast != 0) { 96 uint rootK = Math . sqrt ( uint ( _reserve0 ). mul ( _reserve1 )); 97 uint rootKLast = Math . sqrt ( _kLast ); 98 if ( rootK > rootKLast ) { 20/26 PeckShield Audit Report #: 2021-195Public 99 uint numerator = totalSupply . mul( rootK . sub ( rootKLast )); 100 uint denominator = rootK . mul( IShibaFactory ( factory ). feeAmount () ). add ( rootKLast ); 101 uint liquidity = numerator / denominator ; 102 if ( liquidity > 0) _mint (feeTo , liquidity ); 103 } 104 } 105 } else if ( _kLast != 0) { 106 kLast = 0; 107 } 108 } Listing 3.10: ShibaPair::_mintFee() Recommendation Ensuretheconsistencybetweendocuments(includingembeddedcomments) and implementation. Status This issue has been fixed in this commit: e7041e5. 3.7 Redundant Code Removal •ID: PVE-007 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: ShibaLibrary •Category: Coding Practices [8] •CWE subcategory: CWE-563 [5] Description ShibaNova makes good use of a number of reference contracts, such as ERC20,SafeERC20 ,SafeMath, and Ownable, to facilitate its code implementation and organization. For example, the MasterShiba 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 getReserves() function in the ShibaLibrary contract, this function makes a redundant call to pairFor(factory, tokenA, tokenB) (line 31). 28 // fetches and sorts the reserves for a pair 29 function getReserves ( address factory , address tokenA , address tokenB ) internal view returns ( uint reserveA , uint reserveB ) { 30 ( address token0 ,) = sortTokens ( tokenA , tokenB ); 31 pairFor ( factory , tokenA , tokenB ); 32 ( uint reserve0 , uint reserve1 ,) = IShibaPair ( pairFor ( factory , tokenA , tokenB )). getReserves (); 33 ( reserveA , reserveB ) = tokenA == token0 ? ( reserve0 , reserve1 ) : ( reserve1 , reserve0 ); 21/26 PeckShield Audit Report #: 2021-195Public 34 } Listing 3.11: ShibaLibrary::getReserves() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status This issue has been fixed in this commit: e7041e5. 3.8 Reentrancy Risk in deposit()/withdraw()/harvestReward() •ID: PVE-008 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterShiba •Category: Coding Practices [8] •CWE subcategory: CWE-561 [4] 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 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 are several occasions the checks-effects-interactions principle is violated. Note the withdraw() 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 339) starts before effecting the update on internal states (line 342), 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 very same withdraw() function. 319 // Withdraw LP tokens from MasterShiba . 320 function withdraw ( uint256 _pid , uint256 _amount ) external validatePool ( _pid ) { 321 PoolInfo storage pool = poolInfo [ _pid ]; 322 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 323 require ( user . amount >= _amount , " withdraw : not good "); 324 325 updatePool ( _pid ); 22/26 PeckShield Audit Report #: 2021-195Public 326 uint256 pending = user . amountWithBonus . mul ( pool . accNovaPerShare ). div (1 e12 ). sub ( user . rewardDebt ); 327 if( pending > 0) { 328 if( pool . isSNovaRewards ){ 329 safeSNovaTransfer ( msg . sender , pending ); 330 } 331 else { 332 safeNovaTransfer ( msg . sender , pending ); 333 } 334 } 335 if( _amount > 0) { 336 user . amount = user . amount .sub ( _amount ); 337 uint256 _bonusAmount = _amount . mul ( userBonus (_pid , msg . sender ). add (10000) ). div (10000) ; 338 user . amountWithBonus = user . amountWithBonus . sub ( _bonusAmount ); 339 pool . lpToken . safeTransfer ( address ( msg. sender ), _amount ); 340 pool . lpSupply = pool . lpSupply .sub ( _bonusAmount ); 341 } 342 user . rewardDebt = user . amountWithBonus . mul ( pool . accNovaPerShare ). div (1 e12 ); 343 emit Withdraw (msg. sender , _pid , _amount ); 344 } Listing 3.12: MasterShiba::withdraw() Note that the same issue also found in the deposit() and the harvestReward() functions. Recommendation Add the nonReentrant modifier to prevent reentrancy. Status This issue has been fixed in this commit: e7041e5. 23/26 PeckShield Audit Report #: 2021-195Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the ShibaNova protocol. The system presents a decentralized exchange and automatic market maker built on the Binance Smart Chain (BSC). The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and fixed. 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. 24/26 PeckShield Audit Report #: 2021-195Public 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-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [4] MITRE. CWE-561: Dead Code. https://cwe.mitre.org/data/definitions/561.html. [5] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [6] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [7] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.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. 25/26 PeckShield Audit Report #: 2021-195Public [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] Jong Seok Park. Sushiswap Delegation Double Spending Bug. https://medium.com/ bulldax-finance/sushiswap-delegation-double-spending-bug-5adcc7b3830f. [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. 26/26 PeckShield Audit Report #: 2021-195
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Trading Fee Discrepancy Between ShibaSwap And ShibaNova (Line 12) - Sybil Attacks on sNova Voting (Line 14) - Accommodation of Non-Compliant ERC20 Tokens (Line 16) - Trust Issue of Admin Keys (Line 17) 2.b Fix (one line with code reference) - Adjust the fee rate of ShibaSwap and ShibaNova (Line 12) - Implement a voting system with a KYC process (Line 14) - Implement a whitelist of compliant ERC20 tokens (Line 16) - Implement a multi-signature wallet for admin keys (Line 17) Moderate 3.a Problem (one line with code reference) - Timely massUpdatePools During Pool Weight Changes (Line 19) - Inconsistency Between Document and Implementation (Line 20) 3.b Fix (one line with code reference) - Implement a Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - The goal is to solve one of the fundamental problems in decentralized finance (DeFi) - The solution is to turn investors into valued shareholders eligible to get their share of 75% of fees collected in the dApp - ShibaNova is an Ethereum Smart Contract - Latest Audit Report is July 20, 2021 - PeckShield Inc. is a leading blockchain security company - OWASP Risk Rating Methodology is used to evaluate the risk Conclusion: No issues were found in the audit. 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 function transferFrom() (CWE-252) 2.b Fix (one line with code reference) - Check return value of transferFrom() before proceeding (CWE-252) Moderate 3.a Problem (one line with code reference) - Unchecked return value in function transfer() (CWE-252) 3.b Fix (one line with code reference) - Check return value of transfer() before proceeding (CWE-252) Major - None Critical - 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 4 minor issues and 2 moderate issues, all of which have been addressed. No major or critical issues were found.
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/SafeMath.sol"; import "./libs/Ownable.sol"; import "./interfaces/IMasterBonus.sol"; import "./interfaces/IBonusAggregator.sol"; /* The purpose of this contract is to allow us adding bonus to user's reward by adding NFT contracts for example without updating the masterChef The owner of this contract will be transferred to a timelock */ contract ShibaBonusAggregator is Ownable, IBonusAggregator{ using SafeMath for uint256; IMasterBonus master; // pid => address => bonus percent mapping(uint256 => mapping(address => uint256)) public userBonusOnFarms; mapping (address => bool) public contractBonusSource; /** * @dev Throws if called by any account other than the verified contracts. * Can be an NFT contract for example */ modifier onlyVerifiedContract() { require(contractBonusSource[msg.sender], "caller is not in contract list"); _; } function setupMaster(IMasterBonus _master) external onlyOwner{ master = _master; } function addOrRemoveContractBonusSource(address _contract, bool _add) external onlyOwner{ contractBonusSource[_contract] = _add; } function addUserBonusOnFarm(address _user, uint256 _percent, uint256 _pid) external onlyVerifiedContract{ userBonusOnFarms[_pid][_user] = userBonusOnFarms[_pid][_user].add(_percent); require(userBonusOnFarms[_pid][_user] < 10000, "Invalid percent"); master.updateUserBonus(_user, _pid, userBonusOnFarms[_pid][_user]); } function removeUserBonusOnFarm(address _user, uint256 _percent, uint256 _pid) external onlyVerifiedContract{ userBonusOnFarms[_pid][_user] = userBonusOnFarms[_pid][_user].sub(_percent); master.updateUserBonus(_user, _pid, userBonusOnFarms[_pid][_user]); } function getBonusOnFarmsForUser(address _user, uint256 _pid) external virtual override view returns (uint256){ return userBonusOnFarms[_pid][_user]; } } // SPDX-License-Identifier: MIT pragma solidity =0.6.12; import './interfaces/IShibaFactory.sol'; import './libs/TransferHelper.sol'; import './interfaces/IShibaRouter02.sol'; import './libs/ShibaLibrary.sol'; import './libs/SafeMath.sol'; import './interfaces/IERC20.sol'; import './interfaces/IWETH.sol'; contract ShibaRouter is IShibaRouter02 { using SafeMath for uint; address public immutable override factory; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'ShibaRouter: EXPIRED'); _; } constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IShibaFactory(factory).getPair(tokenA, tokenB) == address(0)) { IShibaFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = ShibaLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = ShibaLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'ShibaRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = ShibaLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'ShibaRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = ShibaLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IShibaPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = ShibaLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IShibaPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = ShibaLibrary.pairFor(factory, tokenA, tokenB); IShibaPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IShibaPair(pair).burn(to); (address token0,) = ShibaLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'ShibaRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'ShibaRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = ShibaLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IShibaPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = ShibaLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IShibaPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = ShibaLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IShibaPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = ShibaLibrary.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? ShibaLibrary.pairFor(factory, output, path[i + 2]) : _to; IShibaPair(ShibaLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = ShibaLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'ShibaRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, ShibaLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = ShibaLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'ShibaRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, ShibaLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'ShibaRouter: INVALID_PATH'); amounts = ShibaLibrary.getAmountsOut(factory, msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'ShibaRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(ShibaLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'ShibaRouter: INVALID_PATH'); amounts = ShibaLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'ShibaRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, ShibaLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'ShibaRouter: INVALID_PATH'); amounts = ShibaLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'ShibaRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, ShibaLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'ShibaRouter: INVALID_PATH'); amounts = ShibaLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'ShibaRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); assert(IWETH(WETH).transfer(ShibaLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = ShibaLibrary.sortTokens(input, output); IShibaPair pair = IShibaPair(ShibaLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = ShibaLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? ShibaLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, ShibaLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'ShibaRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'ShibaRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(ShibaLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'ShibaRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'ShibaRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, ShibaLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'ShibaRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return ShibaLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return ShibaLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return ShibaLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return ShibaLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return ShibaLibrary.getAmountsIn(factory, amountOut, path); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/SafeMath.sol"; import "./libs/IBEP20.sol"; import "./libs/SafeBEP20.sol"; import "./libs/Ownable.sol"; import "./ShibaBonusAggregator.sol"; import "./libs/ShibaBEP20.sol"; // MasterShiba is the master of Nova and sNova. // The Ownership of this contract is going to be transferred to a timelock contract MasterShiba is Ownable, IMasterBonus { using SafeMath for uint256; using SafeBEP20 for ShibaBEP20; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 amountWithBonus; uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of Novas // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accNovaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accNovaPerShare` (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. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 lpSupply; uint256 allocPoint; // How many allocation points assigned to this pool. Novas to distribute per block. uint256 lastRewardBlock; // Last block number that Novas distribution occurs. uint256 accNovaPerShare; // Accumulated Novas per share, times 1e12. See below. uint256 depositFeeBP; // deposit Fee bool isSNovaRewards; } ShibaBonusAggregator public bonusAggregator; // The Nova TOKEN! ShibaBEP20 public Nova; // The SNova TOKEN! ShibaBEP20 public sNova; // Dev address. address public devaddr; // Nova tokens created per block. uint256 public NovaPerBlock; // Deposit Fee address address public feeAddress; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when Nova mining starts. uint256 public immutable startBlock; // Initial emission rate: 1 Nova per block. uint256 public immutable initialEmissionRate; // Minimum emission rate: 0.5 Nova per block. uint256 public minimumEmissionRate = 500 finney; // Reduce emission every 14400 blocks ~ 12 hours. uint256 public immutable emissionReductionPeriodBlocks = 14400; // Emission reduction rate per period in basis points: 2%. uint256 public immutable emissionReductionRatePerPeriod = 200; // Last reduction period index uint256 public lastReductionPeriodIndex = 0; 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); event EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount); constructor( ShibaBEP20 _Nova, ShibaBEP20 _sNova, ShibaBonusAggregator _bonusAggregator, address _devaddr, address _feeAddress, uint256 _NovaPerBlock, uint256 _startBlock ) public { Nova = _Nova; sNova = _sNova; bonusAggregator = _bonusAggregator; devaddr = _devaddr; feeAddress = _feeAddress; NovaPerBlock = _NovaPerBlock; startBlock = _startBlock; initialEmissionRate = _NovaPerBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _Nova, lpSupply: 0, allocPoint: 800, lastRewardBlock: _startBlock, accNovaPerShare: 0, depositFeeBP: 0, isSNovaRewards: false })); totalAllocPoint = 800; } modifier validatePool(uint256 _pid) { require(_pid < poolInfo.length, "validatePool: pool exists?"); _; } modifier onlyAggregator() { require(msg.sender == address(bonusAggregator), "Ownable: caller is not the owner"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } function userBonus(uint256 _pid, address _user) public view returns (uint256){ return bonusAggregator.getBonusOnFarmsForUser(_user, _pid); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IBEP20 _lpToken, uint256 _depositFeeBP, bool _isSNovaRewards, bool _withUpdate) external onlyOwner { require(_depositFeeBP <= 400, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, lpSupply: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accNovaPerShare: 0, depositFeeBP : _depositFeeBP, isSNovaRewards: _isSNovaRewards })); } // Update the given pool's Nova allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint256 _depositFeeBP, bool _isSNovaRewards, bool _withUpdate) external onlyOwner { require(_depositFeeBP <= 400, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; poolInfo[_pid].isSNovaRewards = _isSNovaRewards; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); } } // View function to see pending Novas on frontend. function pendingNova(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accNovaPerShare = pool.accNovaPerShare; uint256 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 NovaReward = multiplier.mul(NovaPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accNovaPerShare = accNovaPerShare.add(NovaReward.mul(1e12).div(lpSupply)); } uint256 userRewards = user.amountWithBonus.mul(accNovaPerShare).div(1e12).sub(user.rewardDebt); if(!pool.isSNovaRewards){ // taking account of the 2% auto-burn userRewards = userRewards.mul(98).div(100); } return userRewards; // taking account of the 2% auto burn on Nova } // Reduce emission rate based on configurations function updateEmissionRate() internal { if(startBlock > 0 && block.number <= startBlock){ return; } if(NovaPerBlock <= minimumEmissionRate){ return; } uint256 currentIndex = block.number.sub(startBlock).div(emissionReductionPeriodBlocks); if (currentIndex <= lastReductionPeriodIndex) { return; } uint256 newEmissionRate = NovaPerBlock; for (uint256 index = lastReductionPeriodIndex; index < currentIndex; ++index) { newEmissionRate = newEmissionRate.mul(1e4 - emissionReductionRatePerPeriod).div(1e4); } newEmissionRate = newEmissionRate < minimumEmissionRate ? minimumEmissionRate : newEmissionRate; if (newEmissionRate >= NovaPerBlock) { return; } lastReductionPeriodIndex = currentIndex; uint256 previousEmissionRate = NovaPerBlock; NovaPerBlock = newEmissionRate; emit EmissionRateUpdated(msg.sender, previousEmissionRate, newEmissionRate); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public validatePool(_pid) { updateEmissionRate(); PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpSupply; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 NovaReward = multiplier.mul(NovaPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 devMintAmount = NovaReward.div(10); Nova.mint(devaddr, devMintAmount); if (pool.isSNovaRewards){ sNova.mint(address(this), NovaReward); } else{ Nova.mint(address(this), NovaReward); } pool.accNovaPerShare = pool.accNovaPerShare.add(NovaReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Allow ShibaBonusAggregator to add bonus on a single pool by id to a specific user function updateUserBonus(address _user, uint256 _pid, uint256 bonus) external virtual override validatePool(_pid) onlyAggregator{ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amountWithBonus.mul(pool.accNovaPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if(pool.isSNovaRewards){ safeSNovaTransfer(_user, pending); } else{ safeNovaTransfer(_user, pending); } } } pool.lpSupply = pool.lpSupply.sub(user.amountWithBonus); user.amountWithBonus = user.amount.mul(bonus.add(10000)).div(10000); pool.lpSupply = pool.lpSupply.add(user.amountWithBonus); user.rewardDebt = user.amountWithBonus.mul(pool.accNovaPerShare).div(1e12); } // Deposit LP tokens to MasterShiba for Nova allocation. function deposit(uint256 _pid, uint256 _amount) external validatePool(_pid) { address _user = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amountWithBonus.mul(pool.accNovaPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if(pool.isSNovaRewards){ safeSNovaTransfer(_user, pending); } else{ safeNovaTransfer(_user, pending); } } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(_user), address(this), _amount); if (address(pool.lpToken) == address(Nova)) { uint256 transferTax = _amount.mul(2).div(100); _amount = _amount.sub(transferTax); } if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); uint256 _bonusAmount = _amount.sub(depositFee).mul(userBonus(_pid, _user).add(10000)).div(10000); user.amountWithBonus = user.amountWithBonus.add(_bonusAmount); pool.lpSupply = pool.lpSupply.add(_bonusAmount); } else { user.amount = user.amount.add(_amount); uint256 _bonusAmount = _amount.mul(userBonus(_pid, _user).add(10000)).div(10000); user.amountWithBonus = user.amountWithBonus.add(_bonusAmount); pool.lpSupply = pool.lpSupply.add(_bonusAmount); } } user.rewardDebt = user.amountWithBonus.mul(pool.accNovaPerShare).div(1e12); emit Deposit(_user, _pid, _amount); } // Withdraw LP tokens from MasterShiba. function withdraw(uint256 _pid, uint256 _amount) external validatePool(_pid) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amountWithBonus.mul(pool.accNovaPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { if(pool.isSNovaRewards){ safeSNovaTransfer(msg.sender, pending); } else{ safeNovaTransfer(msg.sender, pending); } } if(_amount > 0) { user.amount = user.amount.sub(_amount); uint256 _bonusAmount = _amount.mul(userBonus(_pid, msg.sender).add(10000)).div(10000); user.amountWithBonus = user.amountWithBonus.sub(_bonusAmount); // SWC-Reentrancy: L339 - L341 pool.lpToken.safeTransfer(address(msg.sender), _amount); pool.lpSupply = pool.lpSupply.sub(_bonusAmount); } user.rewardDebt = user.amountWithBonus.mul(pool.accNovaPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; pool.lpSupply = pool.lpSupply.sub(user.amountWithBonus); user.amount = 0; user.rewardDebt = 0; user.amountWithBonus = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } function getPoolInfo(uint256 _pid) external view returns(address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accNovaPerShare, uint256 depositFeeBP, bool isSNovaRewards) { return ( address(poolInfo[_pid].lpToken), poolInfo[_pid].allocPoint, poolInfo[_pid].lastRewardBlock, poolInfo[_pid].accNovaPerShare, poolInfo[_pid].depositFeeBP, poolInfo[_pid].isSNovaRewards ); } // Safe Nova transfer function, just in case if rounding error causes pool to not have enough Novas. function safeNovaTransfer(address _to, uint256 _amount) internal { uint256 NovaBal = Nova.balanceOf(address(this)); bool transferSuccess = false; if (_amount > NovaBal) { transferSuccess = Nova.transfer(_to, NovaBal); } else { transferSuccess = Nova.transfer(_to, _amount); } require(transferSuccess, "safeNovaTransfer: Transfer failed"); } // Safe sNova transfer function, just in case if rounding error causes pool to not have enough SNovas. function safeSNovaTransfer(address _to, uint256 _amount) internal { uint256 sNovaBal = sNova.balanceOf(address(this)); bool transferSuccess = false; if (_amount > sNovaBal) { transferSuccess = sNova.transfer(_to, sNovaBal); } else { transferSuccess = sNova.transfer(_to, _amount); } require(transferSuccess, "safeSNovaTransfer: Transfer failed"); } // Update dev address by the previous dev. function dev(address _devaddr) external { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function setFeeAddress(address _feeAddress) external onlyOwner { feeAddress = _feeAddress; } function updateMinimumEmissionRate(uint256 _minimumEmissionRate) external onlyOwner{ require(minimumEmissionRate > _minimumEmissionRate, "must be lower"); minimumEmissionRate = _minimumEmissionRate; if(NovaPerBlock == minimumEmissionRate){ lastReductionPeriodIndex = block.number.sub(startBlock).div(emissionReductionPeriodBlocks); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/SafeMath.sol"; import "./libs/IBEP20.sol"; import "./libs/SafeBEP20.sol"; import "./libs/Ownable.sol"; import "./interfaces/IMoneyPot.sol"; /* * This contract is used to collect sNova stacking dividends from fee (like swap, deposit on pools or farms) */ contract ShibaMoneyPot is Ownable, IMoneyPot { using SafeBEP20 for IBEP20; using SafeMath for uint256; struct TokenPot { uint256 tokenAmount; // Total amount distributing over 1 cycle (updateMoneyPotPeriodNbBlocks) uint256 accTokenPerShare; // Amount of dividends per Share uint256 lastRewardBlock; // last data update uint256 lastUpdateTokenPotBlocks; // last cycle update for this token } struct UserInfo { uint256 rewardDept; uint256 pending; } IBEP20 public sNova; uint256 public updateMoneyPotPeriodNbBlocks; uint256 public lastUpdateMoneyPotBlocks; uint256 public startBlock; // Start block for dividends distribution (first cycle the current money pot will be empty) // _token => user => rewardsDebt / pending mapping(address => mapping (address => UserInfo)) public sNovaHoldersRewardsInfo; // user => LastSNovaBalanceSaved mapping (address => uint256) public sNovaHoldersInfo; address[] public registeredToken; // List of all token that will be distributed as dividends. Should never be too weight ! mapping (address => bool ) public tokenInitialized; // List of token already added to registeredToken // addressWithoutReward is a map containing each address which are not going to get rewards // At least, it will include the masterChef address as masterChef minting continuously sNova for rewards on Nova pair pool. // We can add later LP contract if someone initialized sNova LP // Those contracts are included as holders on sNova // All dividends attributed to those addresses are going to be added to the "reserveTokenAmount" mapping (address => bool) addressWithoutReward; // address of the feeManager which is allow to add dividends to the pendingTokenPot address public feeManager; mapping (address => TokenPot) private _distributedMoneyPot; // Current MoneyPot mapping (address => uint256 ) public pendingTokenAmount; // Pending amount of each dividends token that will be distributed in next cycle mapping (address => uint256) public reserveTokenAmount; // Bonus which is used to add more dividends in the pendingTokenAmount uint256 public lastSNovaSupply; // Cache the last totalSupply of sNova constructor (IBEP20 _sNova, address _feeManager, address _masterShiba, uint256 _startBlock, uint256 _initialUpdateMoneyPotPeriodNbBlocks) public{ updateMoneyPotPeriodNbBlocks = _initialUpdateMoneyPotPeriodNbBlocks; startBlock = _startBlock; lastUpdateMoneyPotBlocks = _startBlock; sNova = _sNova; addressWithoutReward[_masterShiba] = true; feeManager = _feeManager; } function getRegisteredToken(uint256 index) external virtual override view returns (address){ return registeredToken[index]; } function distributedMoneyPot(address _token) external view returns (uint256 tokenAmount, uint256 accTokenPerShare, uint256 lastRewardBlock ){ return ( _distributedMoneyPot[_token].tokenAmount, _distributedMoneyPot[_token].accTokenPerShare, _distributedMoneyPot[_token].lastRewardBlock ); } function isDividendsToken(address _tokenAddr) external virtual override view returns (bool){ return tokenInitialized[_tokenAddr]; } function updateAddressWithoutReward(address _contract, bool _unattributeDividends) external onlyOwner { addressWithoutReward[_contract] = _unattributeDividends; } function updateFeeManager(address _feeManager) external onlyOwner{ // Allow us to update the feeManager contract => Can be upgraded if needed feeManager = _feeManager; } function getRegisteredTokenLength() external virtual override view returns (uint256){ return registeredToken.length; } function getTokenAmountPotFromMoneyPot(address _token) external view returns (uint256 tokenAmount){ return _distributedMoneyPot[_token].tokenAmount; } // Amount of dividends in a specific token distributed at each block during the current cycle (=updateMoneyPotPeriodNbBlocks) function tokenPerBlock(address _token) external view returns (uint256){ return _distributedMoneyPot[_token].tokenAmount.div(updateMoneyPotPeriodNbBlocks); } function massUpdateMoneyPot() public { uint256 length = registeredToken.length; for (uint256 index = 0; index < length; ++index) { _updateTokenPot(registeredToken[index]); } } function updateCurrentMoneyPot(address _token) external{ _updateTokenPot(_token); } function getMultiplier(uint256 _from, uint256 _to) internal pure returns (uint256){ if(_from >= _to){ return 0; } return _to.sub(_from); } /* Update current dividends for specific token */ function _updateTokenPot(address _token) internal { TokenPot storage tokenPot = _distributedMoneyPot[_token]; if (block.number <= tokenPot.lastRewardBlock) { return; } if (lastSNovaSupply == 0) { tokenPot.lastRewardBlock = block.number; return; } if (block.number >= tokenPot.lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks)){ if(tokenPot.tokenAmount > 0){ uint256 multiplier = getMultiplier(tokenPot.lastRewardBlock, tokenPot.lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks)); uint256 tokenRewardsPerBlock = tokenPot.tokenAmount.div(updateMoneyPotPeriodNbBlocks); tokenPot.accTokenPerShare = tokenPot.accTokenPerShare.add(tokenRewardsPerBlock.mul(multiplier).mul(1e12).div(lastSNovaSupply)); } tokenPot.tokenAmount = pendingTokenAmount[_token]; pendingTokenAmount[_token] = 0; tokenPot.lastRewardBlock = tokenPot.lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks); tokenPot.lastUpdateTokenPotBlocks = tokenPot.lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks); lastUpdateMoneyPotBlocks = tokenPot.lastUpdateTokenPotBlocks; if (block.number >= tokenPot.lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks)){ // If something bad happen in blockchain and moneyPot aren't able to be updated since // return here, will allow us to re-call updatePool manually, instead of directly doing it recursively here // which can cause too much gas error and so break all the MP contract return; } } if(tokenPot.tokenAmount > 0){ uint256 multiplier = getMultiplier(tokenPot.lastRewardBlock, block.number); uint256 tokenRewardsPerBlock = tokenPot.tokenAmount.div(updateMoneyPotPeriodNbBlocks); tokenPot.accTokenPerShare = tokenPot.accTokenPerShare.add(tokenRewardsPerBlock.mul(multiplier).mul(1e12).div(lastSNovaSupply)); } tokenPot.lastRewardBlock = block.number; if (block.number >= tokenPot.lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks)){ lastUpdateMoneyPotBlocks = tokenPot.lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks); } } /* Used by front-end to display user's pending rewards that he can harvest */ function pendingTokenRewardsAmount(address _token, address _user) external view returns (uint256){ if(lastSNovaSupply == 0){ return 0; } uint256 accTokenPerShare = _distributedMoneyPot[_token].accTokenPerShare; uint256 tokenReward = _distributedMoneyPot[_token].tokenAmount.div(updateMoneyPotPeriodNbBlocks); uint256 lastRewardBlock = _distributedMoneyPot[_token].lastRewardBlock; uint256 lastUpdateTokenPotBlocks = _distributedMoneyPot[_token].lastUpdateTokenPotBlocks; if (block.number >= lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks)){ accTokenPerShare = (accTokenPerShare.add( tokenReward.mul(getMultiplier(lastRewardBlock, lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks)) ).mul(1e12).div(lastSNovaSupply))); lastRewardBlock = lastUpdateTokenPotBlocks.add(updateMoneyPotPeriodNbBlocks); tokenReward = pendingTokenAmount[_token].div(updateMoneyPotPeriodNbBlocks); } if (block.number > lastRewardBlock && lastSNovaSupply != 0 && tokenReward > 0) { accTokenPerShare = accTokenPerShare.add( tokenReward.mul(getMultiplier(lastRewardBlock, block.number) ).mul(1e12).div(lastSNovaSupply)); } return (sNova.balanceOf(_user).mul(accTokenPerShare).div(1e12).sub(sNovaHoldersRewardsInfo[_token][_user].rewardDept)) .add(sNovaHoldersRewardsInfo[_token][_user].pending); } /* Update tokenPot, user's sNova balance (cache) and pending dividends */ function updateSNovaHolder(address _sNovaHolder) external virtual override { uint256 holderPreviousSNovaAmount = sNovaHoldersInfo[_sNovaHolder]; uint256 holderBalance = sNova.balanceOf(_sNovaHolder); uint256 length = registeredToken.length; for (uint256 index = 0; index < length; ++index) { _updateTokenPot(registeredToken[index]); TokenPot storage tokenPot = _distributedMoneyPot[registeredToken[index]]; if(holderPreviousSNovaAmount > 0 && tokenPot.accTokenPerShare > 0){ uint256 pending = holderPreviousSNovaAmount.mul(tokenPot.accTokenPerShare).div(1e12).sub(sNovaHoldersRewardsInfo[registeredToken[index]][_sNovaHolder].rewardDept); if(pending > 0) { if (addressWithoutReward[_sNovaHolder]) { if(sNovaHoldersRewardsInfo[registeredToken[index]][_sNovaHolder].pending > 0){ pending = pending.add(sNovaHoldersRewardsInfo[registeredToken[index]][_sNovaHolder].pending); sNovaHoldersRewardsInfo[registeredToken[index]][_sNovaHolder].pending = 0; } reserveTokenAmount[registeredToken[index]] = reserveTokenAmount[registeredToken[index]].add(pending); } else { sNovaHoldersRewardsInfo[registeredToken[index]][_sNovaHolder].pending = sNovaHoldersRewardsInfo[registeredToken[index]][_sNovaHolder].pending.add(pending); } } } sNovaHoldersRewardsInfo[registeredToken[index]][_sNovaHolder].rewardDept = holderBalance.mul(tokenPot.accTokenPerShare).div(1e12); } if (holderPreviousSNovaAmount > 0){ lastSNovaSupply = lastSNovaSupply.sub(holderPreviousSNovaAmount); } lastSNovaSupply = lastSNovaSupply.add(holderBalance); sNovaHoldersInfo[_sNovaHolder] = holderBalance; } function harvestRewards(address _sNovaHolder) external { uint256 length = registeredToken.length; for (uint256 index = 0; index < length; ++index) { harvestReward(_sNovaHolder, registeredToken[index]); } } /* * Allow user to harvest their pending dividends */ function harvestReward(address _sNovaHolder, address _token) public { uint256 holderBalance = sNovaHoldersInfo[_sNovaHolder]; _updateTokenPot(_token); TokenPot storage tokenPot = _distributedMoneyPot[_token]; if(holderBalance > 0 && tokenPot.accTokenPerShare > 0){ uint256 pending = holderBalance.mul(tokenPot.accTokenPerShare).div(1e12).sub(sNovaHoldersRewardsInfo[_token][_sNovaHolder].rewardDept); if(pending > 0) { if (addressWithoutReward[_sNovaHolder]) { if(sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending > 0){ pending = pending.add(sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending); sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending = 0; } reserveTokenAmount[_token] = reserveTokenAmount[_token].add(pending); } else { sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending = sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending.add(pending); } } } if ( sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending > 0 ){ safeTokenTransfer(_token, _sNovaHolder, sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending); sNovaHoldersRewardsInfo[_token][_sNovaHolder].pending = 0; } sNovaHoldersRewardsInfo[_token][_sNovaHolder].rewardDept = holderBalance.mul(tokenPot.accTokenPerShare).div(1e12); } /* * Used by feeManager contract to deposit rewards (collected from many sources) */ function depositRewards(address _token, uint256 _amount) external virtual override{ require(msg.sender == feeManager); massUpdateMoneyPot(); IBEP20(_token).safeTransferFrom(msg.sender, address(this), _amount); if(block.number < startBlock){ reserveTokenAmount[_token] = reserveTokenAmount[_token].add(_amount); } else { pendingTokenAmount[_token] = pendingTokenAmount[_token].add(_amount); } } /* * Used by dev to deposit bonus rewards that can be added to pending pot at any time */ function depositBonusRewards(address _token, uint256 _amount) external onlyOwner{ IBEP20(_token).safeTransferFrom(msg.sender, address(this), _amount); reserveTokenAmount[_token] = reserveTokenAmount[_token].add(_amount); } /* * Allow token address to be distributed as dividends to sNova holder */ function addTokenToRewards(address _token) external onlyOwner{ if (!tokenInitialized[_token]){ registeredToken.push(_token); _distributedMoneyPot[_token].lastRewardBlock = lastUpdateMoneyPotBlocks > block.number ? lastUpdateMoneyPotBlocks : lastUpdateMoneyPotBlocks.add(updateMoneyPotPeriodNbBlocks); _distributedMoneyPot[_token].accTokenPerShare = 0; _distributedMoneyPot[_token].tokenAmount = 0; _distributedMoneyPot[_token].lastUpdateTokenPotBlocks = _distributedMoneyPot[_token].lastRewardBlock; tokenInitialized[_token] = true; } } /* Remove token address to be distributed as dividends to sNova holder */ function removeTokenToRewards(address _token) external onlyOwner{ require(_distributedMoneyPot[_token].tokenAmount == 0, "cannot remove before end of distribution"); if (tokenInitialized[_token]){ uint256 length = registeredToken.length; uint256 indexToRemove = length; // If token not found web do not try to remove bad index for (uint256 index = 0; index < length; ++index) { if(registeredToken[index] == _token){ indexToRemove = index; break; } } if(indexToRemove < length){ // Should never be false.. Or something wrong happened registeredToken[indexToRemove] = registeredToken[registeredToken.length-1]; registeredToken.pop(); } tokenInitialized[_token] = false; return; } } /* Used by front-end to get the next moneyPot cycle update */ function nextMoneyPotUpdateBlock() external view returns (uint256){ return lastUpdateMoneyPotBlocks.add(updateMoneyPotPeriodNbBlocks); } function addToPendingFromReserveTokenAmount(address _token, uint256 _amount) external onlyOwner{ require(_amount <= reserveTokenAmount[_token], "Insufficient amount"); reserveTokenAmount[_token] = reserveTokenAmount[_token].sub(_amount); pendingTokenAmount[_token] = pendingTokenAmount[_token].add(_amount); } // Safe Token transfer function, just in case if rounding error causes pool to not have enough Tokens. function safeTokenTransfer(address _token, address _to, uint256 _amount) internal { IBEP20 token = IBEP20(_token); uint256 tokenBal = token.balanceOf(address(this)); bool transferSuccess = false; if (_amount > tokenBal) { transferSuccess = token.transfer(_to, tokenBal); } else { transferSuccess = token.transfer(_to, _amount); } require(transferSuccess, "safeSNovaTransfer: Transfer failed"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/Ownable.sol"; import "./libs/SafeMath.sol"; import "./libs/IBEP20.sol"; import "./libs/SafeBEP20.sol"; import "./interfaces/IMoneyPot.sol"; import "./interfaces/IShibaRouter02.sol"; import "./interfaces/IShibaPair.sol"; /* The FeeManager is a kind of contract-wallet that allow the owner to unbind (LP) and swap tokens to BNB/BUSD before sending them to the Money Pot */ contract FeeManager is Ownable{ using SafeMath for uint256; using SafeBEP20 for IBEP20; uint256 public moneyPotShare; uint256 public teamShare; IMoneyPot public moneyPot; IShibaRouter02 public router; IBEP20 public Nova; address public teamAddr; // Used for dev/marketing and others funds for project address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; constructor (IBEP20 _Nova, address _teamAddr, uint256 _moneyPotShare) public{ Nova = _Nova; teamAddr = _teamAddr; /*swap fees team wallet*/ moneyPotShare = _moneyPotShare; teamShare = 10000 - moneyPotShare; } function removeLiquidityToToken(address _token) external onlyOwner{ IShibaPair _pair = IShibaPair(_token); uint256 _amount = _pair.balanceOf(address(this)); address token0 = _pair.token0(); address token1 = _pair.token1(); _pair.approve(address(router), _amount); router.removeLiquidity(token0, token1, _amount, 0, 0, address(this), block.timestamp.add(100)); } function swapBalanceToToken(address _token0, address _token1) external onlyOwner { require(_token0 != address(Nova), "Nova can only be burn"); uint256 _amount = IBEP20(_token0).balanceOf(address(this)); IBEP20(_token0).approve(address(router), _amount); address[] memory path = new address[](2); path[0] = _token0; path[1] = _token1; router.swapExactTokensForTokens(_amount, 0, path, address(this), block.timestamp.add(100)); } function swapToToken(address _token0, address _token1, uint256 _token0Amount) external onlyOwner { require(_token0 != address(Nova), "Nova can only be burn"); IBEP20(_token0).approve(address(router), _token0Amount); address[] memory path = new address[](2); path[0] = _token0; path[1] = _token1; router.swapExactTokensForTokens(_token0Amount, 0, path, address(this), block.timestamp.add(100)); } function updateShares(uint256 _moneyPotShare) external onlyOwner{ require(_moneyPotShare <= 10000, "Invalid percent"); require(_moneyPotShare >= 7500, "Moneypot share must be at least 75%"); moneyPotShare = _moneyPotShare; teamShare = 10000 - moneyPotShare; } function setTeamAddr(address _newTeamAddr) external onlyOwner{ teamAddr = _newTeamAddr; } function setupRouter(address _router) external onlyOwner{ router = IShibaRouter02(_router); } function setupMoneyPot(IMoneyPot _moneyPot) external onlyOwner{ moneyPot = _moneyPot; } /* distribute fee to the moneypot and dev wallet */ function distributeFee() external onlyOwner { uint256 length = moneyPot.getRegisteredTokenLength(); for (uint256 index = 0; index < length; ++index) { IBEP20 _curToken = IBEP20(moneyPot.getRegisteredToken(index)); uint256 _amount = _curToken.balanceOf(address(this)); uint256 _moneyPotAmount = _amount.mul(moneyPotShare).div(10000); _curToken.approve(address(moneyPot), _moneyPotAmount); moneyPot.depositRewards(address(_curToken), _moneyPotAmount); _curToken.safeTransfer(teamAddr, _amount.sub(_moneyPotAmount)); } if (Nova.balanceOf(address(this)) > 0){ Nova.transfer(BURN_ADDRESS, Nova.balanceOf(address(this))); } } }// 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; } } // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol // 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. // // Ctrl+f for XXX to see all the modifications. pragma solidity 0.6.12; import "./libs/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 = 0 hours; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public adminInitialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay mustn't exceed minimum delay"); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay mustn't exceed maximum delay"); admin = admin_; delay = delay_; adminInitialized = false; } 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 mustn't 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 (adminInitialized) { 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"); adminInitialized = 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); } /* solhint-disable-next-line avoid-call-value avoid-low-level-calls */ (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) { /* solhint-disable-next-line not-rely-on-time */ return block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/ShibaBEP20.sol"; contract NovaToken is ShibaBEP20("Shiba NOVA", "NOVA") { address public sNova; /* * @dev Throws if called by any account other than the owner or sNova */ modifier onlyOwnerOrSNova() { require(isOwner() || isSNova(), "caller is not the owner or sNova"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == owner(); } /** * @dev Returns true if the caller is sNova contracts. */ function isSNova() internal view returns (bool) { return msg.sender == address(sNova); } function setupSNova(address _sNova) external onlyOwner{ sNova = _sNova; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterShiba). function mint(address _to, uint256 _amount) external virtual override onlyOwnerOrSNova { _mint(_to, _amount); } /// @dev overrides transfer function to meet tokenomics of Nova function _transfer(address sender, address recipient, uint256 amount) internal virtual override { require(amount > 0, "amount 0"); if (recipient == BURN_ADDRESS) { super._burn(sender, amount); } else { // 2% of every transfer burnt uint256 burnAmount = amount.mul(2).div(100); // 98% of transfer sent to recipient uint256 sendAmount = amount.sub(burnAmount); require(amount == sendAmount + burnAmount, "Nova::transfer: Burn value invalid"); super._burn(sender, burnAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } }// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title Multicall - Aggregate results from multiple read-only function calls /// @author Michael Elliot <mike@makerdao.com> /// @author Joshua Levine <joshua@makerdao.com> /// @author Nick Johnson <arachnid@notdot.net> contract Multicall { struct Call { address target; bytes callData; } function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) { blockNumber = block.number; returnData = new bytes[](calls.length); for(uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); require(success); returnData[i] = ret; } } // Helper functions function getEthBalance(address addr) public view returns (uint256 balance) { balance = addr.balance; } function getBlockHash(uint256 blockNumber) public view returns (bytes32 blockHash) { blockHash = blockhash(blockNumber); } function getLastBlockHash() public view returns (bytes32 blockHash) { blockHash = blockhash(block.number - 1); } function getCurrentBlockTimestamp() public view returns (uint256 timestamp) { timestamp = block.timestamp; } function getCurrentBlockDifficulty() public view returns (uint256 difficulty) { difficulty = block.difficulty; } function getCurrentBlockGasLimit() public view returns (uint256 gaslimit) { gaslimit = block.gaslimit; } function getCurrentBlockCoinbase() public view returns (address coinbase) { coinbase = block.coinbase; } }// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/SafeMath.sol"; import "./libs/ShibaBEP20.sol"; import "./interfaces/IMoneyPot.sol"; // SNovaToken with Governance. contract SNovaToken is ShibaBEP20("ShibaNova share token sNova", "sNova") { using SafeMath for uint256; struct HolderInfo { uint256 avgTransactionBlock; } IMoneyPot public moneyPot; ShibaBEP20 public Nova; bool private _isNovaSetup = false; bool private _isMoneyPotSetup = false; uint256 public immutable SWAP_PENALTY_MAX_PERIOD ; // after 72h penalty of holding sNova. Swap penalty is at the minimum uint256 public immutable SWAP_PENALTY_MAX_PER_SNova ; // 30% => 1 sNova = 0.3 Nova mapping(address => HolderInfo) public holdersInfo; constructor (uint256 swapPenaltyMaxPeriod, uint256 swapPenaltyMaxPerSNova) public{ SWAP_PENALTY_MAX_PERIOD = swapPenaltyMaxPeriod; // default 28800: after 24h penalty of holding sNova. Swap penalty is at the minimum SWAP_PENALTY_MAX_PER_SNova = swapPenaltyMaxPerSNova.mul(1e10); // default: 30, 30% => 1 sNova = 0.3 Nova } function setupNova(ShibaBEP20 _Nova) external onlyOwner { require(!_isNovaSetup); Nova = _Nova; _isNovaSetup = true; } function setupMoneyPot(IMoneyPot _moneyPot) external onlyOwner { require(!_isMoneyPotSetup); moneyPot = _moneyPot; _isMoneyPotSetup = true; } /* Calculate the penality for swapping sNova to Nova for a user. The penality decrease over time (by holding duration). From SWAP_PENALTY_MAX_PER_SNova % to 0% on SWAP_PENALTY_MAX_PERIOD */ function getPenaltyPercent(address _holderAddress) public view returns (uint256){ HolderInfo storage holderInfo = holdersInfo[_holderAddress]; if(block.number >= holderInfo.avgTransactionBlock.add(SWAP_PENALTY_MAX_PERIOD)){ return 0; } if(block.number == holderInfo.avgTransactionBlock){ return SWAP_PENALTY_MAX_PER_SNova; } uint256 avgHoldingDuration = block.number.sub(holderInfo.avgTransactionBlock); return SWAP_PENALTY_MAX_PER_SNova.sub( SWAP_PENALTY_MAX_PER_SNova.mul(avgHoldingDuration).div(SWAP_PENALTY_MAX_PERIOD) ); } /* Allow use to exchange (swap) their sNova to Nova */ function swapToNova(uint256 _amount) external { require(_amount > 0, "amount 0"); address _from = msg.sender; uint256 NovaAmount = _swapNovaAmount( _from, _amount); holdersInfo[_from].avgTransactionBlock = _getAvgTransactionBlock(_from, holdersInfo[_from], _amount, true); super._burn(_from, _amount); Nova.mint(_from, NovaAmount); if (address(moneyPot) != address(0)) { moneyPot.updateSNovaHolder(_from); } } /* @notice Preview swap return in Nova with _sNovaAmount by _holderAddress * this function is used by front-end to show how much Nova will be retrieve if _holderAddress swap _sNovaAmount */ function previewSwapNovaExpectedAmount(address _holderAddress, uint256 _sNovaAmount) external view returns (uint256 expectedNova){ return _swapNovaAmount( _holderAddress, _sNovaAmount); } /* @notice Calculate the adjustment for a user if he want to swap _sNovaAmount to Nova */ function _swapNovaAmount(address _holderAddress, uint256 _sNovaAmount) internal view returns (uint256 expectedNova){ require(balanceOf(_holderAddress) >= _sNovaAmount, "Not enough sNova"); uint256 penalty = getPenaltyPercent(_holderAddress); if(penalty == 0){ return _sNovaAmount; } return _sNovaAmount.sub(_sNovaAmount.mul(penalty).div(1e12)); } /* @notice Calculate average deposit/withdraw block for _holderAddress */ function _getAvgTransactionBlock(address _holderAddress, HolderInfo storage holderInfo, uint256 _sNovaAmount, bool _onWithdraw) internal view returns (uint256){ if (balanceOf(_holderAddress) == 0) { return block.number; } uint256 transactionBlockWeight; if (_onWithdraw) { if (balanceOf(_holderAddress) == _sNovaAmount) { return 0; } else { return holderInfo.avgTransactionBlock; } } else { transactionBlockWeight = (balanceOf(_holderAddress).mul(holderInfo.avgTransactionBlock).add(block.number.mul(_sNovaAmount))); } return transactionBlockWeight.div(balanceOf(_holderAddress).add(_sNovaAmount)); } /// @notice Creates `_amount` token to `_to`. function mint(address _to, uint256 _amount) external virtual override onlyOwner { HolderInfo storage holder = holdersInfo[_to]; holder.avgTransactionBlock = _getAvgTransactionBlock(_to, holder, _amount, false); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); if (address(moneyPot) != address(0)) { moneyPot.updateSNovaHolder(_to); } } /// @dev overrides transfer function to meet tokenomics of SNova function _transfer(address _sender, address _recipient, uint256 _amount) internal virtual override { holdersInfo[_sender].avgTransactionBlock = _getAvgTransactionBlock(_sender, holdersInfo[_sender], _amount, true); if (_recipient == BURN_ADDRESS) { super._burn(_sender, _amount); if (address(moneyPot) != address(0)) { moneyPot.updateSNovaHolder(_sender); } } else { holdersInfo[_recipient].avgTransactionBlock = _getAvgTransactionBlock(_recipient, holdersInfo[_recipient], _amount, false); super._transfer(_sender, _recipient, _amount); if (address(moneyPot) != address(0)) { moneyPot.updateSNovaHolder(_sender); if (_sender != _recipient){ moneyPot.updateSNovaHolder(_recipient); } } } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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 Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { 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 ) external { 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), "Nova::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Nova::delegateBySig: invalid nonce"); require(now <= expiry, "Nova::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 (uint256) { 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) external view returns (uint256) { require(blockNumber < block.number, "Nova::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]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying Novas (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Nova::_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 getChainId() internal pure returns (uint) { uint256 chainId; assembly {chainId := chainid()} return chainId; } }
Public SMART CONTRACT AUDIT REPORT for ShibaNova Prepared By: Yiqun Chen PeckShield July 20, 2021 1/26 PeckShield Audit Report #: 2021-195Public Document Properties Client ShibaNova Title Smart Contract Audit Report Target ShibaNova Version 1.0 Author Xuxian Jiang Auditors Jing Wang, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 July 20, 2021 Xuxian Jiang Final Release 1.0-rc1 July 13, 2021 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/26 PeckShield Audit Report #: 2021-195Public Contents 1 Introduction 4 1.1 About ShibaNova . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Trading Fee Discrepancy Between ShibaSwap And ShibaNova . . . . . . . . . . . . . 12 3.2 Sybil Attacks on sNova Voting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.3 Accommodation of Non-Compliant ERC20 Tokens . . . . . . . . . . . . . . . . . . . 16 3.4 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.5 Timely massUpdatePools During Pool Weight Changes . . . . . . . . . . . . . . . . 19 3.6 Inconsistency Between Document and Implementation . . . . . . . . . . . . . . . . . 20 3.7 Redundant Code Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.8 Reentrancy Risk in deposit()/withdraw()/harvestReward() . . . . . . . . . . . . . . . 22 4 Conclusion 24 References 25 3/26 PeckShield Audit Report #: 2021-195Public 1 | Introduction Given the opportunity to review the ShibaNova design document and related smart contract source code, we outline in the report our systematic approach to evaluate potential security issues in the smartcontractimplementation,exposepossiblesemanticinconsistenciesbetweensmartcontractcode 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 ShibaNova ShibaNova is a decentralized exchange and automatic market maker built on the Binance Smart Chain (BSC). The goal is to solve one of the fundamental problems in decentralized finance (DeFi), where the project’s native token rises in value at launch only to incrementally decrease in value day after day until it ultimately goes down to zero. The solution is effectively turning our investors into valued shareholders - eligible to get their share of 75~of fees collected in the dApp. By providing liquidity to the project and creating/holding the related dividend tokens, the shareholders are able to earn daily passive income. This daily dividends system not only incentivizes long-term holding but promotes ownership of the project by the entire community. The basic information of ShibaNova is as follows: Table 1.1: Basic Information of ShibaNova ItemDescription IssuerShibaNova Website http://www.ShibaNova.io TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report July 20, 2021 4/26 PeckShield Audit Report #: 2021-195Public In the following, we show the Git repository of reviewed files and the commit hash values used in this audit. •https://github.com/ShibaNova/Contracts.git (b6b1ce1) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/ShibaNova/Contracts.git (6b221ae) 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 the 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. 5/26 PeckShield Audit Report #: 2021-195Public 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 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) [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. 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 6/26 PeckShield Audit Report #: 2021-195Public 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 7/26 PeckShield Audit Report #: 2021-195Public 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/26 PeckShield Audit Report #: 2021-195Public 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/26 PeckShield Audit Report #: 2021-195Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the implementation of the ShibaNova protocol. 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 1 Medium 1 Low 4 Informational 2 Total 8 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/26 PeckShield Audit Report #: 2021-195Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improvedbyresolvingtheidentifiedissues(showninTable2.1), including 1high-severityvulnerability, 1medium-severity vulnerability, 4low-severity vulnerabilities, and 2informational recommendations. Table 2.1: Key ShibaNova Audit Findings ID Severity Title Category Status PVE-001 High Trading Fee Discrepancy Between ShibaSwap And ShibaNovaBusiness Logic Fixed PVE-002 Low Sybil Attacks on sNova Voting Business Logic Fixed PVE-003 Low Accommodation of Non-ERC20- Compliant TokensCoding Practices Confirmed PVE-004 Medium Trust Issue of Admin Keys Security Features Confirmed PVE-005 Low Timely massUpdatePools During Pool Weight ChangesBusiness Logic Fixed PVE-006 Informational Inconsistency Between Document And ImplementationCoding Practices Fixed PVE-007 Informational Redundant Code Removal Coding Practices Fixed PVE-008 Low Reentrancy Risk in de- posit()/withdraw()/harvestReward()Coding Practices Fixed 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. 11/26 PeckShield Audit Report #: 2021-195Public 3 | Detailed Results 3.1 Trading Fee Discrepancy Between ShibaSwap And ShibaNova •ID: PVE-001 •Severity: High •Likelihood: High •Impact: Medium•Target: Multiple Contracts •Category: Business Logic [9] •CWE subcategory: CWE-841 [6] Description As a decentralized exchange and automatic market maker, the ShibaNova protocol has a constant need to convert one token to another. With the built-in ShibaSwap , if you make a token swap or trade on the exchange, you will need to pay a 0:2~trading fee, which is split into two parts. The first part is returned to liquidity pools in the form of a fee reward for liquidity providers while the second part is sent to the feeManager for distribution. To elaborate, we show below the getAmountOut() routine inside the the ShibaLibrary . For com- parison, we also show the swap()routine in ShibaPair . It is interesting to note that ShibaPair has implicitly assumed the trading fee is 0:2~, instead of 0:16~inShibaLibrary . The difference in the built-in trading fee may deviate the normal operations of a number of helper routines in ShibaRouter . 43 // given an input amount of an asset and pair reserves , returns the maximum output amount of the other asset 44 function getAmountOut ( uint amountIn , uint reserveIn , uint reserveOut ) internal pure returns ( uint amountOut ) { 45 require ( amountIn > 0, ’ ShibaLibrary : INSUFFICIENT_INPUT_AMOUNT ’); 46 require ( reserveIn > 0 && reserveOut > 0, ’ ShibaLibrary : INSUFFICIENT_LIQUIDITY ’) ; 47 uint amountInWithFee = amountIn . mul (9984) ; 48 uint numerator = amountInWithFee . mul( reserveOut ); 49 uint denominator = reserveIn . mul (10000) . add ( amountInWithFee ); 50 amountOut = numerator / denominator ; 51 } 12/26 PeckShield Audit Report #: 2021-195Public 52 53 // given an output amount of an asset and pair reserves , returns a required input amount of the other asset 54 function getAmountIn ( uint amountOut , uint reserveIn , uint reserveOut ) internal pure returns ( uint amountIn ) { 55 require ( amountOut > 0, ’ ShibaLibrary : INSUFFICIENT_OUTPUT_AMOUNT ’); 56 require ( reserveIn > 0 && reserveOut > 0, ’ ShibaLibrary : INSUFFICIENT_LIQUIDITY ’) ; 57 uint numerator = reserveIn . mul ( amountOut ).mul (10000) ; 58 uint denominator = reserveOut . sub ( amountOut ). mul (9984) ; 59 amountIn = ( numerator / denominator ). add (1) ; 60 } Listing 3.1: ShibaLibrary::getAmountOut() 160 function swap ( uint amount0Out , uint amount1Out , address to , bytes calldata data ) external lock { 161 require ( amount0Out > 0 amount1Out > 0, ’ShibaSwap : INSUFFICIENT_OUTPUT_AMOUNT ’) ; 162 ( uint112 _reserve0 , uint112 _reserve1 ,) = getReserves (); // gas savings 163 require ( amount0Out < _reserve0 && amount1Out < _reserve1 , ’ShibaSwap : INSUFFICIENT_LIQUIDITY ’); 164 165 uint balance0 ; 166 uint balance1 ; 167 { // scope for _token {0 ,1} , avoids stack too deep errors 168 address _token0 = token0 ; 169 address _token1 = token1 ; 170 require (to != _token0 && to != _token1 , ’ShibaSwap : INVALID_TO ’); 171 if ( amount0Out > 0) _safeTransfer ( _token0 , to , amount0Out ); // optimistically transfer tokens 172 if ( amount1Out > 0) _safeTransfer ( _token1 , to , amount1Out ); // optimistically transfer tokens 173 if ( data . length > 0) IShibaCallee (to). shibaCall ( msg. sender , amount0Out , amount1Out , data ); 174 balance0 = IERC20 ( _token0 ). balanceOf ( address ( this )); 175 balance1 = IERC20 ( _token1 ). balanceOf ( address ( this )); 176 } 177 uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - ( _reserve0 - amount0Out ) : 0; 178 uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - ( _reserve1 - amount1Out ) : 0; 179 require ( amount0In > 0 amount1In > 0, ’ShibaSwap : INSUFFICIENT_INPUT_AMOUNT ’); 180 { // scope for reserve {0 ,1} Adjusted , avoids stack too deep errors 181 uint balance0Adjusted = balance0 . mul (10000) . sub ( amount0In .mul (20) ); 182 uint balance1Adjusted = balance1 . mul (10000) . sub ( amount1In .mul (20) ); 183 require ( balance0Adjusted . mul ( balance1Adjusted ) >= uint ( _reserve0 ).mul ( _reserve1 ) . mul (10000**2) , ’ShibaSwap : K’); 184 } 185 186 _update ( balance0 , balance1 , _reserve0 , _reserve1 ); 187 emit Swap (msg. sender , amount0In , amount1In , amount0Out , amount1Out , to); 13/26 PeckShield Audit Report #: 2021-195Public 188 } Listing 3.2: ShibaPair::swap() Recommendation Make the built-in trading fee in ShibaNova consistent with the actual trading fee in ShibaPair . Status This issue has been fixed in this commit: e7041e5. 3.2 Sybil Attacks on sNova Voting •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: SNovaToken •Category: Business Logic [9] •CWE subcategory: CWE-841 [6] Description InShibaNova , there is a protocol-related token, i.e., SNovaToken (sNova) , which has been enhanced with the functionality to cast and record the votes. Moreover, the sNovacontract allows for dynamic delegation of a voter to another, though the delegation is not transitive. When a submitted proposal is being tallied, the votes are counted prior to the proposal’s activation. Our analysis with the sNovatoken shows that the current token contract is vulnerable to a so- called Sybilattacks1. For elaboration, let’s assume at the very beginning there is a malicious actor named Malice, who owns 100 sNovatokens. Malicehas an accomplice named Trudywho currently has0balance of sNova. This Sybilattack can be launched as follows: 319 function _delegate ( address delegator , address delegatee ) 320 internal 321 { 322 address currentDelegate = _delegates [ delegator ]; 323 uint256 delegatorBalance = balanceOf ( delegator ); 324 // balance of underlying Novas (not scaled ); 325 _delegates [ delegator ] = delegatee ; 326 327 emit DelegateChanged ( delegator , currentDelegate , delegatee ); 328 329 _moveDelegates ( currentDelegate , delegatee , delegatorBalance ); 330 } 331 332 function _moveDelegates ( address srcRep , address dstRep , uint256 amount ) internal { 333 if ( srcRep != dstRep && amount > 0) { 1The same issue occurs to the SUSHI token and the credit goes to Jong Seok Park[12]. 14/26 PeckShield Audit Report #: 2021-195Public 334 if ( srcRep != address (0) ) { 335 // decrease old representative 336 uint32 srcRepNum = numCheckpoints [ srcRep ]; 337 uint256 srcRepOld = srcRepNum > 0 ? checkpoints [ srcRep ][ srcRepNum - 1]. votes : 0; 338 uint256 srcRepNew = srcRepOld .sub ( amount ); 339 _writeCheckpoint ( srcRep , srcRepNum , srcRepOld , srcRepNew ); 340 } 341 342 if ( dstRep != address (0) ) { 343 // increase new representative 344 uint32 dstRepNum = numCheckpoints [ dstRep ]; 345 uint256 dstRepOld = dstRepNum > 0 ? checkpoints [ dstRep ][ dstRepNum - 1]. votes : 0; 346 uint256 dstRepNew = dstRepOld .add ( amount ); 347 _writeCheckpoint ( dstRep , dstRepNum , dstRepOld , dstRepNew ); 348 } 349 } 350 } Listing 3.3: SNovaToken.sol 1.Maliceinitially delegates the voting to Trudy. Right after the initial delegation, Trudycan have 100votes if he chooses to cast the vote. 2.Malicetransfers the full 100balance to M1who also delegates the voting to Trudy. Right after this delegation, Trudycan have 200votes if he chooses to cast the vote. The reason is that the SushiToken contract’s transfer() does NOT _moveDelegates() together. In other words, even now Malicehas0balance, the initial delegation (of Malice) to Trudywill not be affected, therefore Trudystill retains the voting power of 100 sNova. When M1delegates to Trudy, since M1now has 100 sNova,Trudywill get additional 100votes, totaling 200votes. 3. We can repeat by transferring Mi’s100 sNovabalance to Mi+1who also delegates the votes toTrudy. Every iteration will essentially add 100voting power to Trudy. In other words, we can effectively amplify the voting powers of Trudyarbitrarily with new accounts created and iterated! Recommendation To mitigate, it is necessary to accompany every single transfer() and transferFrom() with the _moveDelegates() so that the voting power of the sender’s delegate will be movedto thedestination’sdelegate. Bydoingso, wecaneffectivelymitigate theabove Sybilattacks. Status This issue has been fixed in this commit: e7041e5. 15/26 PeckShield Audit Report #: 2021-195Public 3.3 Accommodation of Non-Compliant ERC20 Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [8] •CWE subcategory: CWE-1126 [2] Description ThoughthereisastandardizedERC-20specification, manytokencontractsmaynotstrictlyfollowthe specification or have additional functionalities beyond the specification. In this section, we examine the transfer() routine and 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. Specifically, the transfer() routine does not have a return value defined and implemented. However, the IERC20interface has defined the transfer() interface with a boolreturn value. As a result, the call to transfer() may expect a return value. With the lack of return value ofUSDT’stransfer() , the call will be unfortunately reverted. 126 function transfer ( address _to , uint _value ) public onlyPayloadSize (2 * 32) { 127 uint fee = ( _value . mul ( basisPointsRate )). div (10000) ; 128 if ( fee > maximumFee ) { 129 fee = maximumFee ; 130 } 131 uint sendAmount = _value . sub( fee); 132 balances [msg . sender ] = balances [msg . sender ]. sub ( _value ); 133 balances [_to ] = balances [ _to ]. add ( sendAmount ); 134 if ( fee > 0) { 135 balances [ owner ] = balances [ owner ]. add ( fee ); 136 Transfer (msg .sender , owner , fee ); 137 } 138 Transfer (msg .sender , _to , sendAmount ); 139 } Listing 3.4: USDT::transfer() Because of that, a normal call to transfer() is suggested to use the safe version, i.e., safeTransfer (), Inessence, itisawrapperaroundERC20operationsthatmayeitherthrowonfailureorreturnfalse 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 approve()/transferFrom() as well, i.e., safeApprove()/safeTransferFrom() . In current implementation, if we examine the PresaleContract::swap() routine that is designed to fund-raising by swapping the input token0totoken1To accommodate the specific idiosyncrasy, 16/26 PeckShield Audit Report #: 2021-195Public there is a need to use safeTransferFrom() (instead of transferFrom() - line 172) and safeTransfer() (instead of transfer() - line 176). 161 function swap ( uint256 inAmount ) public onlyWhitelisted { 162 uint256 quota = token1 . balanceOf ( address ( this )); 163 uint256 total = token0 . balanceOf ( msg. sender ); 164 uint256 outAmount = inAmount . mul (1000) . div ( swapRate ); 167 require ( isSwapStarted == true , ’ ShibanovaSwap :: Swap not started ’); 168 require ( inAmount <= total , " ShibanovaSwap :: Insufficient funds "); 169 require ( outAmount <= quota , " ShibanovaSwap :: Quota not enough "); 170 require ( spent [ msg. sender ]. add( inAmount ) <= maxBuy , " ShibanovaSwap : : Reached Max Buy "); 172 token0 . transferFrom ( msg . sender , address ( Payee ), inAmount ); 174 spent [ msg . sender ] = spent [ msg . sender ] + inAmount ; 176 token1 . transfer ( msg . sender , outAmount ); 178 emit Swap (msg. sender , inAmount , outAmount ); 179 } Listing 3.5: PresaleContract::swap() Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related approve()/transfer()/transferFrom() . Status This issue has been confirmed. 3.4 Trust Issue of Admin Keys •ID: PVE-004 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Security Features [7] •CWE subcategory: CWE-287 [3] Description In the ShibaNova protocol, there is a special owneraccount that plays a critical role in governing and regulating the protocol-wide operations (e.g., set various parameters and add/remove reward pools). 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 owneraccount as well as related privileged opeations. 17/26 PeckShield Audit Report #: 2021-195Public To elaborate, we show below two example functions, i.e., setFeeAmount() and set(). The first one allows for dynamic allocation on the trading fee between liquidity providers and feeManager while the second one may specify deposit fee for staking. 66 function setFeeAmount ( uint16 _newFeeAmount ) external { 67 // This parameter allow us to lower the fee which will be send to the feeManager 68 // 20 = 0.20% ( all fee goes directly to the feeManager ) 69 // If we update it to 10 for example , 0.10% are going to LP holder and 0.10% to the feeManager 70 require ( msg . sender == owner () , " caller is not the owner "); 71 require ( _newFeeAmount <= 20, " amount too big "); 72 _feeAmount = _newFeeAmount ; 73 } Listing 3.6: ShibaFactory::setFeeAmount() 158 // Update the given pool ’s Nova allocation point . Can only be called by the owner . 159 function set ( uint256 _pid , uint256 _allocPoint , uint256 _depositFeeBP , bool _isSNovaRewards , bool _withUpdate ) external onlyOwner { 160 require ( _depositFeeBP <= 400 , " set : invalid deposit fee basis points "); 161 massUpdatePools (); 162 uint256 prevAllocPoint = poolInfo [ _pid ]. allocPoint ; 163 poolInfo [ _pid ]. allocPoint = _allocPoint ; 164 poolInfo [ _pid ]. depositFeeBP = _depositFeeBP ; 165 poolInfo [ _pid ]. isSNovaRewards = _isSNovaRewards ; 166 if ( prevAllocPoint != _allocPoint ) { 167 totalAllocPoint = totalAllocPoint . sub ( prevAllocPoint ). add ( _allocPoint ); 168 } 169 } Listing 3.7: MasterShiba::set() We understand the need of the privileged functions for contract maintenance, but at the same time the extra power to the owner may also be a counter-party risk to the protocol users. It is worrisome if the privileged owneraccount 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. 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. 18/26 PeckShield Audit Report #: 2021-195Public 3.5 Timely massUpdatePools During Pool Weight Changes •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterShiba •Category: Business Logic [9] •CWE subcategory: CWE-841 [6] Description The ShibaNova protocol provides incentive mechanisms that reward the staking of supported assets. The rewards are carried out by designating a number of staking pools into which supported assets can be staked. And staking users are rewarded in proportional to their share of LP tokens in the reward pool. The reward pools can be dynamically added via add()and the weights of supported pools can be adjusted via set(). When analyzing the pool weight update routine set(), we notice the need of timely invoking massUpdatePools() to update the reward distribution before the new pool weight becomes effective. 158 // Update the given pool ’s Nova allocation point . Can only be called by the owner . 159 function set ( uint256 _pid , uint256 _allocPoint , uint256 _depositFeeBP , bool _isSNovaRewards , bool _withUpdate ) external onlyOwner { 160 require ( _depositFeeBP <= 400 , " set : invalid deposit fee basis points "); 161 if ( _withUpdate ) { 162 massUpdatePools (); 163 } 164 uint256 prevAllocPoint = poolInfo [ _pid ]. allocPoint ; 165 poolInfo [ _pid ]. allocPoint = _allocPoint ; 166 poolInfo [ _pid ]. depositFeeBP = _depositFeeBP ; 167 poolInfo [ _pid ]. isSNovaRewards = _isSNovaRewards ; 168 if ( prevAllocPoint != _allocPoint ) { 169 totalAllocPoint = totalAllocPoint . sub ( prevAllocPoint ). add ( _allocPoint ); 170 } 171 } Listing 3.8: MasterShiba::set() If the call to massUpdatePools() is not immediately invoked before updating the pool weights, certain situations may be crafted to create an unfair reward distribution. Moreover, a hidden pool withoutanyweightcansuddenlysurfacetoclaimunreasonableshareofrewardedtokens. Fortunately, this interface is restricted to the owner (via the onlyOwner modifier), which greatly alleviates the concern. Recommendation Timely invoke massUpdatePools() when any pool’s weight has been updated. In fact, the third parameter ( _withUpdate ) to the set()routine can be simply ignored or removed. 19/26 PeckShield Audit Report #: 2021-195Public 158 // Update the given pool ’s Nova allocation point . Can only be called by the owner . 159 function set ( uint256 _pid , uint256 _allocPoint , uint256 _depositFeeBP , bool _isSNovaRewards , bool _withUpdate ) external onlyOwner { 160 require ( _depositFeeBP <= 400 , " set : invalid deposit fee basis points "); 161 massUpdatePools (); 162 uint256 prevAllocPoint = poolInfo [ _pid ]. allocPoint ; 163 poolInfo [ _pid ]. allocPoint = _allocPoint ; 164 poolInfo [ _pid ]. depositFeeBP = _depositFeeBP ; 165 poolInfo [ _pid ]. isSNovaRewards = _isSNovaRewards ; 166 if ( prevAllocPoint != _allocPoint ) { 167 totalAllocPoint = totalAllocPoint . sub ( prevAllocPoint ). add ( _allocPoint ); 168 } 169 } Listing 3.9: MasterShiba::set() Status This issue has been fixed in this commit: e7041e5. 3.6 Inconsistency Between Document and Implementation •ID: PVE-006 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: ShibaPair •Category: Coding Practices [8] •CWE subcategory: CWE-1041 [1] Description Thereisamisleadingcommentembeddedinthe ShibaPair contract, whichbringsunnecessaryhurdles to understand and/or maintain the software. The preceding function summary indicates that this function is supposed to mint liquidity "equiv- alent to 1/6th of the growth in sqrt(k)" However, the implementation logic (line 98 * 103) indicates the minted liquidity should be equal to 1/(IShibaFactory(factory).feeAmount()+1) of the growth in sqrt(k). 89 // if fee is on , mint liquidity equivalent to 1/6 th of the growth in sqrt (k) 90 function _mintFee ( uint112 _reserve0 , uint112 _reserve1 ) private returns ( bool feeOn ) { 91 address feeTo = IShibaFactory ( factory ). feeTo (); 92 feeOn = feeTo != address (0) ; 93 uint _kLast = kLast ; // gas savings 94 if ( feeOn ) { 95 if ( _kLast != 0) { 96 uint rootK = Math . sqrt ( uint ( _reserve0 ). mul ( _reserve1 )); 97 uint rootKLast = Math . sqrt ( _kLast ); 98 if ( rootK > rootKLast ) { 20/26 PeckShield Audit Report #: 2021-195Public 99 uint numerator = totalSupply . mul( rootK . sub ( rootKLast )); 100 uint denominator = rootK . mul( IShibaFactory ( factory ). feeAmount () ). add ( rootKLast ); 101 uint liquidity = numerator / denominator ; 102 if ( liquidity > 0) _mint (feeTo , liquidity ); 103 } 104 } 105 } else if ( _kLast != 0) { 106 kLast = 0; 107 } 108 } Listing 3.10: ShibaPair::_mintFee() Recommendation Ensuretheconsistencybetweendocuments(includingembeddedcomments) and implementation. Status This issue has been fixed in this commit: e7041e5. 3.7 Redundant Code Removal •ID: PVE-007 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: ShibaLibrary •Category: Coding Practices [8] •CWE subcategory: CWE-563 [5] Description ShibaNova makes good use of a number of reference contracts, such as ERC20,SafeERC20 ,SafeMath, and Ownable, to facilitate its code implementation and organization. For example, the MasterShiba 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 getReserves() function in the ShibaLibrary contract, this function makes a redundant call to pairFor(factory, tokenA, tokenB) (line 31). 28 // fetches and sorts the reserves for a pair 29 function getReserves ( address factory , address tokenA , address tokenB ) internal view returns ( uint reserveA , uint reserveB ) { 30 ( address token0 ,) = sortTokens ( tokenA , tokenB ); 31 pairFor ( factory , tokenA , tokenB ); 32 ( uint reserve0 , uint reserve1 ,) = IShibaPair ( pairFor ( factory , tokenA , tokenB )). getReserves (); 33 ( reserveA , reserveB ) = tokenA == token0 ? ( reserve0 , reserve1 ) : ( reserve1 , reserve0 ); 21/26 PeckShield Audit Report #: 2021-195Public 34 } Listing 3.11: ShibaLibrary::getReserves() Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status This issue has been fixed in this commit: e7041e5. 3.8 Reentrancy Risk in deposit()/withdraw()/harvestReward() •ID: PVE-008 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterShiba •Category: Coding Practices [8] •CWE subcategory: CWE-561 [4] 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 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 are several occasions the checks-effects-interactions principle is violated. Note the withdraw() 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 339) starts before effecting the update on internal states (line 342), 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 very same withdraw() function. 319 // Withdraw LP tokens from MasterShiba . 320 function withdraw ( uint256 _pid , uint256 _amount ) external validatePool ( _pid ) { 321 PoolInfo storage pool = poolInfo [ _pid ]; 322 UserInfo storage user = userInfo [ _pid ][ msg. sender ]; 323 require ( user . amount >= _amount , " withdraw : not good "); 324 325 updatePool ( _pid ); 22/26 PeckShield Audit Report #: 2021-195Public 326 uint256 pending = user . amountWithBonus . mul ( pool . accNovaPerShare ). div (1 e12 ). sub ( user . rewardDebt ); 327 if( pending > 0) { 328 if( pool . isSNovaRewards ){ 329 safeSNovaTransfer ( msg . sender , pending ); 330 } 331 else { 332 safeNovaTransfer ( msg . sender , pending ); 333 } 334 } 335 if( _amount > 0) { 336 user . amount = user . amount .sub ( _amount ); 337 uint256 _bonusAmount = _amount . mul ( userBonus (_pid , msg . sender ). add (10000) ). div (10000) ; 338 user . amountWithBonus = user . amountWithBonus . sub ( _bonusAmount ); 339 pool . lpToken . safeTransfer ( address ( msg. sender ), _amount ); 340 pool . lpSupply = pool . lpSupply .sub ( _bonusAmount ); 341 } 342 user . rewardDebt = user . amountWithBonus . mul ( pool . accNovaPerShare ). div (1 e12 ); 343 emit Withdraw (msg. sender , _pid , _amount ); 344 } Listing 3.12: MasterShiba::withdraw() Note that the same issue also found in the deposit() and the harvestReward() functions. Recommendation Add the nonReentrant modifier to prevent reentrancy. Status This issue has been fixed in this commit: e7041e5. 23/26 PeckShield Audit Report #: 2021-195Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the ShibaNova protocol. The system presents a decentralized exchange and automatic market maker built on the Binance Smart Chain (BSC). The current code base is well structured and neatly organized. Those identified issues are promptly confirmed and fixed. 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. 24/26 PeckShield Audit Report #: 2021-195Public 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-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [4] MITRE. CWE-561: Dead Code. https://cwe.mitre.org/data/definitions/561.html. [5] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [6] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [7] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.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. 25/26 PeckShield Audit Report #: 2021-195Public [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] Jong Seok Park. Sushiswap Delegation Double Spending Bug. https://medium.com/ bulldax-finance/sushiswap-delegation-double-spending-bug-5adcc7b3830f. [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. 26/26 PeckShield Audit Report #: 2021-195
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Trading Fee Discrepancy Between ShibaSwap And ShibaNova (Line 12) - Sybil Attacks on sNova Voting (Line 14) - Accommodation of Non-Compliant ERC20 Tokens (Line 16) - Trust Issue of Admin Keys (Line 17) 2.b Fix (one line with code reference) - Adjust the fee rate of ShibaSwap and ShibaNova (Line 12) - Implement a voting system with a KYC process (Line 14) - Implement a whitelist of compliant ERC20 tokens (Line 16) - Implement a multi-signature wallet for admin keys (Line 17) Moderate 3.a Problem (one line with code reference) - Timely massUpdatePools During Pool Weight Changes (Line 19) - Inconsistency Between Document and Implementation (Line 20) 3.b Fix (one line with code reference) - Implement a Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - The goal of the project is to solve one of the fundamental problems in decentralized finance (DeFi) - The project's native token rises in value at launch only to incrementally decrease in value day after day until it ultimately goes down to zero - The solution is effectively turning investors into valued shareholders - eligible to get their share of 75% of fees collected in the dApp - By providing liquidity to the project and creating/holding the related dividend tokens, the shareholders are able to earn daily passive income - This daily dividends system not only incentivizes long-term holding but promotes ownership of the project by the entire community - PeckShield Inc. is a leading blockchain security company with the goal of elevating the security, privacy, and usability of current blockchain ecosystems - The audit was conducted using a whitebox method - The audit was conducted using the OWASP Risk Rating Methodology Conclusion: The audit of the ShibaNova project was conducted using a whitebox method and the OWASP Risk Rating Methodology. No issues were found in 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 function transferFrom() (CWE-252) 2.b Fix (one line with code reference): Check return value of transferFrom() (CWE-252) Moderate Issues 3.a Problem (one line with code reference): Unchecked return value in function transfer() (CWE-252) 3.b Fix (one line with code reference): Check return value of transfer() (CWE-252) 3.c Problem (one line with code reference): Unchecked return value in function approve() (CWE-252) 3.d Fix (one line with code reference): Check return value of approve() (CWE-252) 3.e Problem (one line with code reference): Unchecked return value in function transferFrom() (CWE-252) 3.f Fix (one line with code reference): Check return value of transferFrom() (CWE-252) Major: 0 Critical: 0
//SPDX-License-Identifier: Unlicense pragma solidity 0.7.5; pragma abicoder v2; import './dependencies/SafeMath.sol'; import './interfaces/IBridgeExecutor.sol'; abstract contract BridgeExecutorBase is IBridgeExecutor { using SafeMath for uint256; uint256 public immutable override GRACE_PERIOD; uint256 public immutable override MINIMUM_DELAY; uint256 public immutable override MAXIMUM_DELAY; uint256 private _actionsSetCounter; address private _guardian; uint256 private _delay; mapping(uint256 => ActionsSet) private _actionsSets; mapping(bytes32 => bool) private _queuedActions; modifier onlyGuardian() { require(msg.sender == _guardian, 'ONLY_BY_GUARDIAN'); _; } constructor( uint256 delay, uint256 gracePeriod, uint256 minimumDelay, uint256 maximumDelay, address guardian ) { require(delay >= minimumDelay, 'DELAY_SHORTER_THAN_MINIMUM'); require(delay <= maximumDelay, 'DELAY_LONGER_THAN_MAXIMUM'); _delay = delay; GRACE_PERIOD = gracePeriod; MINIMUM_DELAY = minimumDelay; MAXIMUM_DELAY = maximumDelay; _guardian = guardian; emit NewDelay(delay); } /** * @dev Execute the ActionsSet * @param actionsSetId id of the ActionsSet to execute **/ function execute(uint256 actionsSetId) external payable override { require(getActionsSetState(actionsSetId) == ActionsSetState.Queued, 'ONLY_QUEUED_ACTIONS'); ActionsSet storage actionsSet = _actionsSets[actionsSetId]; require(block.timestamp >= actionsSet.executionTime, 'TIMELOCK_NOT_FINISHED'); actionsSet.executed = true; for (uint256 i = 0; i < actionsSet.targets.length; i++) { _executeTransaction( actionsSet.targets[i], actionsSet.values[i], actionsSet.signatures[i], actionsSet.calldatas[i], actionsSet.executionTime, actionsSet.withDelegatecalls[i] ); } emit ActionsSetExecuted(actionsSetId, msg.sender); } /** * @dev Cancel the ActionsSet * @param actionsSetId id of the ActionsSet to cancel **/ function cancel(uint256 actionsSetId) external override onlyGuardian { ActionsSetState state = getActionsSetState(actionsSetId); require(state == ActionsSetState.Queued, 'ONLY_BEFORE_EXECUTED'); ActionsSet storage actionsSet = _actionsSets[actionsSetId]; actionsSet.canceled = true; for (uint256 i = 0; i < actionsSet.targets.length; i++) { _cancelTransaction( actionsSet.targets[i], actionsSet.values[i], actionsSet.signatures[i], actionsSet.calldatas[i], actionsSet.executionTime, actionsSet.withDelegatecalls[i] ); } emit ActionsSetCanceled(actionsSetId); } /** * @dev Set the delay * @param delay delay between queue and execution of an ActionsSet **/ function setDelay(uint256 delay) public override onlyGuardian { _validateDelay(delay); _delay = delay; emit NewDelay(delay); } /** * @dev Get the ActionsSet by Id * @param actionsSetId id of the ActionsSet * @return the ActionsSet requested **/ function getActionsSetById(uint256 actionsSetId) external view override returns (ActionsSet memory) { return _actionsSets[actionsSetId]; } /** * @dev Get the current state of an ActionsSet * @param actionsSetId id of the ActionsSet * @return The current state if the ActionsSet **/ function getActionsSetState(uint256 actionsSetId) public view override returns (ActionsSetState) { require(_actionsSetCounter >= actionsSetId, 'INVALID_ACTION_ID'); ActionsSet storage actionsSet = _actionsSets[actionsSetId]; if (actionsSet.canceled) { return ActionsSetState.Canceled; } else if (actionsSet.executed) { return ActionsSetState.Executed; } else if (block.timestamp > actionsSet.executionTime.add(GRACE_PERIOD)) { return ActionsSetState.Expired; } else { return ActionsSetState.Queued; } } /** * @dev Returns whether an action (via actionHash) is queued * @param actionHash hash of the action to be checked * keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)) * @return true if underlying action of actionHash is queued **/ function isActionQueued(bytes32 actionHash) public view override returns (bool) { return _queuedActions[actionHash]; } /** * @dev Receive Funds if necessary for delegate calls **/ function receiveFunds() external payable {} /** * @dev Getter of the delay between queuing and execution * @return The delay in seconds **/ function getDelay() external view override returns (uint256) { return _delay; } /** * @dev Queue the ActionsSet - only callable by the BridgeMessageProvessor * @param targets list of contracts called by each action's associated transaction * @param values list of value in wei for each action's associated transaction * @param signatures list of function signatures (can be empty) to be used when created the callData * @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments * @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target **/ function _queue( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, bool[] memory withDelegatecalls ) internal { require(targets.length != 0, 'INVALID_EMPTY_TARGETS'); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length && targets.length == withDelegatecalls.length, 'INCONSISTENT_PARAMS_LENGTH' ); uint256 actionsSetId = _actionsSetCounter; uint256 executionTime = block.timestamp.add(_delay); _actionsSetCounter++; for (uint256 i = 0; i < targets.length; i++) { bytes32 actionHash = keccak256( abi.encode( targets[i], values[i], signatures[i], calldatas[i], executionTime, withDelegatecalls[i] ) ); require(!isActionQueued(actionHash), 'DUPLICATED_ACTION'); // SWC-Presence of unused variables: L203 _queuedActions[actionHash] = true; } ActionsSet storage actionsSet = _actionsSets[actionsSetId]; actionsSet.id = actionsSetId; actionsSet.targets = targets; actionsSet.values = values; actionsSet.signatures = signatures; actionsSet.calldatas = calldatas; actionsSet.withDelegatecalls = withDelegatecalls; actionsSet.executionTime = executionTime; emit ActionsSetQueued( actionsSetId, targets, values, signatures, calldatas, withDelegatecalls, executionTime ); } function _executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) internal { bytes32 actionHash = keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)); // SWC-Presence of unused variables: L237 _queuedActions[actionHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } bool success; bytes memory resultData; if (withDelegatecall) { require(msg.value >= value, 'NOT_ENOUGH_MSG_VALUE'); // solium-disable-next-line security/no-call-value (success, resultData) = target.delegatecall(callData); } else { // solium-disable-next-line security/no-call-value (success, resultData) = target.call{value: value}(callData); } require(success, 'FAILED_ACTION_EXECUTION'); } function _cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 executionTime, bool withDelegatecall ) internal { bytes32 actionHash = keccak256(abi.encode(target, value, signature, data, executionTime, withDelegatecall)); // SWC-Presence of unused variables: 270 _queuedActions[actionHash] = false; } function _validateDelay(uint256 delay) internal view { require(delay >= MINIMUM_DELAY, 'DELAY_SHORTER_THAN_MINIMUM'); require(delay <= MAXIMUM_DELAY, 'DELAY_LONGER_THAN_MAXIMUM'); } } //SPDX-License-Identifier: Unlicense pragma solidity 0.7.5; pragma abicoder v2; import './interfaces/IFxMessageProcessor.sol'; import './BridgeExecutorBase.sol'; contract PolygonBridgeExecutor is BridgeExecutorBase, IFxMessageProcessor { address private immutable _fxRootSender; address private immutable _fxChild; constructor( address fxRootSender, address fxChild, uint256 delay, uint256 gracePeriod, uint256 minimumDelay, uint256 maximumDelay, address guardian ) BridgeExecutorBase(delay, gracePeriod, minimumDelay, maximumDelay, guardian) { _fxRootSender = fxRootSender; _fxChild = fxChild; } /** * @dev Process the cross-chain message from an FxChild contract through the ETH/Polygon StateSender * @param stateId Id of the cross-chain message created in the ETH/Polygon StateSender * @param rootMessageSender address that initally sent this message on ethereum * @param data the data from the abi-encoded cross-chain message **/ function processMessageFromRoot( uint256 stateId, address rootMessageSender, bytes calldata data ) external override { require(msg.sender == _fxChild, 'UNAUTHORIZED_CHILD_ORIGIN'); require(rootMessageSender == _fxRootSender, 'UNAUTHORIZED_ROOT_ORIGIN'); address[] memory targets; uint256[] memory values; string[] memory signatures; bytes[] memory calldatas; bool[] memory withDelegatecalls; (targets, values, signatures, calldatas, withDelegatecalls) = abi.decode( data, (address[], uint256[], string[], bytes[], bool[]) ); _queue(targets, values, signatures, calldatas, withDelegatecalls); } } //SPDX-License-Identifier: Unlicense pragma solidity 0.7.5; pragma abicoder v2; import './BridgeExecutorBase.sol'; contract ArbitrumBridgeExecutor is BridgeExecutorBase { address private immutable _ethereumGovernanceExecutor; constructor( address ethereumGovernanceExecutor, uint256 delay, uint256 gracePeriod, uint256 minimumDelay, uint256 maximumDelay, address guardian ) BridgeExecutorBase(delay, gracePeriod, minimumDelay, maximumDelay, guardian) { _ethereumGovernanceExecutor = ethereumGovernanceExecutor; } /** * @dev Queue the cross-chain message in the BridgeExecutor * @param targets list of contracts called by each action's associated transaction * @param values list of value in wei for each action's associated transaction * @param signatures list of function signatures (can be empty) to be used when created the callData * @param calldatas list of calldatas: if associated signature empty, calldata ready, else calldata is arguments * @param withDelegatecalls boolean, true = transaction delegatecalls the taget, else calls the target **/ function queue( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, bool[] memory withDelegatecalls ) external { require(msg.sender == _ethereumGovernanceExecutor, 'UNAUTHORIZED_EXECUTOR'); _queue(targets, values, signatures, calldatas, withDelegatecalls); } }
AAVE GOVERNANCE CROSSCHAIN BRIDGES SMART CONTRACT AUDIT June 17, 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 2.3.WARNING...................................................................6 WRN-1 No validation of the address parameter value in contract constructor..6 WRN-2 Missing validation on relation........................................8 WRN-3 The value is assigned to a variable, but not used.....................9 2.4.COMMENTS.................................................................10 CMT-1 Caching the value will improve the code..............................10 CMT-2 Confusing variable name..............................................11 3.ABOUT MIXBYTES................................................................12 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 Aave. 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 This scope of contracts contains the crosschain governance bridges used for the aave markets deployed across different networks. 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 smart contracts, examined in this audit, are designed to operate on the Polygon and Arbitrum blockchains. The functionality is designed to work with tasks for calling functions in other contracts. You can queue, execute, or cancel tasks. All tasks are saved in a smart contract. 1.5PROJECT DASHBOARD Client Aave Audit name Governance Crosschain Bridges Initial version 7f56e7ae63f30ba8dcd7ced6a11a34c2eb865a1d 763ef5da8befff3a129443a3ff4ef7ca4d3bb446 Final version 763ef5da8befff3a129443a3ff4ef7ca4d3bb446 SLOC 260 Date 2021-06-02 - 2021-06-17 Auditors engaged 2 auditors FILES LISTING BridgeExecutorBase.sol BridgeExecutorBase.sol ArbitrumBridgeExecutor.sol ArbitrumBridgeExecuto... PolygonBridgeExecutor.sol PolygonBridgeExecutor.sol IBridgeExecutor.sol IBridgeExecutor.sol IFxMessageProcessor.sol IFxMessageProcessor.sol 4FINDINGS SUMMARY Level Amount Critical 0 Major 0 Warning 3 Comment 2 CONCLUSION Smart contracts have been audited and several suspicious places have been spotted. During the audit no critical or major issues were found, several warnings and comments were spotted. After working on the reported findings all of them were either fixed by the client or acknowledged (if the problem was not critical). So, the contracts are assumed as secure to use according to our security criteria.Final commit identifier with all fixes: 763ef5da8befff3a129443a3ff4ef7ca4d3bb446 52.FINDINGS REPORT 2.1CRITICAL Not Found 2.2MAJOR Not Found 2.3WARNING WRN-1 No validation of the address parameter value in contract constructor File BridgeExecutorBase.sol PolygonBridgeExecutor.sol ArbitrumBridgeExecutor.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 the line BridgeExecutorBase.sol#L41 the _guardian variable is set to the value of the guardian input parameter. At the line PolygonBridgeExecutor.sol#L21 the _fxRootSender variable is set to the value of the fxRootSender input parameter. At the line PolygonBridgeExecutor.sol#L22 the _fxChild variable is set to the value of the fxChild input parameter. At the line ArbitrumBridgeExecutor.sol#L18 the _ethereumGovernanceExecutor variable is set to the value of the ethereumGovernanceExecutor input parameter. RECOMMENDATION It is necessary to add a check of the input parameter to zero before initializing the variables. 6CLIENT'S COMMENTARY I think not validating against the 0 address is an acceptable risk. Worst case, you re-deploy. You can't check for all incorrect addresses. 7WRN-2 Missing validation on relation File BridgeExecutorBase.sol SeverityWarning Status Acknowledged DESCRIPTION At the lines BridgeExecutorBase.sol#L34-L39 are working with the variables minimumDelay and maximumDelay . But nowhere is there a comparison of these variables with each other. RECOMMENDATION It is recommended to add a check for comparing the values of variables between each other. CLIENT'S COMMENTARY While we do not directly compare the min and max delay values, we do compare the delay to both the min and the max. If the min and max did not have an appropriate relationship, there would be no delay value that would satisfy both of these lines 34 and 35 in the BaseBridgeExecutor. 8WRN-3 The value is assigned to a variable, but not used File BridgeExecutorBase.sol SeverityWarning Status Acknowledged DESCRIPTION At the line BridgeExecutorBase.sol#L202 sets the variable _queuedActions[actionHash] to true when tasks are queued. At the line BridgeExecutorBase.sol#L269 sets the variable _queuedActions[actionHash] to false to cancel the job. But when executed on line BridgeExecutorBase.sol#L235, no validation is made for the _queuedActions[actionHash] variable. RECOMMENDATION It is recommended to add a check for the value of the _queuedActions[actionHash] variable before executing delegatecall and call . CLIENT'S COMMENTARY We perform the action hash in-order to check that the action is not duplicated prior to queuing the action. This occurs in the isActionQueued check of _queue. On execution, if the entire ActionsSet is queued per the check in line 51, then all of it's actions are inherently queued in _queuedActions. therefore checking the _queuedActions mapping for each action prior to executing would never return false. 92.4COMMENTS CMT-1 Caching the value will improve the code File BridgeExecutorBase.sol SeverityComment Status Acknowledged DESCRIPTION At the lines BridgeExecutorBase.sol#L176-L183 the calculation of the same value is used many times. But the value of targets.length is easier to calculate only once at the very beginning and store it in a variable. Then work with this variable. RECOMMENDATION It is recommended to optimize the code to use the cached value of the variable. CLIENT'S COMMENTARY Agree, this would be marginally more optimal, but we are ok with how it is currently implemented. This also mirrors the implementation in Aave-Governance-v2 that is already deployed 1 0CMT-2 Confusing variable name File BridgeExecutorBase.sol SeverityComment Status Fixed at 763ef5da DESCRIPTION At the line BridgeExecutorBase.sol#L124, the function is called getActionsSetState() . But it is very difficult to understand when in one word there are two different concepts of get and set at once. For example, the name getCurrentState() will be much clearer. RECOMMENDATION It is recommended to rename this variable. 1 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 1 2
Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 2 Critical: 1 Major: 4.a Problem (one line with code reference): WRN-1 No validation of the address parameter value in contract constructor. 4.b Fix (one line with code reference): Validate the address parameter value in the contract constructor. 4.a Problem (one line with code reference): WRN-2 Missing validation on relation. 4.b Fix (one line with code reference): Validate the relation before using it. Critical: 5.a Problem (one line with code reference): WRN-3 The value is assigned to a variable, but not used. 5.b Fix (one line with code reference): Use the assigned value in the code. Observations: The audit report found two major issues and one critical issue. Conclusion: The audit report concluded that the code needs to be improved to address the identified issues. 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 found no major or critical issues in the code. The minor issues found were addressed and fixed. 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 smart contracts examined in this audit are secure and do not contain any critical or major issues.
pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/token/ERC20/CappedToken.sol'; import 'zeppelin-solidity/contracts/token/ERC20/PausableToken.sol'; /** * CappedToken token is Mintable token with a max cap on totalSupply that can ever be minted. * PausableToken overrides all transfers methods and adds a modifier to check if paused is set to false. */ contract MeshToken is CappedToken, PausableToken { string public name = "RIGHTMESH TOKEN"; string public symbol = "RMESH"; uint256 public decimals = 18; uint256 public cap = 1000000 ether; /** * @dev variable to keep track of what addresses are allowed to call transfer functions when token is paused. */ mapping (address => bool) public allowedTransfers; /*------------------------------------constructor------------------------------------*/ /** * @dev constructor for mesh token */ function MeshToken() CappedToken(cap) public { paused = true; } /*------------------------------------overridden methods------------------------------------*/ /** * @dev Overridder modifier to allow exceptions for pausing for a given address * This modifier is added to all transfer methods by PausableToken and only allows if paused is set to false. * With this override the function allows either if paused is set to false or msg.sender is allowedTransfers during the pause as well. */ modifier whenNotPaused() { require(!paused || allowedTransfers[msg.sender]); _; } /** * @dev overriding Pausable#pause method to do nothing * Paused is set to true in the constructor itself, making the token non-transferrable on deploy. * once unpaused the contract cannot be paused again. * adding this to limit owner's ability to pause the token in future. */ function pause() onlyOwner whenNotPaused public {} /*------------------------------------new methods------------------------------------*/ /** * @dev method to updated allowedTransfers for an address * @param _address that needs to be updated * @param _allowedTransfers indicating if transfers are allowed or not * @return boolean indicating function success. */ function updateAllowedTransfers(address _address, bool _allowedTransfers) external onlyOwner returns (bool) { // don't allow owner to change this for themselves // otherwise whenNotPaused will not work as expected for owner, // therefore prohibiting them from calling pause/unpause. require(_address != owner); allowedTransfers[_address] = _allowedTransfers; return true; } } 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) external restricted { last_completed_migration = completed; } function upgrade(address new_address) external restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity ^0.4.18; import './MeshToken.sol'; import 'zeppelin-solidity/contracts/crowdsale/CappedCrowdsale.sol'; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; /** * CappedCrowdsale limits the total number of wei that can be collected in the sale. */ contract MeshCrowdsale is CappedCrowdsale, Ownable { using SafeMath for uint256; /** * @dev weiLimits keeps track of amount of wei that can be contibuted by an address. */ mapping (address => uint256) public weiLimits; /** * @dev weiContributions keeps track of amount of wei that are contibuted by an address. */ mapping (address => uint256) public weiContributions; /** * @dev whitelistingAgents keeps track of who is allowed to call the setLimit method */ mapping (address => bool) public whitelistingAgents; /** * @dev minimumContribution keeps track of what should be the minimum contribution required per address */ uint256 public minimumContribution; /** * @dev variable to keep track of beneficiaries for which we need to mint the tokens directly */ address[] public beneficiaries; /** * @dev variable to keep track of amount og tokens to mint for beneficiaries */ uint256[] public beneficiaryAmounts; /*---------------------------------constructor---------------------------------*/ /** * @dev Constructor for MeshCrowdsale contract */ function MeshCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumContribution, MeshToken _token, address[] _beneficiaries, uint256[] _beneficiaryAmounts) CappedCrowdsale(_cap) Crowdsale(_startTime, _endTime, _rate, _wallet, _token) public { require(_beneficiaries.length == _beneficiaryAmounts.length); beneficiaries = _beneficiaries; beneficiaryAmounts = _beneficiaryAmounts; minimumContribution = _minimumContribution; } /*---------------------------------overridden methods---------------------------------*/ /** * overriding Crowdsale#buyTokens to keep track of wei contributed per address */ function buyTokens(address beneficiary) public payable { weiContributions[msg.sender] = weiContributions[msg.sender].add(msg.value); super.buyTokens(beneficiary); } /** * overriding CappedCrowdsale#validPurchase to add extra contribution limit logic * @return true if investors can buy at the moment */ function validPurchase() internal view returns (bool) { bool withinLimit = weiContributions[msg.sender] <= weiLimits[msg.sender]; bool atleastMinimumContribution = weiContributions[msg.sender] >= minimumContribution; return atleastMinimumContribution && withinLimit && super.validPurchase(); } /*---------------------------------new methods---------------------------------*/ /** * @dev Allows owner to add / remove whitelistingAgents * @param _address that is being allowed or removed from whitelisting addresses * @param _value boolean indicating if address is whitelisting agent or not * @return boolean indicating function success. */ function setWhitelistingAgent(address _address, bool _value) external onlyOwner returns (bool) { whitelistingAgents[_address] = _value; return true; } /** * @dev Allows the current owner to update contribution limits * @param _addresses whose contribution limits should be changed * @param _weiLimit new contribution limit * @return boolean indicating function success. */ function setLimit(address[] _addresses, uint256 _weiLimit) external returns (bool) { require(whitelistingAgents[msg.sender] == true); for (uint i = 0; i < _addresses.length; i++) { address _address = _addresses[i]; // only allow changing the limit to be greater than current contribution if(_weiLimit >= weiContributions[_address]) { weiLimits[_address] = _weiLimit; } } return true; } /** * @dev Allows the current owner to change the ETH to token generation rate. * @param _rate indicating the new token generation rate. * @return boolean indicating function success. */ function setRate(uint256 _rate) external onlyOwner returns (bool) { // make sure the crowdsale has not started require(weiRaised == 0); // make sure new rate is greater than 0 require(_rate > 0); rate = _rate; return true; } /** * @dev Allows the current owner to change the crowdsale cap. * @param _cap indicating the new crowdsale cap. * @return boolean indicating function success. */ function setCap(uint256 _cap) external onlyOwner returns (bool) { // make sure the crowdsale has not started require(weiRaised == 0); // make sure new cap is greater than 0 require(_cap > 0); cap = _cap; return true; } /** * @dev Allows the current owner to change the required minimum contribution. * @param _minimumContribution indicating the minimum required contribution. * @return boolean indicating function success. */ function setMinimumContribution(uint256 _minimumContribution) external onlyOwner returns (bool) { minimumContribution = _minimumContribution; return true; } /* * @dev Function to perform minting to predefined beneficiaries once crowdsale has started * can be called by anyone as the outcome is fixed and does not depend on who is calling the method * can be called multiple times but will only do the minting once per address */ function mintPredefinedTokens() external onlyOwner returns (bool) { // make sure the crowdsale has started require(weiRaised > 0); // loop through the list and call mint on token directly // this minting does not affect any crowdsale numbers for (uint i = 0; i < beneficiaries.length; i++) { if (beneficiaries[i] != address(0) && token.balanceOf(beneficiaries[i]) == 0) { token.mint(beneficiaries[i], beneficiaryAmounts[i]); } } } /*---------------------------------proxy methods for token when owned by contract---------------------------------*/ /** * @dev Allows the current owner to transfer token control back to contract owner */ function transferTokenOwnership() external onlyOwner { token.transferOwnership(owner); } } pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; import "zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol"; /** * @title TokenTimelock * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme with a cliff, gradual release period, and implied residue. * * Withdraws by an address can be paused by the owner. */ contract Timelock is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; /* * @dev ERC20 token that is being timelocked */ ERC20Basic public token; /** * @dev timestamp at which the timelock schedule begins */ uint256 public startTime; /** * @dev number of seconds from startTime to cliff */ uint256 public cliffDuration; /** * @dev a percentage that becomes available at the cliff, expressed as a number between 0 and 100 */ uint256 public cliffReleasePercentage; /** * @dev number of seconds from cliff to residue, over this period tokens become avialable gradually */ uint256 public slopeDuration; /** * @dev a percentage that becomes avilable over the gradual release period expressed as a number between 0 and 100 */ uint256 public slopeReleasePercentage; /** * @dev boolean indicating if owner has finished allocation. */ bool public allocationFinished; /** * @dev variable to keep track of cliff time. */ uint256 public cliffTime; /** * @dev variable to keep track of when the timelock ends. */ uint256 public timelockEndTime; /** * @dev mapping to keep track of what amount of tokens have been allocated to what address. */ mapping (address => uint256) public allocatedTokens; /** * @dev mapping to keep track of what amount of tokens have been withdrawn by what address. */ mapping (address => uint256) public withdrawnTokens; /** * @dev mapping to keep track of if withdrawls are paused for a given address. */ mapping (address => bool) public withdrawalPaused; /** * @dev constructor * @param _token address of ERC20 token that is being timelocked. * @param _startTime timestamp indicating when the unlocking of tokens start. * @param _cliffDuration number of seconds before any tokens are unlocked. * @param _cliffReleasePercent percentage of tokens that become available at the cliff time. * @param _slopeDuration number of seconds for gradual release of Tokens. * @param _slopeReleasePercentage percentage of tokens that are released gradually. */ function Timelock(ERC20Basic _token, uint256 _startTime, uint256 _cliffDuration, uint256 _cliffReleasePercent, uint256 _slopeDuration, uint256 _slopeReleasePercentage) public { // sanity checks require(_cliffReleasePercent.add(_slopeReleasePercentage) <= 100); require(_startTime > now); require(_token != address(0)); // defaults allocationFinished = false; // storing constructor params token = _token; startTime = _startTime; cliffDuration = _cliffDuration; cliffReleasePercentage = _cliffReleasePercent; slopeDuration = _slopeDuration; slopeReleasePercentage = _slopeReleasePercentage; // derived variables cliffTime = startTime.add(cliffDuration); timelockEndTime = cliffTime.add(slopeDuration); } /** * @dev helper method that allows owner to allocate tokens to an address. * @param _address beneficiary receiving the tokens. * @param _amount number of tokens being received by beneficiary. * @return boolean indicating function success. */ function allocateTokens(address _address, uint256 _amount) onlyOwner public returns (bool) { require(!allocationFinished); allocatedTokens[_address] = _amount; return true; } /** * @dev helper method that allows owner to mark allocation as done. * @return boolean indicating function success. */ function finishAllocation() onlyOwner public returns (bool) { allocationFinished = true; return true; } /** * @dev helper method that allows owner to pause withdrawls for any address. * @return boolean indicating function success. */ function pauseWithdrawal(address _address) onlyOwner public returns (bool) { withdrawalPaused[_address] = true; return true; } /** * @dev helper method that allows owner to unpause withdrawls for any address. * @return boolean indicating function success. */ function unpauseWithdrawal(address _address) onlyOwner public returns (bool) { withdrawalPaused[_address] = false; return true; } /** * @dev helper method that allows anyone to check amount that is available for withdrawl by a given address. * @param _address for which the user needs to check available amount for withdrawl. * @return uint256 number indicating the number of tokens available for withdrawl. */ function availableForWithdrawal(address _address) public view returns (uint256) { if (now < cliffTime) { return 0; } else if (now < timelockEndTime) { uint256 cliffTokens = (cliffReleasePercentage.mul(allocatedTokens[_address])).div(100); uint256 slopeTokens = (allocatedTokens[_address].mul(slopeReleasePercentage)).div(100); uint256 timeAtSlope = now.sub(cliffTime); uint256 slopeTokensByNow = (slopeTokens.mul(timeAtSlope)).div(slopeDuration); return (cliffTokens.add(slopeTokensByNow)).sub(withdrawnTokens[_address]); } else { return allocatedTokens[_address].sub(withdrawnTokens[_address]); } } /** * @dev helper method that allows a beneficiary to withdraw tokens that have vested for their address. * @return boolean indicating function success. */ function withdraw() public returns (bool) { require(!withdrawalPaused[msg.sender]); uint256 availableTokens = availableForWithdrawal(msg.sender); if (availableTokens > 0) { withdrawnTokens[msg.sender] = withdrawnTokens[msg.sender].add(availableTokens); token.safeTransfer(msg.sender, availableTokens); } return true; } }
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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
/* 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
/* 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
/* 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
/* 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
/* 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
/* 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
// 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
// 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: 3 - Moderate: 0 - Major: 0 - Critical: 1 Minor Issues: - Problem: Lack of two-phase ownership transfer. - Fix: No changes were made to ownership transfers. - Problem: Lack of mitigations for the short-address attack. - Fix: No changes were made to mitigate short-address attacks. - Problem: Token allocation configuration that is less than ideally transparent. - Fix: No changes were made to the configuration of predefined token allocations. Critical: - Problem: Flaw in the mechanism for minting “predefined tokens” which allowed the crowd sale owner to issue large quantities of tokens to addresses that it controls. - Fix: RightMesh made changes to their contracts to prevent predefined tokens from being minted multiple times. Observations: - The code is well commented. - The RightMesh white papers and other documentation provide very little detail about the operation of the crowd sale or token. Conclusion: The audit identified one critical finding and three additional minor flaws. RightMesh made changes to their contracts to prevent pred Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: Problem: None Fix: None Moderate Issues: Problem: None Fix: None Major Issues: Problem: None Fix: None Critical Issues: Problem: Predefined tokens can be minted multiple times Fix: Add a check to ensure mintPredefinedTokens has not been called previously, and update the comments to reflect the onlyOwner tag. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: Problem: Lack of two-phase ownership transfer Fix: Not Fixed Observations: 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. Conclusion: RightMesh opted to preserve the current ownership transfer mechanism and 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.
pragma solidity >=0.6.6; import {ChainlinkClient} from "@chainlink/contracts/src/v0.6/ChainlinkClient.sol"; import {LinkTokenInterface} from "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; import { Chainlink } from "@chainlink/contracts/src/v0.6/Chainlink.sol"; import {ILimaOracleReceiver} from "./interfaces/ILimaOracleReceiver.sol"; /** * @title LimaOracle is an contract which is responsible for requesting data from * the Chainlink network */ contract LimaOracle is ChainlinkClient { address public oracle; bytes32 public jobId; uint256 private fee; string private uri; mapping(bytes32 => ILimaOracleReceiver) public pendingRequests; /** * @notice Deploy the contract with a specified address for the LINK * and Oracle contract addresses */ constructor(address _oracle, address link, bytes32 _jobId, string memory _uri) public { oracle = _oracle; fee = LINK / 10; // 0.1 LINK jobId = _jobId; uri = _uri; setChainlinkToken(link); } function requestDeliveryStatus(address _receiver) public returns (bytes32 requestId) { Chainlink.Request memory req = buildChainlinkRequest( jobId, address(this), this.fulfill.selector ); //Set the URL to perform the GET request on req.add( "get", uri ); //Set the path to find the desired data in the API response, where the response format is: req.add("path", "address"); requestId = sendChainlinkRequestTo(oracle, req, fee); //Save callback function & receiver pendingRequests[requestId] = ILimaOracleReceiver(_receiver); return requestId; } /** * @notice The fulfill method from requests created by this contract * @dev The recordChainlinkFulfillment protects this function from being called * by anyone other than the oracle address that the request was sent to * @param _requestId The ID that was generated for the request * @param _data The answer provided by the oracle */ function fulfill(bytes32 _requestId, bytes32 _data) public recordChainlinkFulfillment(_requestId) { ILimaOracleReceiver receiver = pendingRequests[_requestId]; receiver.receiveOracleData(_requestId, _data); delete pendingRequests[_requestId]; } } pragma solidity ^0.6.2; import { ERC20PausableUpgradeSafe, IERC20, SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import { SafeERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import { OwnableUpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import {AddressArrayUtils} from "./library/AddressArrayUtils.sol"; import {OwnableLimaManager} from "./limaTokenModules/OwnableLimaManager.sol"; import {ILimaSwap} from "./interfaces/ILimaSwap.sol"; import {IAmunUser} from "./interfaces/IAmunUser.sol"; import {ILimaOracle} from "./interfaces/ILimaOracle.sol"; /** * @title LimaToken * @author Lima Protocol * * Standard LimaToken. */ contract LimaTokenStorage is OwnableUpgradeSafe, OwnableLimaManager { using AddressArrayUtils for address[]; using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_UINT256 = 2**256 - 1; address public constant USDC = address( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 ); address public LINK; // = address(0x514910771AF9Ca656af840dff83E8264EcF986CA); // List of UnderlyingTokens address[] public underlyingTokens; address public currentUnderlyingToken; // address public owner; ILimaSwap public limaSwap; address public limaToken; //Fees address public feeWallet; uint256 public burnFee; // 1 / burnFee * burned amount == fee uint256 public mintFee; // 1 / mintFee * minted amount == fee uint256 public performanceFee; //Rebalance uint256 public lastUnderlyingBalancePer1000; uint256 public lastRebalance; uint256 public rebalanceInterval; ILimaOracle public oracle; bytes32 public oracleData; bytes32 public requestId; bool public isOracleDataReturned; bool public isRebalancing; uint256 public rebalanceBonus; uint256 public payoutGas; uint256 public minimumReturnLink; uint256 newToken; uint256 minimumReturn; uint256 minimumReturnGov; uint256 amountToSellForLink; /** * @dev Initializes contract */ function __LimaTokenStorage_init_unchained( address _limaSwap, address _feeWallet, address _currentUnderlyingToken, address[] memory _underlyingTokens, uint256 _mintFee, uint256 _burnFee, uint256 _performanceFee, address _LINK, address _oracle ) public initializer { require( _underlyingTokens.contains(_currentUnderlyingToken), "_currentUnderlyingToken must be part of _underlyingTokens." ); __Ownable_init(); limaSwap = ILimaSwap(_limaSwap); __OwnableLimaManager_init_unchained(); underlyingTokens = _underlyingTokens; currentUnderlyingToken = _currentUnderlyingToken; burnFee = _burnFee; //1/100 = 1% mintFee = _mintFee; performanceFee = _performanceFee; //1/10 = 10% rebalanceInterval = 24 hours; lastRebalance = now; lastUnderlyingBalancePer1000 = 0; feeWallet = _feeWallet; rebalanceBonus = 0; payoutGas = 21000; //for minting to user LINK = _LINK; oracle = ILimaOracle(_oracle); minimumReturnLink = 10; } /** * @dev Throws if called by any account other than the limaManager. */ modifier onlyLimaManagerOrOwner() { _isLimaManagerOrOwner(); _; } function _isLimaManagerOrOwner() internal view { require( limaManager() == _msgSender() || owner() == _msgSender() || limaToken == _msgSender(), "LS2" //"Ownable: caller is not the limaManager or owner" ); } modifier onlyUnderlyingToken(address _token) { // Internal function used to reduce bytecode size _isUnderlyingToken(_token); _; } function _isUnderlyingToken(address _token) internal view { require( isUnderlyingTokens(_token), "LS3" //"Only token that are part of Underlying Tokens" ); } modifier noEmptyAddress(address _address) { // Internal function used to reduce bytecode size require(_address != address(0), "LS4"); //Only address that is not empty"); _; } /* ============ Setter ============ */ function addUnderlyingToken(address _underlyingToken) external onlyLimaManagerOrOwner { require( !isUnderlyingTokens(_underlyingToken), "LS1" //"Can not add already existing underlying token again." ); underlyingTokens.push(_underlyingToken); } function removeUnderlyingToken(address _underlyingToken) external onlyLimaManagerOrOwner { underlyingTokens = underlyingTokens.remove(_underlyingToken); } function setCurrentUnderlyingToken(address _currentUnderlyingToken) external onlyUnderlyingToken(_currentUnderlyingToken) onlyLimaManagerOrOwner { currentUnderlyingToken = _currentUnderlyingToken; } function setLimaToken(address _limaToken) external noEmptyAddress(_limaToken) onlyLimaManagerOrOwner { limaToken = _limaToken; } function setLimaSwap(address _limaSwap) public noEmptyAddress(_limaSwap) onlyLimaManagerOrOwner { limaSwap = ILimaSwap(_limaSwap); } function setFeeWallet(address _feeWallet) external noEmptyAddress(_feeWallet) onlyLimaManagerOrOwner { feeWallet = _feeWallet; } function setPerformanceFee(uint256 _performanceFee) external onlyLimaManagerOrOwner { performanceFee = _performanceFee; } function setBurnFee(uint256 _burnFee) external onlyLimaManagerOrOwner { burnFee = _burnFee; } function setMintFee(uint256 _mintFee) external onlyLimaManagerOrOwner { mintFee = _mintFee; } function setRequestId(bytes32 _requestId) external onlyLimaManagerOrOwner { requestId = _requestId; } function setLimaOracle(address _oracle) external onlyLimaManagerOrOwner { oracle = ILimaOracle(_oracle); } function setLastUnderlyingBalancePer1000( uint256 _lastUnderlyingBalancePer1000 ) external onlyLimaManagerOrOwner { lastUnderlyingBalancePer1000 = _lastUnderlyingBalancePer1000; } function setLastRebalance(uint256 _lastRebalance) external onlyLimaManagerOrOwner { lastRebalance = _lastRebalance; } function setRebalanceInterval(uint256 _rebalanceInterval) external onlyLimaManagerOrOwner { rebalanceInterval = _rebalanceInterval; } function setRebalanceBonus(uint256 _rebalanceBonus) external onlyLimaManagerOrOwner { rebalanceBonus = _rebalanceBonus; } function setPayoutGas(uint256 _payoutGas) external onlyLimaManagerOrOwner { payoutGas = _payoutGas; } function setOracleData(bytes32 _data) external onlyLimaManagerOrOwner { oracleData = _data; } function setIsRebalancing(bool _isRebalancing) external onlyLimaManagerOrOwner { isRebalancing = _isRebalancing; } function setIsOracleDataReturned(bool _isOracleDataReturned) public onlyLimaManagerOrOwner { isOracleDataReturned = _isOracleDataReturned; } function setLink(address _LINK) public onlyLimaManagerOrOwner { LINK = _LINK; } function shouldRebalance( uint256 _newToken, uint256 _minimumReturnGov, uint256 _amountToSellForLink ) external view returns (bool) { return !(underlyingTokens[_newToken] == currentUnderlyingToken && _minimumReturnGov == 0 && _amountToSellForLink == 0); } /* ============ View ============ */ function isUnderlyingTokens(address _underlyingToken) public view returns (bool) { return underlyingTokens.contains(_underlyingToken); } } pragma solidity ^0.6.2; import { ERC20PausableUpgradeSafe, IERC20, SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import { SafeERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import {AddressArrayUtils} from "./library/AddressArrayUtils.sol"; import {ILimaSwap} from "./interfaces/ILimaSwap.sol"; import {ILimaToken} from "./interfaces/ILimaToken.sol"; import {LimaTokenStorage} from "./LimaTokenStorage.sol"; import {AmunUsers} from "./limaTokenModules/AmunUsers.sol"; import {InvestmentToken} from "./limaTokenModules/InvestmentToken.sol"; /** * @title LimaToken * @author Lima Protocol * * Standard LimaToken. */ contract LimaTokenHelper is LimaTokenStorage, InvestmentToken, AmunUsers { using AddressArrayUtils for address[]; using SafeMath for uint256; using SafeERC20 for IERC20; function initialize( address _limaSwap, address _feeWallet, address _currentUnderlyingToken, address[] memory _underlyingTokens, uint256 _mintFee, uint256 _burnFee, uint256 _performanceFee, address _link, address _oracle ) public initializer { __LimaTokenStorage_init_unchained( _limaSwap, _feeWallet, _currentUnderlyingToken, _underlyingTokens, _mintFee, _burnFee, _performanceFee, _link, _oracle ); __AmunUsers_init_unchained(true); } /* ============ View ============ */ /** * @dev Get total net token value. */ function getNetTokenValue(address _targetToken) public view returns (uint256 netTokenValue) { return getExpectedReturn( currentUnderlyingToken, _targetToken, getUnderlyingTokenBalance() ); } /** * @dev Get total net token value. */ function getNetTokenValueOf(address _targetToken, uint256 _amount) public view returns (uint256 netTokenValue) { return getExpectedReturn( currentUnderlyingToken, _targetToken, getUnderlyingTokenBalanceOf(_amount) ); } //helper for redirect to LimaSwap function getExpectedReturn( address _from, address _to, uint256 _amount ) public view returns (uint256 returnAmount) { returnAmount = limaSwap.getExpectedReturn(_from, _to, _amount); } function getUnderlyingTokenBalance() public view returns (uint256 balance) { return IERC20(currentUnderlyingToken).balanceOf(limaToken); } function getUnderlyingTokenBalanceOf(uint256 _amount) public view returns (uint256 balanceOf) { uint256 balance = getUnderlyingTokenBalance(); require(balance != 0, "LM4"); //"Balance of underlyng token cant be zero." return balance.mul(_amount).div(ILimaToken(limaToken).totalSupply()); } /* ============ Helper Main Functions ============ */ function _getPayback(uint256 gas) internal view returns (uint256) { //send gas cost uint256 gasPayback = (gas + payoutGas).mul(tx.gasprice) + rebalanceBonus; return gasPayback; //todo // 0x922018674c12a7F0D394ebEEf9B58F186CdE13c1.price('ETH'); // uint256 returnAmount = limaSwap.getExpectedReturn( // USDC, // currentUnderlyingToken, // gasPayback // ); // return // gasPayback.mul(ILimaToken(limaToken).totalSupply()).div( // ILimaToken(limaToken).getUnderlyingTokenBalance() // ); } /** * @dev Return the amount to mint in LimaToken as payback for user function call */ function getPayback(uint256 gas) external view returns (uint256) { return _getPayback(gas); } /** * @dev Return the performance over the last time interval */ function getPerformanceFee() external view returns (uint256 performanceFeeToWallet) { performanceFeeToWallet = 0; if ( ILimaToken(limaToken).getUnderlyingTokenBalanceOf(1000 ether) > lastUnderlyingBalancePer1000 && performanceFee != 0 ) { performanceFeeToWallet = ( ILimaToken(limaToken).getUnderlyingTokenBalance().sub( ILimaToken(limaToken) .totalSupply() .mul(lastUnderlyingBalancePer1000) .div(1000 ether) ) ) .div(performanceFee); } } /* ============ User ============ */ function getFee(uint256 _amount, uint256 _fee) public pure returns (uint256 feeAmount) { //get fee if (_fee > 0) { return _amount.div(_fee); } return 0; } /** * @dev Gets the expecterd return of a redeem */ function getExpectedReturnRedeem(address _to, uint256 _amount) external view returns (uint256 minimumReturn) { _amount = getUnderlyingTokenBalanceOf(_amount); _amount = _amount.sub(getFee(_amount, burnFee)); return getExpectedReturn(currentUnderlyingToken, _to, _amount); } /** * @dev Gets the expecterd return of a create */ function getExpectedReturnCreate(address _from, uint256 _amount) external view returns (uint256 minimumReturn) { _amount = _amount.sub(getFee(_amount, mintFee)); return getExpectedReturn(_from, currentUnderlyingToken, _amount); } /** * @dev Gets the expected returns of a rebalance */ function getExpectedReturnRebalance( address _bestToken, uint256 _amountToSellForLink ) external view returns ( uint256 tokenPosition, uint256 minimumReturn, uint256 minimumReturnGov, uint256 minimumReturnLink ) { address _govToken = limaSwap.getGovernanceToken(currentUnderlyingToken); bool isInUnderlying; (tokenPosition, isInUnderlying) = underlyingTokens.indexOf(_bestToken); require(isInUnderlying, "LH1"); minimumReturnLink = getExpectedReturn( currentUnderlyingToken, LINK, _amountToSellForLink ); minimumReturnGov = getExpectedReturn( _govToken, _bestToken, IERC20(_govToken).balanceOf(limaToken) ); minimumReturn = getExpectedReturn( currentUnderlyingToken, _bestToken, IERC20(currentUnderlyingToken).balanceOf(limaToken).sub( _amountToSellForLink ) ); return ( tokenPosition, minimumReturn, minimumReturnGov, minimumReturnLink ); } /* ============ Oracle ============ */ function decipherNumber(uint32 data) internal pure returns (uint256) { uint8 shift = uint8(data >> 24); return uint256(data & 0x00FF_FFFF) << shift; } /** * @dev Extracts data from oracle payload. * Extrects 4 values (address, number, number, number): * address, which takes last 160 bits of oracle bytes32 data,( it extracts it by mapping bytes32 to uint160, which allows to get rid of other 96 bits) * 3 numbers: * 1. Shift bits to the right (there is no bit shift opcode in the evm though, so this operation might be more expensive than I thought), so given (one of the three) number has it bits on last (least significant) 32 bits of uint256. * 2. Now I get rid of more significant bits (all on the other 224 bits) by casting to uint32. * 3. Once I have uint32, I have to now split this numbers into two values. One uint8 and one uint24. This uint24 represents the original number, but divided by 2^<uint8_value>, so in other words, original number, but shifted to the right by number of bits, where this number is stored in this uint8 value. */ function decodeOracleData(bytes32 _data) public pure returns ( address addr, uint256 a, uint256 b, uint256 c ) { a = decipherNumber(uint32(uint256(_data) >> (256 - 32))); b = decipherNumber(uint32(uint256(_data) >> (256 - 64))); c = decipherNumber(uint32(uint256(_data) >> (256 - 96))); addr = address( uint160((uint256(_data) << (256 - 20 * 8)) >> (256 - 20 * 8)) ); return (addr, a, b, c); } function getRebalancingData() external view returns ( address newtoken, uint256 minimumReturn, uint256 minimumReturnGov, uint256 amountToSellForLink, uint256 _minimumReturnLink, address governanceToken ) { ( newtoken, minimumReturn, minimumReturnGov, amountToSellForLink ) = decodeOracleData(oracleData); return ( newtoken, minimumReturn, minimumReturnGov, amountToSellForLink, minimumReturnLink, limaSwap.getGovernanceToken(currentUnderlyingToken) ); } function isReceiveOracleData(bytes32 _requestId, address _msgSender) external view { require( _requestId == requestId && _msgSender == address(oracle) && !isOracleDataReturned, "LM11" ); } } pragma solidity ^0.6.6; import { ERC20PausableUpgradeSafe, IERC20, SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import { SafeERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import {AddressArrayUtils} from "./library/AddressArrayUtils.sol"; import {ILimaSwap} from "./interfaces/ILimaSwap.sol"; import {ILimaManager} from "./interfaces/ILimaManager.sol"; import {ILimaTokenHelper} from "./interfaces/ILimaTokenHelper.sol"; import {ILimaOracleReceiver} from "./interfaces/ILimaOracleReceiver.sol"; import {ILimaOracle} from "./interfaces/ILimaOracle.sol"; /** * @title LimaToken * @author Lima Protocol * * Standard LimaToken. */ contract LimaToken is ERC20PausableUpgradeSafe { using AddressArrayUtils for address[]; using SafeMath for uint256; using SafeERC20 for IERC20; event Create(address _from, uint256 _amount); event Redeem(address _from, uint256 _amount); event RebalanceInit(address _sender); event RebalanceExecute(address _oldToken, address _newToken); event ReadyForRebalance(); // address public owner; ILimaTokenHelper public limaTokenHelper; //limaTokenStorage /** * @dev Initializes contract */ function initialize( string memory name, string memory symbol, address _limaTokenHelper, uint256 _underlyingAmount, uint256 _limaAmount ) public initializer { limaTokenHelper = ILimaTokenHelper(_limaTokenHelper); __ERC20_init(name, symbol); __ERC20Pausable_init(); if (_underlyingAmount > 0 && _limaAmount > 0) { IERC20(limaTokenHelper.currentUnderlyingToken()).safeTransferFrom( msg.sender, address(this), _underlyingAmount ); _mint(msg.sender, _limaAmount); } } /* ============ Modifiers ============ */ modifier onlyNotRebalancing() { _isRebalancing(false); _; } modifier onlyRebalancing() { _isRebalancing(true); _; } function _isRebalancing(bool active) internal view { // Internal function used to reduce bytecode size require( limaTokenHelper.isRebalancing() == active, "LM10" //"Only when rebalancing is active/inactive" ); } modifier onlyUnderlyingToken(address _token) { _isOnlyUnderlyingToken(_token); _; } function _isOnlyUnderlyingToken(address _token) internal view { // Internal function used to reduce bytecode size require( limaTokenHelper.isUnderlyingTokens(_token), "LM1" //"Only token that are part of Underlying Tokens" ); } modifier onlyInvestmentToken(address _investmentToken) { // Internal function used to reduce bytecode size _isOnlyInvestmentToken(_investmentToken); _; } function _isOnlyInvestmentToken(address _investmentToken) internal view { // Internal function used to reduce bytecode size require( limaTokenHelper.isInvestmentToken(_investmentToken), "LM7" //nly token that are approved to invest/payout. ); } /** * @dev Throws if called by any account other than the limaManager. */ modifier onlyLimaManagerOrOwner() { _isOnlyLimaManagerOrOwner(); _; } function _isOnlyLimaManagerOrOwner() internal view { require( limaTokenHelper.limaManager() == _msgSender() || limaTokenHelper.owner() == _msgSender(), "LM2" // "Ownable: caller is not the limaManager or owner" ); } modifier onlyAmunUsers() { _isOnlyAmunUser(); _; } function _isOnlyAmunUser() internal view { if (limaTokenHelper.isOnlyAmunUserActive()) { require( limaTokenHelper.isAmunUser(msg.sender), "LM3" //"AmunUsers: msg sender must be part of amunUsers." ); } } /* ============ View ============ */ function getUnderlyingTokenBalance() public view returns (uint256 balance) { return IERC20(limaTokenHelper.currentUnderlyingToken()).balanceOf( address(this) ); } function getUnderlyingTokenBalanceOf(uint256 _amount) public view returns (uint256 balanceOf) { return getUnderlyingTokenBalance().mul(_amount).div(totalSupply()); } /* ============ Lima Manager ============ */ function mint(address account, uint256 amount) public onlyLimaManagerOrOwner { _mint(account, amount); } // pausable functions function pause() external onlyLimaManagerOrOwner { _pause(); } function unpause() external onlyLimaManagerOrOwner { _unpause(); } function _approveLimaSwap(address _token, uint256 _amount) internal { if ( IERC20(_token).allowance( address(this), address(limaTokenHelper.limaSwap()) ) < _amount ) { IERC20(_token).safeApprove( address(limaTokenHelper.limaSwap()), limaTokenHelper.MAX_UINT256() ); } } function _swap( address _from, address _to, uint256 _amount, uint256 _minimumReturn ) internal returns (uint256 returnAmount) { if (address(_from) != address(_to) && _amount > 0) { _approveLimaSwap(_from, _amount); returnAmount = limaTokenHelper.limaSwap().swap( address(this), _from, _to, _amount, _minimumReturn ); return returnAmount; } return _amount; } function _unwrap( address _token, uint256 _amount, address _recipient ) internal { if (_amount > 0) { _approveLimaSwap(_token, _amount); limaTokenHelper.limaSwap().unwrap(_token, _amount, _recipient); } } /** * @dev Swaps token to new token */ function swap( address _from, address _to, uint256 _amount, uint256 _minimumReturn ) public onlyLimaManagerOrOwner returns (uint256 returnAmount) { return _swap(_from, _to, _amount, _minimumReturn); } /** * @dev Initilises rebalances proccess and calls oracle * Note: Can be called every 24 h by everyone and will be repayed */ function initRebalance() external onlyNotRebalancing { uint256 startGas = gasleft(); require( limaTokenHelper.lastRebalance() + limaTokenHelper.rebalanceInterval() < now, "LM5" //"Rebalance only every 24 hours" ); limaTokenHelper.setLastRebalance(now); limaTokenHelper.setIsRebalancing(true); IERC20(limaTokenHelper.LINK()).transfer( address(limaTokenHelper.oracle()), 1 * 10**17 ); // 0.1 LINK bytes32 _requestId = limaTokenHelper.oracle().requestDeliveryStatus( address(this) ); limaTokenHelper.setRequestId(_requestId); emit RebalanceInit(msg.sender); _mint(msg.sender, limaTokenHelper.getPayback(startGas - gasleft())); } /* ============ Main Functions ============ */ // response structure: uint8-uint24-uint8-uint24-uint8-uint24-address /** * @dev Data Provided by oracle needed for rebalance * @param _requestId The requestId from oracle. * @param _data The packed data newToken address, minimumReturn for rebalance, * minimumReturn on governance token swap, and amount to sell for LINK. * response structure: uint8-uint24-uint8-uint24-uint8-uint24-address */ function receiveOracleData(bytes32 _requestId, bytes32 _data) public virtual onlyRebalancing { limaTokenHelper.isReceiveOracleData(_requestId, msg.sender); limaTokenHelper.setOracleData(_data); limaTokenHelper.setIsOracleDataReturned(true); emit ReadyForRebalance(); } /** * @dev Rebalances LimaToken * Will do swaps of potential governancetoken, underlying token to token that provides higher return * Will swap to LINK when needed * Uses data stored by receiveOracleData in getRebalancingData() */ function rebalance() external onlyRebalancing { uint256 startGas = gasleft(); require(limaTokenHelper.isOracleDataReturned(), "LM8"); //only rebalance data is returned ( address _bestToken, uint256 _minimumReturn, uint256 _minimumReturnGov, uint256 _amountToSellForLink, uint256 _minimumReturnLink, address _govToken ) = limaTokenHelper.getRebalancingData(); //send fee to fee wallet _unwrap( limaTokenHelper.currentUnderlyingToken(), limaTokenHelper.getPerformanceFee(), limaTokenHelper.feeWallet() ); //swap link if (_amountToSellForLink != 0) { _swap( limaTokenHelper.currentUnderlyingToken(), limaTokenHelper.LINK(), _amountToSellForLink, _minimumReturnLink ); } //swap gov _swap( _govToken, _bestToken, IERC20(_govToken).balanceOf(address(this)), _minimumReturnGov ); //swap underlying _swap( limaTokenHelper.currentUnderlyingToken(), _bestToken, getUnderlyingTokenBalance(), _minimumReturn ); emit RebalanceExecute( limaTokenHelper.currentUnderlyingToken(), _bestToken ); limaTokenHelper.setCurrentUnderlyingToken(_bestToken); limaTokenHelper.setLastUnderlyingBalancePer1000( getUnderlyingTokenBalanceOf(1000 ether) ); limaTokenHelper.setIsRebalancing(false); limaTokenHelper.setIsOracleDataReturned(false); _mint(msg.sender, limaTokenHelper.getPayback(startGas - gasleft())); } /** * @dev Redeem the value of LimaToken in _payoutToken. * @param _payoutToken The address of token to payout with. * @param _amount The amount to redeem. * @param _recipient The user address to redeem from/to. * @param _minimumReturn The minimum amount to return or else revert. */ function forceRedeem( address _payoutToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) external onlyLimaManagerOrOwner returns (bool) { return _redeem( _recipient, _payoutToken, _amount, _recipient, _minimumReturn ); } /* ============ User ============ */ /** * @dev Creates new token for holder by converting _investmentToken value to LimaToken * Note: User need to approve _amount on _investmentToken to this contract * @param _investmentToken The address of token to invest with. * @param _amount The amount of investment token to create lima token from. * @param _recipient The address to transfer the lima token to. * @param _minimumReturn The minimum amount to return or else revert. */ function create( address _investmentToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) external onlyInvestmentToken(_investmentToken) onlyAmunUsers onlyNotRebalancing returns (bool) { uint256 balance = getUnderlyingTokenBalance(); IERC20(_investmentToken).safeTransferFrom( msg.sender, address(this), _amount ); //get fee uint256 fee = limaTokenHelper.getFee( _amount, limaTokenHelper.mintFee() ); if (fee > 0) { IERC20(_investmentToken).safeTransfer( limaTokenHelper.feeWallet(), fee ); _amount = _amount - fee; } _amount = _swap( _investmentToken, limaTokenHelper.currentUnderlyingToken(), _amount, _minimumReturn ); _amount = totalSupply().mul(_amount).div(balance); require(_amount > 0, "zero"); _mint(_recipient, _amount); emit Create(msg.sender, _amount); return true; } function _redeem( address _investor, address _payoutToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) internal onlyInvestmentToken(_payoutToken) onlyNotRebalancing returns (bool) { uint256 underlyingAmount = getUnderlyingTokenBalanceOf(_amount); _burn(_investor, _amount); uint256 fee = limaTokenHelper.getFee( underlyingAmount, limaTokenHelper.burnFee() ); if (fee > 0) { _unwrap( limaTokenHelper.currentUnderlyingToken(), fee, limaTokenHelper.feeWallet() ); underlyingAmount = underlyingAmount - fee; } emit Redeem(msg.sender, _amount); _amount = _swap( limaTokenHelper.currentUnderlyingToken(), _payoutToken, underlyingAmount, _minimumReturn ); require(_amount > 0, "zero"); IERC20(_payoutToken).safeTransfer(_recipient, _amount); return true; } /** * @dev Redeem the value of LimaToken in _payoutToken. * @param _payoutToken The address of token to payout with. * @param _amount The amount of lima token to redeem. * @param _recipient The address to transfer the payout token to. * @param _minimumReturn The minimum amount to return or else revert. */ function redeem( address _payoutToken, uint256 _amount, address _recipient, uint256 _minimumReturn ) external returns (bool) { return _redeem( msg.sender, _payoutToken, _amount, _recipient, _minimumReturn ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; import { OwnableUpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import { SafeERC20, SafeMath } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import { IERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import { ReentrancyGuardUpgradeSafe } from "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import {Compound} from "./interfaces/Compound.sol"; import {Aave} from "./interfaces/Aave.sol"; import {AToken} from "./interfaces/AToken.sol"; import {ICurve} from "./interfaces/ICurve.sol"; import {IOneSplit} from "./interfaces/IOneSplit.sol"; contract AddressStorage is OwnableUpgradeSafe { enum Lender {NOT_FOUND, COMPOUND, AAVE} enum TokenType {NOT_FOUND, STABLE_COIN, INTEREST_TOKEN} address internal constant dai = address( 0x6B175474E89094C44Da98b954EedeAC495271d0F ); address internal constant usdc = address( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 ); address internal constant usdt = address( 0xdAC17F958D2ee523a2206206994597C13D831ec7 ); //governance token address internal constant AAVE = address( 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 ); address internal constant COMP = address( 0xc00e94Cb662C3520282E6f5717214004A7f26888 ); address public aaveLendingPool; address public aaveCore; address public curve; address public oneInchPortal; mapping(address => Lender) public lenders; mapping(address => TokenType) public tokenTypes; mapping(address => address) public interestTokenToUnderlyingStablecoin; // @dev get ERC20 address for governance token from Compound or AAVE // @param _token ERC20 address function getGovernanceToken(address token) public view returns (address) { if (lenders[token] == Lender.COMPOUND) { return COMP; } else if (lenders[token] == Lender.AAVE) { return AAVE; } else { return address(0); } } // @dev get interest bearing token information // @param _token ERC20 address // @return lender protocol (Lender) and TokenTypes enums function getTokenInfo(address interestBearingToken) public view returns (Lender, TokenType) { return ( lenders[interestBearingToken], tokenTypes[interestBearingToken] ); } // @dev set new Aave lending pool address // @param _newAaveLendingPool Aave lending pool address function setNewAaveLendingPool(address _newAaveLendingPool) public onlyOwner { require( _newAaveLendingPool != address(0), "new _newAaveLendingPool is empty" ); aaveLendingPool = _newAaveLendingPool; } // @dev set new Aave core address // @param _newAaveCore Aave core address function setNewAaveCore(address _newAaveCore) public onlyOwner { require(_newAaveCore != address(0), "new _newAaveCore is empty"); aaveCore = _newAaveCore; } // @dev set new curve pool // @param _newCurvePool Curve pool address function setNewCurvePool(address _newCurvePool) public onlyOwner { require(_newCurvePool != address(0), "new _newCurvePool is empty"); curve = _newCurvePool; } // @dev set new 1Inch portal // @param _newOneInch Curve pool address function setNewOneInch(address _newOneInch) public onlyOwner { require(_newOneInch != address(0), "new _newOneInch is empty"); oneInchPortal = _newOneInch; } // @dev set interest bearing token to its stable coin underlying // @param interestToken ERC20 address // @param underlyingToken stable coin ERC20 address function setInterestTokenToUnderlyingStablecoin( address interestToken, address underlyingToken ) public onlyOwner { require( interestToken != address(0) && underlyingToken != address(0), "token addresses must be entered" ); interestTokenToUnderlyingStablecoin[interestToken] = underlyingToken; } // @dev set interest bearing token to a lender protocol // @param _token ERC20 address // @param _lender Integer which represents LENDER enum function setAddressToLender(address _token, Lender _lender) public onlyOwner { require(_token != address(0), "!_token"); lenders[_token] = _lender; } // @dev set token to its type // @param _token ERC20 address // @param _tokenType Integer which represents TokenType enum function setAddressTokenType(address _token, TokenType _tokenType) public onlyOwner { require(_token != address(0), "!_token"); tokenTypes[_token] = _tokenType; } } contract LimaSwap is AddressStorage, ReentrancyGuardUpgradeSafe { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public constant MAX_UINT256 = 2**256 - 1; uint16 public constant aaveCode = 94; event Swapped(address from, address to, uint256 amount, uint256 result); function initialize() public initializer { __Ownable_init(); __ReentrancyGuard_init(); aaveLendingPool = address(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); aaveCore = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); curve = address(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); // yPool oneInchPortal = address(0x11111254369792b2Ca5d084aB5eEA397cA8fa48B); // 1Inch address cDai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address cUsdc = 0x39AA39c021dfbaE8faC545936693aC917d5E7563; address cUsdt = 0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9; address aDai = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address aUsdc = 0x9bA00D6856a4eDF4665BcA2C2309936572473B7E; address aUsdt = 0x71fc860F7D3A592A4a98740e39dB31d25db65ae8; // set token types setAddressTokenType(dai, TokenType.STABLE_COIN); setAddressTokenType(usdc, TokenType.STABLE_COIN); setAddressTokenType(usdt, TokenType.STABLE_COIN); setAddressTokenType(cDai, TokenType.INTEREST_TOKEN); setAddressTokenType(cUsdc, TokenType.INTEREST_TOKEN); setAddressTokenType(cUsdt, TokenType.INTEREST_TOKEN); setAddressTokenType(aDai, TokenType.INTEREST_TOKEN); setAddressTokenType(aUsdc, TokenType.INTEREST_TOKEN); setAddressTokenType(aUsdt, TokenType.INTEREST_TOKEN); // set interest bearing tokens to lenders setAddressToLender(cDai, Lender.COMPOUND); // compoundDai setAddressToLender(cUsdc, Lender.COMPOUND); // compoundUSDC setAddressToLender(cUsdt, Lender.COMPOUND); // compoundUSDT setAddressToLender(aDai, Lender.AAVE); // aaveDai setAddressToLender(aUsdc, Lender.AAVE); // aaveUSDC setAddressToLender(aUsdt, Lender.AAVE); // aaveUSDT // set interest tokens to their underlying stable coins setInterestTokenToUnderlyingStablecoin(cDai, dai); //compoundDai setInterestTokenToUnderlyingStablecoin(aDai, dai); // aaveDai setInterestTokenToUnderlyingStablecoin(cUsdc, usdc); //compoundUsdc setInterestTokenToUnderlyingStablecoin(aUsdc, usdc); //aaveUsdc setInterestTokenToUnderlyingStablecoin(cUsdt, usdt); // compoundUsdt setInterestTokenToUnderlyingStablecoin(aUsdt, usdt); // aaveUsdt // infinitely approve tokens IERC20(dai).safeApprove(aaveCore, MAX_UINT256); IERC20(dai).safeApprove(cDai, MAX_UINT256); // compoundDai IERC20(dai).safeApprove(curve, MAX_UINT256); // curve IERC20(usdc).safeApprove(aaveCore, MAX_UINT256); IERC20(usdc).safeApprove(cUsdc, MAX_UINT256); // compoundUSDC IERC20(usdc).safeApprove(curve, MAX_UINT256); // curve IERC20(usdt).safeApprove(aaveCore, MAX_UINT256); IERC20(usdt).safeApprove(cUsdt, MAX_UINT256); // compoundUSDT IERC20(usdt).safeApprove(curve, MAX_UINT256); // curve } /* ============ Public ============ */ // @dev only used for stable coins usdt usdc and dai // @param fromToken from ERC20 address // @param toToken destination ERC20 address // @param amount Number in fromToken function getExpectedReturn( address fromToken, address toToken, uint256 amount ) public view returns (uint256 returnAmount) { (int128 i, int128 j) = _calculateCurveSelector( IERC20(fromToken), IERC20(toToken) ); returnAmount = ICurve(curve).get_dy_underlying(i, j, amount); } // @dev Add function to remove locked tokens that may be sent by users accidently to the contract // @param token ERC20 address of token // @param recipient Beneficiary of the token transfer // @param amount Number to tranfer function removeLockedErc20( address token, address recipient, uint256 amount ) external onlyOwner { IERC20(token).safeTransfer(recipient, amount); } // @dev balance of an ERC20 token within swap contract // @param token ERC20 token address function balanceOfToken(address token) public view returns (uint256) { return IERC20(token).balanceOf(address(this)); } // @dev swap from token A to token B for sender. Receiver of funds needs to be passed. Sender needs to approve LimaSwap to use her tokens // @param recipient Beneficiary of the swap tx // @param from ERC20 address of token to swap from // @param to ERC20 address to swap to // @param amount from Token value to swap // @param minReturnAmount Minimum amount that needs to be returned. Used to prevent frontrunning function swap( address recipient, address from, address to, uint256 amount, uint256 minReturnAmount ) public nonReentrant returns (uint256) { uint256 balanceofSwappedtoken; // non core swaps if ( tokenTypes[from] == TokenType.NOT_FOUND || tokenTypes[to] == TokenType.NOT_FOUND ) { (uint256 retAmount, uint256[] memory distribution) = IOneSplit( oneInchPortal ) .getExpectedReturn(IERC20(from), IERC20(to), amount, 1, 0); balanceofSwappedtoken = IOneSplit(oneInchPortal).swap( IERC20(from), IERC20(to), amount, retAmount, distribution, 0 // flags ); } else { // core swaps uint256 returnedAmount = _swapCoreTokens( from, to, amount, minReturnAmount ); balanceofSwappedtoken = returnedAmount; } IERC20(to).safeTransfer(recipient, balanceofSwappedtoken); emit Swapped(from, to, amount, balanceofSwappedtoken); return balanceofSwappedtoken; } // @dev swap interesting bearing token to its underlying from either AAve or Compound // @param interestBearingToken ERC20 address of interest bearing token // @param amount Interest bearing token value // @param recipient Beneficiary of the tx function unwrap( address interestBearingToken, uint256 amount, address recipient ) public nonReentrant { (Lender l, TokenType t) = getTokenInfo(interestBearingToken); require(t == TokenType.INTEREST_TOKEN, "not an interest bearing token"); _transferAmountToSwap(interestBearingToken, amount); if (l == Lender.COMPOUND) { _withdrawCompound(interestBearingToken); } else if (l == Lender.AAVE) { _withdrawAave(interestBearingToken); } address u = interestTokenToUnderlyingStablecoin[interestBearingToken]; uint256 balanceofSwappedtoken = balanceOfToken(u); IERC20(u).safeTransfer(recipient, balanceofSwappedtoken); } /* ============ Internal ============ */ function _swapCoreTokens( address from, address to, uint256 amount, uint256 minReturnAmount ) internal returns (uint256 balanceofSwappedtoken) { address fromTokencalculatedUnderlyingStablecoin; // from token calculations if (tokenTypes[from] == TokenType.INTEREST_TOKEN) { _transferAmountToSwap(from, amount); if (lenders[from] == Lender.COMPOUND) { _withdrawCompound(from); } else if (lenders[from] == Lender.AAVE) { _withdrawAave(from); } fromTokencalculatedUnderlyingStablecoin = interestTokenToUnderlyingStablecoin[from]; } else { _transferAmountToSwap(from, amount); fromTokencalculatedUnderlyingStablecoin = from; } // to token calculations if (tokenTypes[to] == TokenType.STABLE_COIN) { if (fromTokencalculatedUnderlyingStablecoin == to) { balanceofSwappedtoken = balanceOfToken( fromTokencalculatedUnderlyingStablecoin ); } else { _swapViaCurve( fromTokencalculatedUnderlyingStablecoin, to, minReturnAmount ); balanceofSwappedtoken = balanceOfToken(to); } } else { address toTokenStablecoin = interestTokenToUnderlyingStablecoin[to]; if (fromTokencalculatedUnderlyingStablecoin != toTokenStablecoin) { _swapViaCurve( fromTokencalculatedUnderlyingStablecoin, toTokenStablecoin, minReturnAmount ); } uint256 balanceToTokenStableCoin = balanceOfToken( toTokenStablecoin ); if (balanceToTokenStableCoin > 0) { if (lenders[to] == Lender.COMPOUND) { _supplyCompound(to, balanceToTokenStableCoin); } else if (lenders[to] == Lender.AAVE) { _supplyAave(toTokenStablecoin, balanceToTokenStableCoin); } } balanceofSwappedtoken = balanceOfToken(to); } } function _transferAmountToSwap(address from, uint256 amount) internal { IERC20(from).safeTransferFrom(msg.sender, address(this), amount); } // curve interface functions function _calculateCurveSelector(IERC20 fromToken, IERC20 toToken) internal pure returns (int128, int128) { IERC20[] memory tokens = new IERC20[](3); tokens[0] = IERC20(dai); tokens[1] = IERC20(usdc); tokens[2] = IERC20(usdt); int128 i = 0; int128 j = 0; for (uint256 t = 0; t < tokens.length; t++) { if (fromToken == tokens[t]) { i = int128(t + 1); } if (toToken == tokens[t]) { j = int128(t + 1); } } return (i - 1, j - 1); } function _swapViaCurve( address from, address to, uint256 minAmountToPreventFrontrunning ) internal { (int128 i, int128 j) = _calculateCurveSelector( IERC20(from), IERC20(to) ); uint256 balanceStabletoken = balanceOfToken(from); ICurve(curve).exchange_underlying( i, j, balanceStabletoken, minAmountToPreventFrontrunning ); } // compound interface functions function _supplyCompound(address interestToken, uint256 amount) internal { require( Compound(interestToken).mint(amount) == 0, "COMPOUND: supply failed" ); } function _withdrawCompound(address cToken) internal { uint256 balanceInCToken = IERC20(cToken).balanceOf(address(this)); if (balanceInCToken > 0) { require( Compound(cToken).redeem(balanceInCToken) == 0, "COMPOUND: withdraw failed" ); } } // aave interface functions function _supplyAave(address _underlyingToken, uint256 amount) internal { Aave(aaveLendingPool).deposit(_underlyingToken, amount, aaveCode); } function _withdrawAave(address aToken) internal { uint256 amount = IERC20(aToken).balanceOf(address(this)); if (amount > 0) { AToken(aToken).redeem(amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; import { LimaToken } from "./LimaToken.sol"; contract LimaTokenV2 is LimaToken { function newFunction() public pure returns(uint256) { return 1; } }
(Vyper part)YEARN VAULT V2 SMART CONTRACT AUDIT December 2, 2020TABLE OF CONTENTS 2 22INTRODUCTION TO THE AUDIT.............................................. General provisions ................................................. Scope of audit .....................................................SECURITY ASSESSMENT PRINCIPLES ........................................ 3 Classification of issues ........................................... 3 Security assessment methodology .................................... 3 DETECTED ISSUES ....................................................... 4 4 Critical ........................................................... Major .............................................................. 4 Warnings ........................................................... 5 1. Code commentary doesn’t comply with real implementation ...... 5 2. Potential issue with re-entrancy ............................. 5 1. 3.Typo in commentary............................................. 7 4.Implicit loss calculation .................................... 7 5. 6.Strategy can report loss and gain at the same time............ 8 9 CONCLUSION AND RESULTS ................................................ ABOUT MIXBYTES ........................................................ 9 DISCLAIMER ............................................................ 10 1Unoptimized withdrawalQueue updating......................... .. 8Comments ........................................................... 6 2. Optimize deposit amount check................................. 6Adding Approval event in transferFrom ....................... .. 61. Potential withdrawal lock .................................... 401 INTRODUCTION TO THE AUDIT General Provisions Scope of the Audit The scope of the audit includes the following smart contracts at: https://github.com/iearn-finance/yearn-vaults/ blob/054034304c7912d227d460feadc23177103de0b9/contracts/Vault.vy The audited commit identifiers are: 054034304c7912d227d460feadc23177103de0b9 2 Yearn Finance is a decentralized investment aggregator that leverages composability and uses automated strategies to earn high yield on crypto assets. The audited contract is a part of a new second version of Yearn vaults. Yearn vaults represent a user funds manager in Yearn ecosystem. Smart contract provides an entry point for a user to deposit and withdraw funds and under the hood operates with linked strategies. The code is written using new Vyper language that improved readability of the code and allowed auditors to consider mostly only on business logic. (tag v0.2.0)02SECURITY ASSESSMENT PRINCIPLES Classification of Issues CRITICAL: Bugs leading to Ether or token theft, fund access locking or any other loss of Ether/tokens to be transferred to any party (for example, dividends). MAJOR: Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement. WARNINGS: Bugs that can break the intended contract logic or expose it to DoS attacks. COMMENTS: Other issues and recommendations reported to/ acknowledged by the team. Security Assessment Methodology Two auditors independently verified the code. Stages of the audit were as follows: "Blind" manual check of the code and its model "Guided" manual code review Checking the code compliance with the customer requirements Discussion of independent audit results Report preparation 303DETECTED ISSUES CRITICAL Not found MAJOR 1.Potential withdrawal lock Description Status Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/commits/ b129fb3b669322640dbe98b05fd3b236848613fb 4At this line: https://github.com/iearn-finance/yearn-vaults/ blob/054034304c7912d227d460feadc23177103de0b9/contracts/Vault.vy#L787 amountNeeded: uint256 = value - sel f.token.balanceOf(self) In case if the result of withdrawals in the previous loop iteration self.token.balanceOf(self) becomes more than value that will cause a transaction revert. That scenario is possible because only for the first iteration we can exactly consider that value more than self.token.balanceOf(self), but according to the withdrawal logic there is no check for the following iterations that the real withdrawn amount(after Strategy(strategy).withdraw(amountNe eded) call) is less or equal to what is desired amountNeeded. Recommendation It seems in normal/optimistic flow that Strategy(strategy).withdraw(amountN eeded) never withdraws more tokens than requested, but anyway we recommend properly handling a pessimistic case because strategy is an external contract and can be broken. Due to withdrawal queue, it can be changed only by governance (usually governance is msig or smth like that). Unexpected strategy behavior can lock withdrawals for undefined period that might be fatal in some cases.5WARNINGS 1.Code commentary doesn’t comply with real implementation Description At line it is defined that rate limit has “tokens per block” dimension: We recommend keeping commentaries consistent with implementationRecommendation“Increase/decrease per block” But in rate limit checker code https://github.com/iearn-finance/ yearn-vaults/blob/054034304c7912d227d460feadc23177103de0b9/contracts/ Vault.vy#L1124 strategy_rateLimit assumed as variable with “tokens per second” dimension Status Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/ commits/62258c98bfd98315672b5f73b31b825438bec439 Status Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/ commits/669c7ff9125197c3dc684fb88caa4eb839c5c0f0 2.Potential issue with re-entrancy Description Method repor t at this line called by strategy makes an external call back to strategy in _assessFees method: https://github.com/iearn-finance/yearn- vaults/blob/054034304c7912d227d460feadc23177103de0b9/contracts/ Vault.vy#L1239. So broken or hacked, strategy can call back vaults methods while the current state is not finalized. Recommendation We recommend adding re- entrancy checks to avoid potential pro blems. Especially when the code logic is complicated even if for now the code is safe , in future it’s really easy to implicitly introduce some bugs.6COMMENTS 1. Adding Approval event in transferFrom Description Here https://github.com/iearn-finance/yearn-vaults/ blob/054034304c7912d227d460feadc23177103de0b9/contracts/Vault.vy#L468 we have a decrease in allowance as a result of transferFrom call, but new Approval event isn’t emitted. Recommendation That behavior is not required by EIP20, but it’s good to allow the client- side apps to sync the actual allowance amount using only events(without fetch data from the node state). Example from openzeppelin’s implementation: https://github.com/OpenZeppelin/openzeppelin-contracts/ blob/master/contracts/token/ERC20/ERC20.sol#L154 Status Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/commits/ e5f8bee60e9877ad4301b1d0e3fcf9ff13111350 2.Optimize deposit amount check Description Following check of deposit, the amount is required only if the previous condition returns false, in another case amount value is already limited by self.depositLi mit - self. _totalAssets( ). Recommendation We can move limit check into else branch of the condition above to save gas. Status Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/ commits/1e94dc598e61961954c254153592ea36937e1a54 73.Typo in commentary Description At line: https://github.com/iearn-finance/yearn-vaults/ blob/054034304c7912d227d460feadc23177103de0b9/contracts/Vault.vy#L1270 @return Amount of debt outstanding (iff totalDebt > debtLimit). There is an extra ‘f’ Recommendation We suggest removing the excess character. Status Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/commits/ cc82e882dfe686cb3eaa623e574c0cd16d60774c 4. Implicit loss calculation Description _reportLoss function defined here implicitly changes the passed value of the loss tokens amount. Implicit behavior might be wrongly missed and the caller can expect another result. Recommendation We recommend to reduce the implicit logic as much as possible Status AcknowledgedStatus Acknowledged 85. Unoptimized withdrawalQueue updating Description At lines: https://github.com/iearn-finance/yearn-vaults/ blob/054034304c7912d227d460feadc23177103de0b9/contracts/Vault.vy#L1062-L1066 , https://github.com/iearn-finance/yearn-vaults/ blob/054034304c7912d227d460feadc23177103de0b9/contracts/Vault.vy#L1041-L1046 There are some places when we need to remove or add strategy. For now, we first iterate over the array to exclude duplicates or find item idx to remove and after that we call _organizeWithdrawalQueue to normalize the array. With this approach operations complexity can reach up to O(n^2). Recommendation It seems easier and cheaper to add/remove elements with instant normalization in a single walk through the array. 6. Strategy can report loss and gain at the same time Description For now strategy can report loss and gain at the same time. It’s not a problem according to the code logic but it’s little bit weird within the meaning. Recommendation We recommend to make sure that this behavior is correct. Status No issue04CONCLUSION AND RESULTS Findings list Level Amount CRITICAL 0 MAJOR 1 WARNINGS 2 COMMENTS 6 Final commit identifier with all fixes: 99dcc2a8ce495ac6c2ff08e633e5b475a3088255 Smart contracts have been audited. The code is clear and well written. Compared with the Solidity based code, current implementation mostly looks more strict in terms of allowed invariants and it is much better to read and understand contract logic because the code mostly contains business-logic related constructions. Several suspicious places were spotted and some improvements were proposed. 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. Contacts https://github.com/mixbytes/audits_public https://mixbytes.io/ hello@mixbytes.io https://t.me/MixBytes 9Disclaimer 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. 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. 10
MODERATE: Bugs that can lead to a denial of service attack or a bug that can be used to manipulate the system in a way that is not intended. MINOR: All other bugs that do not fit into any of the above categories. Security Assessment Methodology The audit was conducted in accordance with the OpenZeppelin Security Best Practices and the following security assessment methodology: • Manual source code review • Automated static analysis • Automated dynamic analysis • Manual testing 3 DETECTED ISSUES Critical None Major None Warnings 1. Code commentary doesn’t comply with real implementation Problem: The code commentary does not match the actual implementation. Fix: The code commentary should be updated to match the actual implementation. 2. Potential issue with re-entrancy Problem: The code does not check for re-entrancy attacks. Fix: The code should be updated to check for re-entrancy attacks. 3. Typo in commentary Problem: There is a typo in the code commentary. Fix: The code commentary should be updated to fix the typo. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 1 - Critical: 0 Major 1.Potential withdrawal lock - Problem: In case if the result of withdrawals in the previous loop iteration self.token.balanceOf(self) becomes more than value that will cause a transaction revert. - Fix: Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/commits/b129fb3b669322640dbe98b05fd3b236848613fb Warnings 1.Code commentary doesn’t comply with real implementation - Problem: At line it is defined that rate limit has “tokens per block” dimension, but in rate limit checker code it is assumed as variable with “tokens per second” dimension. - Fix: Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/commits/62258c98bfd98315672b5f73b31b825438bec439 Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Here https://github.com/iearn-finance/yearn-vaults/blob/054034304c7912d227d460feadc23177103de0b9/contracts/Vault.vy#L468 we have a decrease in allowance as a result of transferFrom call, but new Approval event isn’t emitted. 2.b Fix: Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/commits/e5f8bee60e9877ad4301b1d0e3fcf9ff13111350 Moderate Issues: 3.a Problem: Optmize deposit amount check 3.b Fix: Fixed at https://github.com/iearn-finance/yearn-vaults/pull/111/commits/1e94dc598e61961954c254153592ea36937e1a54
//SPDX-License-Identifier: Unlicense /* ░██████╗██████╗░███████╗███████╗██████╗░░░░░░░░██████╗████████╗░█████╗░██████╗░ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔══██╗░░░░░░██╔════╝╚══██╔══╝██╔══██╗██╔══██╗ ╚█████╗░██████╔╝█████╗░░█████╗░░██║░░██║█████╗╚█████╗░░░░██║░░░███████║██████╔╝ ░╚═══██╗██╔═══╝░██╔══╝░░██╔══╝░░██║░░██║╚════╝░╚═══██╗░░░██║░░░██╔══██║██╔══██╗ ██████╔╝██║░░░░░███████╗███████╗██████╔╝░░░░░░██████╔╝░░░██║░░░██║░░██║██║░░██║ ╚═════╝░╚═╝░░░░░╚══════╝╚══════╝╚═════╝░░░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝ */ pragma solidity 0.8.11; import "hardhat/console.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Horse is Ownable, ERC721URIStorage { using SafeMath for uint256; using Counters for Counters.Counter; using Strings for uint256; event Mint(address receiver, uint256 tokenId); event ChangeBaseURI(address admin, string uri); event UpdateAge(address user,uint256 tokenId,uint256 age); Counters.Counter private _tokenIds; string public baseURI; mapping(uint256 => string) private uri; mapping(uint256 => uint256) private rarity; mapping(uint256 => uint256) private age; mapping(uint256 => uint256) private bornAt; mapping(address => bool) public minter; uint256 public retriedAge; modifier onlyMinter() { require(minter[msg.sender], "only minter."); _; } constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} function setMinter(address _minter, bool _isMinter) external { minter[_minter] = _isMinter; } // Mint all NFT on deploy and keep data for treading function mint( address _receiver, string memory _uri, uint256 _tokenId, uint256 _rarity, uint256 _age ) public onlyMinter { _mint(_receiver, _tokenId); uri[_tokenId] = _uri; rarity[_tokenId] = _rarity; bornAt[_tokenId] = block.number; age[_tokenId] = _age; emit Mint(_receiver, _tokenId); } function mints( address[] memory _receiver, string[] memory _uri, uint256[] memory _tokenId, uint256[] memory _rarity, uint256[] memory _age ) external onlyMinter { for (uint256 index = 0; index < _receiver.length; index++) { mint( _receiver[index], _uri[index], _tokenId[index], _rarity[index], _age[index] ); } } function getPopularity(uint256 _tokenId) public view returns (uint256) { if (block.number - bornAt[_tokenId] > age[_tokenId]) { return rarity[_tokenId].div(5); } else { return rarity[_tokenId]; } } function setAge(uint256 _tokenId, uint256 _age) external onlyOwner { age[_tokenId] = _age; emit UpdateAge(msg.sender, _tokenId, _age); } function getRemainAge(uint256 _tokenId) external view returns (uint256) { if (age[_tokenId] > block.number.sub(bornAt[_tokenId])) { return age[_tokenId].sub(block.number.sub(bornAt[_tokenId])); } else { return 0; } } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "URI query for nonexistent token"); return string(abi.encodePacked(baseURI, uri[_tokenId], ".json")); } function setBaseURI(string memory _uri) external onlyOwner { baseURI = _uri; emit ChangeBaseURI(msg.sender, _uri); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } } //SPDX-License-Identifier: Unlicense /* ░██████╗██████╗░███████╗███████╗██████╗░░░░░░░░██████╗████████╗░█████╗░██████╗░ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔══██╗░░░░░░██╔════╝╚══██╔══╝██╔══██╗██╔══██╗ ╚█████╗░██████╔╝█████╗░░█████╗░░██║░░██║█████╗╚█████╗░░░░██║░░░███████║██████╔╝ ░╚═══██╗██╔═══╝░██╔══╝░░██╔══╝░░██║░░██║╚════╝░╚═══██╗░░░██║░░░██╔══██║██╔══██╗ ██████╔╝██║░░░░░███████╗███████╗██████╔╝░░░░░░██████╔╝░░░██║░░░██║░░██║██║░░██║ ╚═════╝░╚═╝░░░░░╚══════╝╚══════╝╚═════╝░░░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝ */ pragma solidity 0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; interface IHorse { function mint( address _receiver, string memory _uri, uint256 _tokenId, uint256 _rarity, uint256 _age ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function getPopularity(uint256 tokenId) external returns (uint256); function ownerOf(uint256 tokenId) external returns (address); function isApprovedForAll(address user, address operator) external returns (bool); } contract SwapHorse is Ownable { IHorse public oldHorse; event SwapHorses(address user, uint256[] tokenIds, address oldHorse); event BurnHorse(address user, uint256 tokenId, address oldHorse); constructor(address _oldHorse) { oldHorse = IHorse(_oldHorse); } function swapHorses(uint256[] memory _tokenIds) external { // check owner for (uint256 index = 0; index < _tokenIds.length; index++) { require( oldHorse.ownerOf(_tokenIds[index]) == msg.sender, "User is not owner." ); } require( oldHorse.isApprovedForAll(msg.sender, address(this)), "Require approve contract." ); for (uint256 index = 0; index < _tokenIds.length; index++) { oldHorse.transferFrom( msg.sender, address(this), _tokenIds[index] ); emit BurnHorse(msg.sender, _tokenIds[index], address(oldHorse)); } emit SwapHorses(msg.sender, _tokenIds, address(oldHorse)); } } //SPDX-License-Identifier: Unlicense /* ░██████╗██████╗░███████╗███████╗██████╗░░░░░░░░██████╗████████╗░█████╗░██████╗░ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔══██╗░░░░░░██╔════╝╚══██╔══╝██╔══██╗██╔══██╗ ╚█████╗░██████╔╝█████╗░░█████╗░░██║░░██║█████╗╚█████╗░░░░██║░░░███████║██████╔╝ ░╚═══██╗██╔═══╝░██╔══╝░░██╔══╝░░██║░░██║╚════╝░╚═══██╗░░░██║░░░██╔══██║██╔══██╗ ██████╔╝██║░░░░░███████╗███████╗██████╔╝░░░░░░██████╔╝░░░██║░░░██║░░██║██║░░██║ ╚═════╝░╚═╝░░░░░╚══════╝╚══════╝╚═════╝░░░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝ */ pragma solidity 0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract Shop is Ownable { using SafeMath for uint256; using SafeCast for int256; using SafeERC20 for ERC20; event BuyPack(uint16 packId, uint256 price, address buyer); event SetSaleOpen(bool isOpen); event SetPackPrice(uint16 packId, uint256 price); event SetPackAvaliable(uint16 packId, uint256 amount); event BuyPackAmount(address user, uint16 packId, uint256 amount); event UpdatePriceFeed(address user,address feed); event ClaimToken(address user,uint256 amount); // 100,300,900,1800 mapping(uint16 => uint256) private packPriceDollar; // 3965,5884,567,234 mapping(uint16 => uint256) public packAvaliable; AggregatorV3Interface internal onePriceFeed; bool private openSale; constructor() { onePriceFeed = AggregatorV3Interface( 0xdCD81FbbD6c4572A69a534D8b8152c562dA8AbEF ); } function setPriceFeed(address _address) external onlyOwner { require(!openSale, "Unable to set during sale"); onePriceFeed = AggregatorV3Interface(_address); emit UpdatePriceFeed(msg.sender, _address); } function setPackPrice(uint16 _packId, uint256 _price) external onlyOwner { require(!openSale, "Unable to set during sale"); packPriceDollar[_packId] = _price; emit SetPackPrice(_packId, _price); } function setPackAvaliable(uint16 _packId, uint256 _amount) external onlyOwner { require(!openSale, "Unable to set during sale"); packAvaliable[_packId] = _amount; emit SetPackAvaliable(_packId, _amount); } function setOpenSale(bool _openSale) external onlyOwner { openSale = _openSale; emit SetSaleOpen(_openSale); } function getONERate() public view returns (uint256) { (, int256 price, , , ) = onePriceFeed.latestRoundData(); return uint256(price); } function getPackPrice(uint16 _packId) public view returns (uint256) { uint256 rate = getONERate(); require(rate != 0, "Not found rate for swap."); uint256 payAmountPerDollar = uint256( (1000000000000000000 / uint256(rate)) ).mul(100000000); return packPriceDollar[_packId].mul(payAmountPerDollar); } function buyPack(uint16 _packId) public payable { require(openSale, "Not open sale"); require(packPriceDollar[_packId] > 0, "Price not set"); require(packAvaliable[_packId] > 0, "Not avaliable"); uint256 rate = getONERate(); require(rate != 0, "Not found rate for swap."); uint256 payAmount = getPackPrice(_packId); require(msg.value >= payAmount, "pay amount mismatch"); packAvaliable[_packId] = packAvaliable[_packId].sub(1); // each 100 stable to selled the price is increase to 10$ if (_packId == 0) { if (packAvaliable[_packId] % (100) == 0) { packPriceDollar[_packId] = packPriceDollar[_packId].add(10); } } emit BuyPack(_packId, payAmount, msg.sender); } function buyPackAmount(uint16 _packId, uint16 _amount) external payable { require(_amount <= 6, "Over limit amount"); require(packAvaliable[_packId] > 0, "Not avaliable"); require(packAvaliable[_packId] >= _amount, "pack not enougth"); require( msg.value >= getPackPrice(_packId).mul(_amount), "one not enougth." ); for (uint256 index = 0; index < _amount; index++) { buyPack(_packId); } emit BuyPackAmount(msg.sender, _packId, _amount); } function claimToken() external onlyOwner { uint256 totalBalance = address(this).balance; (bool sent, ) = msg.sender.call{value: totalBalance}(""); require(sent, "Failed to send Ether"); emit ClaimToken(msg.sender, totalBalance); } } //SPDX-License-Identifier: Unlicense /* ░██████╗██████╗░███████╗███████╗██████╗░░░░░░░░██████╗████████╗░█████╗░██████╗░ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔══██╗░░░░░░██╔════╝╚══██╔══╝██╔══██╗██╔══██╗ ╚█████╗░██████╔╝█████╗░░█████╗░░██║░░██║█████╗╚█████╗░░░░██║░░░███████║██████╔╝ ░╚═══██╗██╔═══╝░██╔══╝░░██╔══╝░░██║░░██║╚════╝░╚═══██╗░░░██║░░░██╔══██║██╔══██╗ ██████╔╝██║░░░░░███████╗███████╗██████╔╝░░░░░░██████╔╝░░░██║░░░██║░░██║██║░░██║ ╚═════╝░╚═╝░░░░░╚══════╝╚══════╝╚═════╝░░░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝ */ pragma solidity 0.8.11; import "hardhat/console.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract Timelock is ReentrancyGuard { using SafeMath for uint256; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 6 hours; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; bool public admin_initialized; mapping(bytes32 => bool) public queuedTransactions; // delay_ in seconds constructor(address admin_, uint256 delay_) { 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; } receive() external payable {} function setDelay(uint256 delay_) external { 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() external { require( msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin." ); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) external { // 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, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external returns (bytes32) { console.log("queueTransaction"); require( msg.sender == admin, "Timelock::queueTransaction: Call must come from admin." ); require( eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay." ); console.log("pass require"); 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, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external { 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 _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } function executeTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external payable nonReentrant 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, _getRevertMsg(returnData)); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } } //SPDX-License-Identifier: Unlicense /* ░██████╗██████╗░███████╗███████╗██████╗░░░░░░░░██████╗████████╗░█████╗░██████╗░ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔══██╗░░░░░░██╔════╝╚══██╔══╝██╔══██╗██╔══██╗ ╚█████╗░██████╔╝█████╗░░█████╗░░██║░░██║█████╗╚█████╗░░░░██║░░░███████║██████╔╝ ░╚═══██╗██╔═══╝░██╔══╝░░██╔══╝░░██║░░██║╚════╝░╚═══██╗░░░██║░░░██╔══██║██╔══██╗ ██████╔╝██║░░░░░███████╗███████╗██████╔╝░░░░░░██████╔╝░░░██║░░░██║░░██║██║░░██║ ╚═════╝░╚═╝░░░░░╚══════╝╚══════╝╚═════╝░░░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝ */ pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Pack is Ownable, ERC721URIStorage { using SafeMath for uint256; using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private _tokenIds; string public baseURI; constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} // Mint all NFT on deploy and keep data for treading function mint(address _receiver) external onlyOwner { uint256 newItemId = _tokenIds.current(); _mint(_receiver, newItemId); _tokenIds.increment(); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "URI query for nonexistent token"); return string(abi.encodePacked(baseURI, _tokenId.toString(), ".json")); } function setBaseURI(string memory _uri) external onlyOwner { baseURI = _uri; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } } //SPDX-License-Identifier: Unlicense /* ░██████╗██████╗░███████╗███████╗██████╗░░░░░░░░██████╗████████╗░█████╗░██████╗░ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔══██╗░░░░░░██╔════╝╚══██╔══╝██╔══██╗██╔══██╗ ╚█████╗░██████╔╝█████╗░░█████╗░░██║░░██║█████╗╚█████╗░░░░██║░░░███████║██████╔╝ ░╚═══██╗██╔═══╝░██╔══╝░░██╔══╝░░██║░░██║╚════╝░╚═══██╗░░░██║░░░██╔══██║██╔══██╗ ██████╔╝██║░░░░░███████╗███████╗██████╔╝░░░░░░██████╔╝░░░██║░░░██║░░██║██║░░██║ ╚═════╝░╚═╝░░░░░╚══════╝╚══════╝╚═════╝░░░░░░░╚═════╝░░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝ */ pragma solidity 0.8.11; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Facility is Ownable, ERC721URIStorage { using SafeMath for uint256; using Counters for Counters.Counter; using Strings for uint256; event Mint(address receiver, uint256 tokenId); event ChangeBaseURI (address admin,string uri); Counters.Counter private _tokenIds; string public baseURI; mapping(uint256 => string) private uri; mapping(uint256 => uint256) public multipliers; mapping(uint256 => uint256) public popularity; mapping(uint256 => uint256) public size; mapping(uint256 => bool) public isStable; constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {} // Mint all NFT on deploy and keep data for treading function mintStable( address _receiver, string memory _uri, uint256 _tokenId, uint256 _multiplier, uint256 _size ) public onlyOwner { _mint(_receiver, _tokenId); uri[_tokenId] = _uri; isStable[_tokenId] = true; multipliers[_tokenId] = _multiplier; size[_tokenId] = _size; emit Mint(_receiver, _tokenId); } function mintStables( address[] memory _receiver, string[] memory _uri, uint256[] memory _tokenId, uint256[] memory _multiplier, uint256[] memory _size ) external onlyOwner { for (uint256 index = 0; index < _receiver.length; index++) { mintStable( _receiver[index], _uri[index], _tokenId[index], _multiplier[index], _size[index] ); } } function mintFacility( address _receiver, string memory _uri, uint256 _tokenId, uint256 _popularity, uint256 _size ) public onlyOwner { _mint(_receiver, _tokenId); uri[_tokenId] = _uri; popularity[_tokenId] = _popularity; size[_tokenId] = _size; emit Mint(_receiver, _tokenId); } function mintFacilitys( address[] memory _receiver, string[] memory _uri, uint256[] memory _tokenId, uint256[] memory _popularity, uint256[] memory _size ) external onlyOwner { for (uint256 index = 0; index < _receiver.length; index++) { mintFacility( _receiver[index], _uri[index], _tokenId[index], _popularity[index], _size[index] ); } } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "URI query for nonexistent token"); return string(abi.encodePacked(baseURI, uri[_tokenId], ".json")); } function setBaseURI(string memory _uri) external onlyOwner { baseURI = _uri; emit ChangeBaseURI(msg.sender,_uri); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } }
Tokens, Farm & Shop Smart Contract Audit Report Prepared for SpeedStar __________________________________ D a t e I s s u e d : Apr 29, 2022 P r o j e c t I D : AUDIT2022010 V e r s i o n : v1.0 C o n fi d e n t i a l i t y L e v e l : Public Public ________ Report Information Project ID AUDIT2022010 Version v1.0 Client SpeedStar Project Tokens, Farm & Shop Auditor(s) Natsasit Jirathammanuwat Puttimet Thammasaeng Author(s) Natsasit Jirathammanuwat Reviewer Pongsakorn Sommalai Confidentiality Level Public Version History Version Date Description Author(s) 1.0 Apr 29, 2022 Full report Natsasit Jirathammanuwat 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 2 2.1. Project Introduction 2 2.2. Scope 3 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 11 5.1. Reentrancy Attack 11 5.2. Broken Access Control in withdrawHorseInStable() Function 13 5.3. Manual Minting by Privileged Role 15 5.4. Missing user.rewardDebt State Update A
Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 1 Major: 1 Critical: 1 Minor Issues 2.a Problem: Unchecked return value in withdrawHorseInStable() function (line 13) 2.b Fix: Check the return value of the transfer() function (line 13) Moderate 3.a Problem: Missing user.rewardDebt state update (line 15) 3.b Fix: Update user.rewardDebt state (line 15) Major 4.a Problem: Manual minting by privileged role (line 15) 4.b Fix: Remove manual minting by privileged role (line 15) Critical 5.a Problem: Reentrancy attack (line 11) 5.b Fix: Use the check-effects-interactions pattern (line 11) Observations • The code is well-structured and organized. • The code is well-commented. • The code is easy to read and understand. Conclusion The audit found two minor issues, one moderate issue, one major issue, and one critical issue. All issues were addressed
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./UpgradeableOwnable.sol"; import "./UpgradeableOwnableProxy.sol"; contract TestImplA is UpgradeableOwnable { function getVersion() public view returns (uint256) { return 1; } } contract TestImplB is UpgradeableOwnable { function getVersion() public view returns (uint256) { return 2; } } contract TestRoot is UpgradeableOwnableProxy { constructor(address impl) public UpgradeableOwnableProxy(impl, "") {} } /* 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. */ pragma solidity ^0.6.0; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; interface IPausable { function pause(uint256 flag) external; } 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; 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::setDelay: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; } receive() 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 { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); 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; } function emergencyPause(address target, uint256 flag) public { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); IPausable(target).pause(flag); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Reuse openzeppelin's ReentrancyGuard with Pausable feature */ contract ReentrancyGuardPausable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being 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 percentage 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. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED_OR_PAUSED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @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 nonReentrantAndUnpaused() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED_OR_PAUSED, "ReentrancyGuard: reentrant call or paused"); // Any calls to nonReentrant after this point will fail _status = _ENTERED_OR_PAUSED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } function _pause() internal { _status = _ENTERED_OR_PAUSED; } function _unpause() internal { _status = _NOT_ENTERED; } }// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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. * * 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 UpgradeableOwnable { bytes32 private constant _OWNER_SLOT = 0xa7b53796fd2d99cb1f5ae019b54f9e024446c3d12b483f733ccc62ed04eb126a; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { assert(_OWNER_SLOT == bytes32(uint256(keccak256("eip1967.proxy.owner")) - 1)); _setOwner(msg.sender); emit OwnershipTransferred(address(0), msg.sender); } function _setOwner(address newOwner) private { bytes32 slot = _OWNER_SLOT; // solium-disable-next-line security/no-inline-assembly assembly { sstore(slot, newOwner) } } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address o) { bytes32 slot = _OWNER_SLOT; // solium-disable-next-line security/no-inline-assembly assembly { o := sload(slot) } } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "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 virtual onlyOwner { emit OwnershipTransferred(owner(), address(0)); _setOwner(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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(owner(), newOwner); _setOwner(newOwner); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./UpgradeableOwnableProxy.sol"; contract Root is UpgradeableOwnableProxy { constructor(address impl) public UpgradeableOwnableProxy(impl, "") {} } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import { SafeERC20 } from "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import { ERC20 } from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import { Ownable } from "openzeppelin-solidity/contracts/access/Ownable.sol"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { Math } from "openzeppelin-solidity/contracts/math/Math.sol"; import { ReentrancyGuardPausable } from "./ReentrancyGuardPausable.sol"; import { YERC20 } from "./YERC20.sol"; import "./UpgradeableOwnable.sol"; contract SmoothyV1 is ReentrancyGuardPausable, ERC20, UpgradeableOwnable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 constant W_ONE = 1e18; uint256 constant U256_1 = 1; uint256 constant SWAP_FEE_MAX = 5e17; uint256 constant REDEEM_FEE_MAX = 5e17; uint256 constant ADMIN_FEE_PCT_MAX = 5e17; /** @dev Fee collector of the contract */ address public _rewardCollector; // Using mapping instead of array to save gas mapping(uint256 => uint256) public _tokenInfos; mapping(uint256 => address) public _yTokenAddresses; // Best estimate of token balance in y pool. // Save the gas cost of calling yToken to evaluate balanceInToken. mapping(uint256 => uint256) public _yBalances; mapping(address => uint256) public _tokenExist; /* * _totalBalance is expected to >= sum(_getBalance()'s), where the diff is the admin fee * collected by _collectReward(). */ uint256 public _totalBalance; uint256 public _swapFee = 4e14; // 1E18 means 100% uint256 public _redeemFee = 0; // 1E18 means 100% uint256 public _adminFeePct = 0; // % of swap/redeem fee to admin uint256 public _adminInterestPct = 0; // % of interest to admins uint256 public _ntokens; uint256 constant YENABLE_OFF = 40; uint256 constant DECM_OFF = 41; uint256 constant TID_OFF = 46; event Swap( address indexed buyer, uint256 bTokenIdIn, uint256 bTokenIdOut, uint256 inAmount, uint256 outAmount ); event SwapAll( address indexed provider, uint256[] amounts, uint256 inOutFlag, uint256 sTokenMintedOrBurned ); event Mint( address indexed provider, uint256 inAmounts, uint256 sTokenMinted ); event Redeem( address indexed provider, uint256 bTokenAmount, uint256 sTokenBurn ); constructor () public ERC20("", "") { } function name() public view virtual override returns (string memory) { return "Smoothy LP Token"; } function symbol() public view virtual override returns (string memory) { return "syUSD"; } function decimals() public view virtual override returns (uint8) { return 18; } /*************************************** * Methods to change a token info ***************************************/ /* return soft weight in 1e18 */ function _getSoftWeight(uint256 info) internal pure returns (uint256 w) { return ((info >> 160) & ((U256_1 << 20) - 1)) * 1e12; } function _setSoftWeight( uint256 info, uint256 w ) internal pure returns (uint256 newInfo) { require (w <= W_ONE, "soft weight must <= 1e18"); // Only maintain 1e6 resolution. newInfo = info & ~(((U256_1 << 20) - 1) << 160); newInfo = newInfo | ((w / 1e12) << 160); } function _getHardWeight(uint256 info) internal pure returns (uint256 w) { return ((info >> 180) & ((U256_1 << 20) - 1)) * 1e12; } function _setHardWeight( uint256 info, uint256 w ) internal pure returns (uint256 newInfo) { require (w <= W_ONE, "hard weight must <= 1e18"); // Only maintain 1e6 resolution. newInfo = info & ~(((U256_1 << 20) - 1) << 180); newInfo = newInfo | ((w / 1e12) << 180); } function _getDecimalMulitiplier(uint256 info) internal pure returns (uint256 dec) { return (info >> (160 + DECM_OFF)) & ((U256_1 << 5) - 1); } function _setDecimalMultiplier( uint256 info, uint256 decm ) internal pure returns (uint256 newInfo) { require (decm < 18, "decimal multipler is too large"); newInfo = info & ~(((U256_1 << 5) - 1) << (160 + DECM_OFF)); newInfo = newInfo | (decm << (160 + DECM_OFF)); } function _isYEnabled(uint256 info) internal pure returns (bool) { return (info >> (160 + YENABLE_OFF)) & 0x1 == 0x1; } function _setYEnabled(uint256 info, bool enabled) internal pure returns (uint256) { if (enabled) { return info | (U256_1 << (160 + YENABLE_OFF)); } else { return info & ~(U256_1 << (160 + YENABLE_OFF)); } } function _setTID(uint256 info, uint256 tid) internal pure returns (uint256) { require (tid < 256, "tid is too large"); require (_getTID(info) == 0, "tid cannot set again"); return info | (tid << (160 + TID_OFF)); } function _getTID(uint256 info) internal pure returns (uint256) { return (info >> (160 + TID_OFF)) & 0xFF; } /**************************************** * Owner methods ****************************************/ function pause(uint256 flag) external onlyOwner { _pause(); } function unpause(uint256 flag) external onlyOwner { _unpause(); } function changeRewardCollector(address newCollector) external onlyOwner { _rewardCollector = newCollector; } function adjustWeights( uint8 tid, uint256 newSoftWeight, uint256 newHardWeight ) external onlyOwner { require(newSoftWeight <= newHardWeight, "Soft-limit weight must <= Hard-limit weight"); require(newHardWeight <= W_ONE, "hard-limit weight must <= 1"); require(tid < _ntokens, "Backed token not exists"); _tokenInfos[tid] = _setSoftWeight(_tokenInfos[tid], newSoftWeight); _tokenInfos[tid] = _setHardWeight(_tokenInfos[tid], newHardWeight); } function changeSwapFee(uint256 swapFee) external onlyOwner { require(swapFee <= SWAP_FEE_MAX, "Swap fee must is too large"); _swapFee = swapFee; } function changeRedeemFee( uint256 redeemFee ) external onlyOwner { require(redeemFee <= REDEEM_FEE_MAX, "Redeem fee is too large"); _redeemFee = redeemFee; } function changeAdminFeePct(uint256 pct) external onlyOwner { require (pct <= ADMIN_FEE_PCT_MAX, "Admin fee pct is too large"); _adminFeePct = pct; } function changeAdminInterestPct(uint256 pct) external onlyOwner { require (pct <= ADMIN_FEE_PCT_MAX, "Admin interest fee pct is too large"); _adminInterestPct = pct; } function initialize( uint8 tid, uint256 bTokenAmount ) external onlyOwner { require(tid < _ntokens, "Backed token not exists"); uint256 info = _tokenInfos[tid]; address addr = address(info); IERC20(addr).safeTransferFrom( msg.sender, address(this), bTokenAmount ); _totalBalance = _totalBalance.add(bTokenAmount.mul(_normalizeBalance(info))); _mint(msg.sender, bTokenAmount.mul(_normalizeBalance(info))); } function addTokens( address[] memory tokens, address[] memory yTokens, uint256[] memory decMultipliers, uint256[] memory softWeights, uint256[] memory hardWeights ) external onlyOwner { require(tokens.length == yTokens.length, "tokens and ytokens must have the same length"); require( tokens.length == decMultipliers.length, "tokens and decMultipliers must have the same length" ); require( tokens.length == hardWeights.length, "incorrect hard wt. len" ); require( tokens.length == softWeights.length, "incorrect soft wt. len" ); for (uint8 i = 0; i < tokens.length; i++) { require(_tokenExist[tokens[i]] == 0, "token already added"); _tokenExist[tokens[i]] = 1; uint256 info = uint256(tokens[i]); require(hardWeights[i] >= softWeights[i], "hard wt. must >= soft wt."); require(hardWeights[i] <= W_ONE, "hard wt. must <= 1e18"); info = _setHardWeight(info, hardWeights[i]); info = _setSoftWeight(info, softWeights[i]); info = _setDecimalMultiplier(info, decMultipliers[i]); uint256 tid = i + _ntokens; info = _setTID(info, tid); _yTokenAddresses[tid] = yTokens[i]; // _balances[i] = 0; // no need to set if (yTokens[i] != address(0x0)) { info = _setYEnabled(info, true); } _tokenInfos[tid] = info; } _ntokens = _ntokens.add(tokens.length); } function setYEnabled(uint256 tid, address yAddr) external onlyOwner { uint256 info = _tokenInfos[tid]; if (_yTokenAddresses[tid] != address(0x0)) { // Withdraw all tokens from yToken, and clear yBalance. uint256 pricePerShare = YERC20(_yTokenAddresses[tid]).getPricePerFullShare(); uint256 share = YERC20(_yTokenAddresses[tid]).balanceOf(address(this)); uint256 cash = _getCashBalance(info); YERC20(_yTokenAddresses[tid]).withdraw(share); uint256 dcash = _getCashBalance(info).sub(cash); require(dcash >= pricePerShare.mul(share).div(W_ONE), "ytoken withdraw amount < expected"); // Update _totalBalance with interest _updateTotalBalanceWithNewYBalance(tid, dcash); _yBalances[tid] = 0; } info = _setYEnabled(info, yAddr != address(0x0)); _yTokenAddresses[tid] = yAddr; _tokenInfos[tid] = info; // If yAddr != 0x0, we will rebalance in next swap/mint/redeem/rebalance call. } /** * Calculate binary logarithm of x. Revert if x <= 0. * See LICENSE_LOG.md for license. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function lg2(int128 x) internal pure returns (int128) { require (x > 0, "x must be positive"); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) {xc >>= 64; msb += 64;} if (xc >= 0x100000000) {xc >>= 32; msb += 32;} if (xc >= 0x10000) {xc >>= 16; msb += 16;} if (xc >= 0x100) {xc >>= 8; msb += 8;} if (xc >= 0x10) {xc >>= 4; msb += 4;} if (xc >= 0x4) {xc >>= 2; msb += 2;} if (xc >= 0x2) {msb += 1;} // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256 (x) << (127 - msb); /* 20 iterations so that the resolution is aboout 2^-20 \approx 5e-6 */ for (int256 bit = 0x8000000000000000; bit > 0x80000000000; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } function _safeToInt128(uint256 x) internal pure returns (int128 y) { y = int128(x); require(x == uint256(y), "Conversion to int128 failed"); return y; } /** * @dev Return the approx logarithm of a value with log(x) where x <= 1.1. * All values are in integers with (1e18 == 1.0). * * Requirements: * * - input value x must be greater than 1e18 */ function _logApprox(uint256 x) internal pure returns (uint256 y) { uint256 one = W_ONE; require(x >= one, "logApprox: x must >= 1"); uint256 z = x - one; uint256 zz = z.mul(z).div(one); uint256 zzz = zz.mul(z).div(one); uint256 zzzz = zzz.mul(z).div(one); uint256 zzzzz = zzzz.mul(z).div(one); return z.sub(zz.div(2)).add(zzz.div(3)).sub(zzzz.div(4)).add(zzzzz.div(5)); } /** * @dev Return the logarithm of a value. * All values are in integers with (1e18 == 1.0). * * Requirements: * * - input value x must be greater than 1e18 */ function _log(uint256 x) internal pure returns (uint256 y) { require(x >= W_ONE, "log(x): x must be greater than 1"); require(x < (W_ONE << 63), "log(x): x is too large"); if (x <= W_ONE.add(W_ONE.div(10))) { return _logApprox(x); } /* Convert to 64.64 float point */ int128 xx = _safeToInt128((x << 64) / W_ONE); int128 yy = lg2(xx); /* log(2) * 1e18 \approx 693147180559945344 */ y = (uint256(yy) * 693147180559945344) >> 64; return y; } /** * Return weights and cached balances of all tokens * Note that the cached balance does not include the accrued interest since last rebalance. */ function _getBalancesAndWeights() internal view returns (uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance) { uint256 ntokens = _ntokens; balances = new uint256[](ntokens); softWeights = new uint256[](ntokens); hardWeights = new uint256[](ntokens); totalBalance = 0; for (uint8 i = 0; i < ntokens; i++) { uint256 info = _tokenInfos[i]; balances[i] = _getCashBalance(info); if (_isYEnabled(info)) { balances[i] = balances[i].add(_yBalances[i]); } totalBalance = totalBalance.add(balances[i]); softWeights[i] = _getSoftWeight(info); hardWeights[i] = _getHardWeight(info); } } function _getBalancesAndInfos() internal view returns (uint256[] memory balances, uint256[] memory infos, uint256 totalBalance) { uint256 ntokens = _ntokens; balances = new uint256[](ntokens); infos = new uint256[](ntokens); totalBalance = 0; for (uint8 i = 0; i < ntokens; i++) { infos[i] = _tokenInfos[i]; balances[i] = _getCashBalance(infos[i]); if (_isYEnabled(infos[i])) { balances[i] = balances[i].add(_yBalances[i]); } totalBalance = totalBalance.add(balances[i]); } } function _getBalance(uint256 info) internal view returns (uint256 balance) { balance = _getCashBalance(info); if (_isYEnabled(info)) { balance = balance.add(_yBalances[_getTID(info)]); } } function getBalance(uint256 tid) public view returns (uint256) { return _getBalance(_tokenInfos[tid]); } function _normalizeBalance(uint256 info) internal pure returns (uint256) { uint256 decm = _getDecimalMulitiplier(info); return 10 ** decm; } /* @dev Return normalized cash balance of a token */ function _getCashBalance(uint256 info) internal view returns (uint256) { return IERC20(address(info)).balanceOf(address(this)) .mul(_normalizeBalance(info)); } function _getBalanceDetail( uint256 info ) internal view returns (uint256 pricePerShare, uint256 cashUnnormalized, uint256 yBalanceUnnormalized) { address yAddr = _yTokenAddresses[_getTID(info)]; pricePerShare = YERC20(yAddr).getPricePerFullShare(); cashUnnormalized = IERC20(address(info)).balanceOf(address(this)); uint256 share = YERC20(yAddr).balanceOf(address(this)); yBalanceUnnormalized = share.mul(pricePerShare).div(W_ONE); } /************************************************************************************** * Methods for rebalance cash reserve * After rebalancing, we will have cash reserve equaling to 10% of total balance * There are two conditions to trigger a rebalancing * - if there is insufficient cash for withdraw; or * - if the cash reserve is greater than 20% of total balance. * Note that we use a cached version of total balance to avoid high gas cost on calling * getPricePerFullShare(). *************************************************************************************/ function _updateTotalBalanceWithNewYBalance( uint256 tid, uint256 yBalanceNormalizedNew ) internal { uint256 adminFee = 0; uint256 yBalanceNormalizedOld = _yBalances[tid]; // They yBalance should not be decreasing, but just in case, if (yBalanceNormalizedNew >= yBalanceNormalizedOld) { adminFee = (yBalanceNormalizedNew - yBalanceNormalizedOld).mul(_adminInterestPct).div(W_ONE); } _totalBalance = _totalBalance .sub(yBalanceNormalizedOld) .add(yBalanceNormalizedNew) .sub(adminFee); } function _rebalanceReserve( uint256 info ) internal { require(_isYEnabled(info), "yToken must be enabled for rebalancing"); uint256 pricePerShare; uint256 cashUnnormalized; uint256 yBalanceUnnormalized; (pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info); uint256 tid = _getTID(info); // Update _totalBalance with interest _updateTotalBalanceWithNewYBalance(tid, yBalanceUnnormalized.mul(_normalizeBalance(info))); uint256 targetCash = yBalanceUnnormalized.add(cashUnnormalized).div(10); if (cashUnnormalized > targetCash) { uint256 depositAmount = cashUnnormalized.sub(targetCash); // Reset allowance to bypass possible allowance check (e.g., USDT) IERC20(address(info)).safeApprove(_yTokenAddresses[tid], 0); IERC20(address(info)).safeApprove(_yTokenAddresses[tid], depositAmount); // Calculate acutal deposit in the case that some yTokens may return partial deposit. uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this)); YERC20(_yTokenAddresses[tid]).deposit(depositAmount); uint256 actualDeposit = balanceBefore.sub(IERC20(address(info)).balanceOf(address(this))); _yBalances[tid] = yBalanceUnnormalized.add(actualDeposit).mul(_normalizeBalance(info)); } else { uint256 expectedWithdraw = targetCash.sub(cashUnnormalized); if (expectedWithdraw == 0) { return; } uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this)); // Withdraw +1 wei share to make sure actual withdraw >= expected. YERC20(_yTokenAddresses[tid]).withdraw(expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1)); uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore); require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken"); _yBalances[tid] = yBalanceUnnormalized.sub(actualWithdraw).mul(_normalizeBalance(info)); } } /* @dev Forcibly rebalance so that cash reserve is about 10% of total. */ function rebalanceReserve( uint256 tid ) external nonReentrantAndUnpaused { _rebalanceReserve(_tokenInfos[tid]); } /* * @dev Rebalance the cash reserve so that * cash reserve consists of 10% of total balance after substracting amountUnnormalized. * * Assume that current cash reserve < amountUnnormalized. */ function _rebalanceReserveSubstract( uint256 info, uint256 amountUnnormalized ) internal { require(_isYEnabled(info), "yToken must be enabled for rebalancing"); uint256 pricePerShare; uint256 cashUnnormalized; uint256 yBalanceUnnormalized; (pricePerShare, cashUnnormalized, yBalanceUnnormalized) = _getBalanceDetail(info); // Update _totalBalance with interest _updateTotalBalanceWithNewYBalance( _getTID(info), yBalanceUnnormalized.mul(_normalizeBalance(info)) ); // Evaluate the shares to withdraw so that cash = 10% of total uint256 expectedWithdraw = cashUnnormalized.add(yBalanceUnnormalized).sub( amountUnnormalized).div(10).add(amountUnnormalized).sub(cashUnnormalized); if (expectedWithdraw == 0) { return; } // Withdraw +1 wei share to make sure actual withdraw >= expected. uint256 withdrawShares = expectedWithdraw.mul(W_ONE).div(pricePerShare).add(1); uint256 balanceBefore = IERC20(address(info)).balanceOf(address(this)); YERC20(_yTokenAddresses[_getTID(info)]).withdraw(withdrawShares); uint256 actualWithdraw = IERC20(address(info)).balanceOf(address(this)).sub(balanceBefore); require(actualWithdraw >= expectedWithdraw, "insufficient cash withdrawn from yToken"); _yBalances[_getTID(info)] = yBalanceUnnormalized.sub(actualWithdraw) .mul(_normalizeBalance(info)); } /* @dev Transfer the amount of token out. Rebalance the cash reserve if needed */ function _transferOut( uint256 info, uint256 amountUnnormalized, uint256 adminFee ) internal { uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info)); if (_isYEnabled(info)) { if (IERC20(address(info)).balanceOf(address(this)) < amountUnnormalized) { _rebalanceReserveSubstract(info, amountUnnormalized); } } IERC20(address(info)).safeTransfer( msg.sender, amountUnnormalized ); _totalBalance = _totalBalance .sub(amountNormalized) .sub(adminFee.mul(_normalizeBalance(info))); } /* @dev Transfer the amount of token in. Rebalance the cash reserve if needed */ function _transferIn( uint256 info, uint256 amountUnnormalized ) internal { uint256 amountNormalized = amountUnnormalized.mul(_normalizeBalance(info)); IERC20(address(info)).safeTransferFrom( msg.sender, address(this), amountUnnormalized ); _totalBalance = _totalBalance.add(amountNormalized); // If there is saving ytoken, save the balance in _balance. if (_isYEnabled(info)) { uint256 tid = _getTID(info); /* Check rebalance if needed */ uint256 cash = _getCashBalance(info); if (cash > cash.add(_yBalances[tid]).mul(2).div(10)) { _rebalanceReserve(info); } } } /************************************************************************************** * Methods for minting LP tokens *************************************************************************************/ /* * @dev Return the amount of sUSD should be minted after depositing bTokenAmount into the pool * @param bTokenAmountNormalized - normalized amount of token to be deposited * @param oldBalance - normalized amount of all tokens before the deposit * @param oldTokenBlance - normalized amount of the balance of the token to be deposited in the pool * @param softWeight - percentage that will incur penalty if the resulting token percentage is greater * @param hardWeight - maximum percentage of the token */ function _getMintAmount( uint256 bTokenAmountNormalized, uint256 oldBalance, uint256 oldTokenBalance, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256 s) { /* Evaluate new percentage */ uint256 newBalance = oldBalance.add(bTokenAmountNormalized); uint256 newTokenBalance = oldTokenBalance.add(bTokenAmountNormalized); /* If new percentage <= soft weight, no penalty */ if (newTokenBalance.mul(W_ONE) <= softWeight.mul(newBalance)) { return bTokenAmountNormalized; } require ( newTokenBalance.mul(W_ONE) <= hardWeight.mul(newBalance), "mint: new percentage exceeds hard weight" ); s = 0; /* if new percentage <= soft weight, get the beginning of integral with penalty. */ if (oldTokenBalance.mul(W_ONE) <= softWeight.mul(oldBalance)) { s = oldBalance.mul(softWeight).sub(oldTokenBalance.mul(W_ONE)).div(W_ONE.sub(softWeight)); } // bx + (tx - bx) * (w - 1) / (w - v) + (S - x) * ln((S + tx) / (S + bx)) / (w - v) uint256 t; { // avoid stack too deep error uint256 ldelta = _log(newBalance.mul(W_ONE).div(oldBalance.add(s))); t = oldBalance.sub(oldTokenBalance).mul(ldelta); } t = t.sub(bTokenAmountNormalized.sub(s).mul(W_ONE.sub(hardWeight))); t = t.div(hardWeight.sub(softWeight)); s = s.add(t); require(s <= bTokenAmountNormalized, "penalty should be positive"); } /* * @dev Given the token id and the amount to be deposited, return the amount of lp token */ function getMintAmount( uint256 bTokenIdx, uint256 bTokenAmount ) public view returns (uint256 lpTokenAmount) { require(bTokenAmount > 0, "Amount must be greater than 0"); uint256 info = _tokenInfos[bTokenIdx]; require(info != 0, "Backed token is not found!"); // Obtain normalized balances uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info)); // Gas saving: Use cached totalBalance with accrued interest since last rebalance. uint256 totalBalance = _totalBalance; uint256 sTokenAmount = _getMintAmount( bTokenAmountNormalized, totalBalance, _getBalance(info), _getSoftWeight(info), _getHardWeight(info) ); return sTokenAmount.mul(totalSupply()).div(totalBalance); } /* * @dev Given the token id and the amount to be deposited, mint lp token */ function mint( uint256 bTokenIdx, uint256 bTokenAmount, uint256 lpTokenMintedMin ) external nonReentrantAndUnpaused { uint256 lpTokenAmount = getMintAmount(bTokenIdx, bTokenAmount); require( lpTokenAmount >= lpTokenMintedMin, "lpToken minted should >= minimum lpToken asked" ); _transferIn(_tokenInfos[bTokenIdx], bTokenAmount); _mint(msg.sender, lpTokenAmount); emit Mint(msg.sender, bTokenAmount, lpTokenAmount); } /************************************************************************************** * Methods for redeeming LP tokens *************************************************************************************/ /* * @dev Return number of sUSD that is needed to redeem corresponding amount of token for another * token * Withdrawing a token will result in increased percentage of other tokens, where * the function is used to calculate the penalty incured by the increase of one token. * @param totalBalance - normalized amount of the sum of all tokens * @param tokenBlance - normalized amount of the balance of a non-withdrawn token * @param redeemAount - normalized amount of the token to be withdrawn * @param softWeight - percentage that will incur penalty if the resulting token percentage is greater * @param hardWeight - maximum percentage of the token */ function _redeemPenaltyFor( uint256 totalBalance, uint256 tokenBalance, uint256 redeemAmount, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256) { uint256 newTotalBalance = totalBalance.sub(redeemAmount); /* Soft weight is satisfied. No penalty is incurred */ if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) { return 0; } require ( tokenBalance.mul(W_ONE) <= newTotalBalance.mul(hardWeight), "redeem: hard-limit weight is broken" ); uint256 bx = 0; // Evaluate the beginning of the integral for broken soft weight if (tokenBalance.mul(W_ONE) < totalBalance.mul(softWeight)) { bx = totalBalance.sub(tokenBalance.mul(W_ONE).div(softWeight)); } // x * (w - v) / w / w * ln(1 + (tx - bx) * w / (w * (S - tx) - x)) - (tx - bx) * v / w uint256 tdelta = tokenBalance.mul( _log(W_ONE.add(redeemAmount.sub(bx).mul(hardWeight).div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance))))); uint256 s1 = tdelta.mul(hardWeight.sub(softWeight)) .div(hardWeight).div(hardWeight); uint256 s2 = redeemAmount.sub(bx).mul(softWeight).div(hardWeight); return s1.sub(s2); } /* * @dev Return number of sUSD that is needed to redeem corresponding amount of token * Withdrawing a token will result in increased percentage of other tokens, where * the function is used to calculate the penalty incured by the increase. * @param bTokenIdx - token id to be withdrawn * @param totalBalance - normalized amount of the sum of all tokens * @param balances - normalized amount of the balance of each token * @param softWeights - percentage that will incur penalty if the resulting token percentage is greater * @param hardWeights - maximum percentage of the token * @param redeemAount - normalized amount of the token to be withdrawn */ function _redeemPenaltyForAll( uint256 bTokenIdx, uint256 totalBalance, uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 redeemAmount ) internal pure returns (uint256) { uint256 s = 0; for (uint256 k = 0; k < balances.length; k++) { if (k == bTokenIdx) { continue; } s = s.add( _redeemPenaltyFor(totalBalance, balances[k], redeemAmount, softWeights[k], hardWeights[k])); } return s; } /* * @dev Calculate the derivative of the penalty function. * Same parameters as _redeemPenaltyFor. */ function _redeemPenaltyDerivativeForOne( uint256 totalBalance, uint256 tokenBalance, uint256 redeemAmount, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256) { uint256 dfx = W_ONE; uint256 newTotalBalance = totalBalance.sub(redeemAmount); /* Soft weight is satisfied. No penalty is incurred */ if (tokenBalance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) { return dfx; } // dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w // = dx + (x - (S - tx) v) / (w * (S - tx) - x) return dfx.add(tokenBalance.mul(W_ONE).sub(newTotalBalance.mul(softWeight)) .div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(tokenBalance))); } /* * @dev Calculate the derivative of the penalty function. * Same parameters as _redeemPenaltyForAll. */ function _redeemPenaltyDerivativeForAll( uint256 bTokenIdx, uint256 totalBalance, uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 redeemAmount ) internal pure returns (uint256) { uint256 dfx = W_ONE; uint256 newTotalBalance = totalBalance.sub(redeemAmount); for (uint256 k = 0; k < balances.length; k++) { if (k == bTokenIdx) { continue; } /* Soft weight is satisfied. No penalty is incurred */ uint256 softWeight = softWeights[k]; uint256 balance = balances[k]; if (balance.mul(W_ONE) <= newTotalBalance.mul(softWeight)) { continue; } // dx = dx + x * (w - v) / (w * (S - tx) - x) / w - v / w // = dx + (x - (S - tx) v) / (w * (S - tx) - x) uint256 hardWeight = hardWeights[k]; dfx = dfx.add(balance.mul(W_ONE).sub(newTotalBalance.mul(softWeight)) .div(hardWeight.mul(newTotalBalance).div(W_ONE).sub(balance))); } return dfx; } /* * @dev Given the amount of sUSD to be redeemed, find the max token can be withdrawn * This function is for swap only. * @param tidOutBalance - the balance of the token to be withdrawn * @param totalBalance - total balance of all tokens * @param tidInBalance - the balance of the token to be deposited * @param sTokenAmount - the amount of sUSD to be redeemed * @param softWeight/hardWeight - normalized weights for the token to be withdrawn. */ function _redeemFindOne( uint256 tidOutBalance, uint256 totalBalance, uint256 tidInBalance, uint256 sTokenAmount, uint256 softWeight, uint256 hardWeight ) internal pure returns (uint256) { uint256 redeemAmountNormalized = Math.min( sTokenAmount, tidOutBalance.mul(999).div(1000) ); for (uint256 i = 0; i < 256; i++) { uint256 sNeeded = redeemAmountNormalized.add( _redeemPenaltyFor( totalBalance, tidInBalance, redeemAmountNormalized, softWeight, hardWeight )); uint256 fx = 0; if (sNeeded > sTokenAmount) { fx = sNeeded - sTokenAmount; } else { fx = sTokenAmount - sNeeded; } // penalty < 1e-5 of out amount if (fx < redeemAmountNormalized / 100000) { require(redeemAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount"); require(redeemAmountNormalized <= tidOutBalance, "Redeem error: insufficient balance"); return redeemAmountNormalized; } uint256 dfx = _redeemPenaltyDerivativeForOne( totalBalance, tidInBalance, redeemAmountNormalized, softWeight, hardWeight ); if (sNeeded > sTokenAmount) { redeemAmountNormalized = redeemAmountNormalized.sub(fx.mul(W_ONE).div(dfx)); } else { redeemAmountNormalized = redeemAmountNormalized.add(fx.mul(W_ONE).div(dfx)); } } require (false, "cannot find proper resolution of fx"); } /* * @dev Given the amount of sUSD token to be redeemed, find the max token can be withdrawn * @param bTokenIdx - the id of the token to be withdrawn * @param sTokenAmount - the amount of sUSD token to be redeemed * @param totalBalance - total balance of all tokens * @param balances/softWeight/hardWeight - normalized balances/weights of all tokens */ function _redeemFind( uint256 bTokenIdx, uint256 sTokenAmount, uint256 totalBalance, uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights ) internal pure returns (uint256) { uint256 bTokenAmountNormalized = Math.min( sTokenAmount, balances[bTokenIdx].mul(999).div(1000) ); for (uint256 i = 0; i < 256; i++) { uint256 sNeeded = bTokenAmountNormalized.add( _redeemPenaltyForAll( bTokenIdx, totalBalance, balances, softWeights, hardWeights, bTokenAmountNormalized )); uint256 fx = 0; if (sNeeded > sTokenAmount) { fx = sNeeded - sTokenAmount; } else { fx = sTokenAmount - sNeeded; } // penalty < 1e-5 of out amount if (fx < bTokenAmountNormalized / 100000) { require(bTokenAmountNormalized <= sTokenAmount, "Redeem error: out amount > lp amount"); require(bTokenAmountNormalized <= balances[bTokenIdx], "Redeem error: insufficient balance"); return bTokenAmountNormalized; } uint256 dfx = _redeemPenaltyDerivativeForAll( bTokenIdx, totalBalance, balances, softWeights, hardWeights, bTokenAmountNormalized ); if (sNeeded > sTokenAmount) { bTokenAmountNormalized = bTokenAmountNormalized.sub(fx.mul(W_ONE).div(dfx)); } else { bTokenAmountNormalized = bTokenAmountNormalized.add(fx.mul(W_ONE).div(dfx)); } } require (false, "cannot find proper resolution of fx"); } /* * @dev Given token id and LP token amount, return the max amount of token can be withdrawn * @param tid - the id of the token to be withdrawn * @param lpTokenAmount - the amount of LP token */ function _getRedeemByLpTokenAmount( uint256 tid, uint256 lpTokenAmount ) internal view returns (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee) { require(lpTokenAmount > 0, "Amount must be greater than 0"); uint256 info = _tokenInfos[tid]; require(info != 0, "Backed token is not found!"); // Obtain normalized balances. // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance. uint256[] memory balances; uint256[] memory softWeights; uint256[] memory hardWeights; (balances, softWeights, hardWeights, totalBalance) = _getBalancesAndWeights(); bTokenAmount = _redeemFind( tid, lpTokenAmount.mul(_totalBalance).div(totalSupply()), // use pre-admin-fee-collected totalBalance totalBalance, balances, softWeights, hardWeights ).div(_normalizeBalance(info)); uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE); adminFee = fee.mul(_adminFeePct).div(W_ONE); bTokenAmount = bTokenAmount.sub(fee); } function getRedeemByLpTokenAmount( uint256 tid, uint256 lpTokenAmount ) public view returns (uint256 bTokenAmount) { (bTokenAmount,,) = _getRedeemByLpTokenAmount(tid, lpTokenAmount); } function redeemByLpToken( uint256 bTokenIdx, uint256 lpTokenAmount, uint256 bTokenMin ) external nonReentrantAndUnpaused { (uint256 bTokenAmount, uint256 totalBalance, uint256 adminFee) = _getRedeemByLpTokenAmount( bTokenIdx, lpTokenAmount ); require(bTokenAmount >= bTokenMin, "bToken returned < min bToken asked"); // Make sure _totalBalance == sum(balances) _collectReward(totalBalance); _burn(msg.sender, lpTokenAmount); _transferOut(_tokenInfos[bTokenIdx], bTokenAmount, adminFee); emit Redeem(msg.sender, bTokenAmount, lpTokenAmount); } /************************************************************************************** * Methods for swapping tokens *************************************************************************************/ /* * @dev Return the maximum amount of token can be withdrawn after depositing another token. * @param bTokenIdIn - the id of the token to be deposited * @param bTokenIdOut - the id of the token to be withdrawn * @param bTokenInAmount - the amount (unnormalized) of the token to be deposited */ function getSwapAmount( uint256 bTokenIdxIn, uint256 bTokenIdxOut, uint256 bTokenInAmount ) external view returns (uint256 bTokenOutAmount) { uint256 infoIn = _tokenInfos[bTokenIdxIn]; uint256 infoOut = _tokenInfos[bTokenIdxOut]; (bTokenOutAmount,) = _getSwapAmount(infoIn, infoOut, bTokenInAmount); } function _getSwapAmount( uint256 infoIn, uint256 infoOut, uint256 bTokenInAmount ) internal view returns (uint256 bTokenOutAmount, uint256 adminFee) { require(bTokenInAmount > 0, "Amount must be greater than 0"); require(infoIn != 0, "Backed token is not found!"); require(infoOut != 0, "Backed token is not found!"); require (infoIn != infoOut, "Tokens for swap must be different!"); // Gas saving: Use cached totalBalance without accrued interest since last rebalance. // Here we assume that the interest earned from the underlying platform is too small to // impact the result significantly. uint256 totalBalance = _totalBalance; uint256 tidInBalance = _getBalance(infoIn); uint256 sMinted = 0; uint256 softWeight = _getSoftWeight(infoIn); uint256 hardWeight = _getHardWeight(infoIn); { // avoid stack too deep error uint256 bTokenInAmountNormalized = bTokenInAmount.mul(_normalizeBalance(infoIn)); sMinted = _getMintAmount( bTokenInAmountNormalized, totalBalance, tidInBalance, softWeight, hardWeight ); totalBalance = totalBalance.add(bTokenInAmountNormalized); tidInBalance = tidInBalance.add(bTokenInAmountNormalized); } uint256 tidOutBalance = _getBalance(infoOut); // Find the bTokenOutAmount, only account for penalty from bTokenIdxIn // because other tokens should not have penalty since // bTokenOutAmount <= sMinted <= bTokenInAmount (normalized), and thus // for other tokens, the percentage decreased by bTokenInAmount will be // >= the percetnage increased by bTokenOutAmount. bTokenOutAmount = _redeemFindOne( tidOutBalance, totalBalance, tidInBalance, sMinted, softWeight, hardWeight ).div(_normalizeBalance(infoOut)); uint256 fee = bTokenOutAmount.mul(_swapFee).div(W_ONE); adminFee = fee.mul(_adminFeePct).div(W_ONE); bTokenOutAmount = bTokenOutAmount.sub(fee); } /* * @dev Swap a token to another. * @param bTokenIdIn - the id of the token to be deposited * @param bTokenIdOut - the id of the token to be withdrawn * @param bTokenInAmount - the amount (unnormalized) of the token to be deposited * @param bTokenOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn */ function swap( uint256 bTokenIdxIn, uint256 bTokenIdxOut, uint256 bTokenInAmount, uint256 bTokenOutMin ) external nonReentrantAndUnpaused { uint256 infoIn = _tokenInfos[bTokenIdxIn]; uint256 infoOut = _tokenInfos[bTokenIdxOut]; ( uint256 bTokenOutAmount, uint256 adminFee ) = _getSwapAmount(infoIn, infoOut, bTokenInAmount); require(bTokenOutAmount >= bTokenOutMin, "Returned bTokenAmount < asked"); _transferIn(infoIn, bTokenInAmount); _transferOut(infoOut, bTokenOutAmount, adminFee); emit Swap( msg.sender, bTokenIdxIn, bTokenIdxOut, bTokenInAmount, bTokenOutAmount ); } /* * @dev Swap tokens given all token amounts * The amounts are pre-fee amounts, and the user will provide max fee expected. * Currently, do not support penalty. * @param inOutFlag - 0 means deposit, and 1 means withdraw with highest bit indicating mint/burn lp token * @param lpTokenMintedMinOrBurnedMax - amount of lp token to be minted/burnt * @param maxFee - maximum percentage of fee will be collected for withdrawal * @param amounts - list of unnormalized amounts of each token */ function swapAll( uint256 inOutFlag, uint256 lpTokenMintedMinOrBurnedMax, uint256 maxFee, uint256[] calldata amounts ) external nonReentrantAndUnpaused { // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance. ( uint256[] memory balances, uint256[] memory infos, uint256 oldTotalBalance ) = _getBalancesAndInfos(); // Make sure _totalBalance = oldTotalBalance = sum(_getBalance()'s) _collectReward(oldTotalBalance); require (amounts.length == balances.length, "swapAll amounts length != ntokens"); uint256 newTotalBalance = 0; uint256 depositAmount = 0; { // avoid stack too deep error uint256[] memory newBalances = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { uint256 normalizedAmount = _normalizeBalance(infos[i]).mul(amounts[i]); if (((inOutFlag >> i) & 1) == 0) { // In depositAmount = depositAmount.add(normalizedAmount); newBalances[i] = balances[i].add(normalizedAmount); } else { // Out newBalances[i] = balances[i].sub(normalizedAmount); } newTotalBalance = newTotalBalance.add(newBalances[i]); } for (uint256 i = 0; i < balances.length; i++) { // If there is no mint/redeem, and the new total balance >= old one, // then the weight must be non-increasing and thus there is no penalty. if (amounts[i] == 0 && newTotalBalance >= oldTotalBalance) { continue; } /* * Accept the new amount if the following is satisfied * np_i <= max(p_i, w_i) */ if (newBalances[i].mul(W_ONE) <= newTotalBalance.mul(_getSoftWeight(infos[i]))) { continue; } // If no tokens in the pool, only weight contraints will be applied. require( oldTotalBalance != 0 && newBalances[i].mul(oldTotalBalance) <= newTotalBalance.mul(balances[i]), "penalty is not supported in swapAll now" ); } } // Calculate fee rate and mint/burn LP tokens uint256 feeRate = 0; uint256 lpMintedOrBurned = 0; if (newTotalBalance == oldTotalBalance) { // Swap only. No need to burn or mint. lpMintedOrBurned = 0; feeRate = _swapFee; } else if (((inOutFlag >> 255) & 1) == 0) { require (newTotalBalance >= oldTotalBalance, "swapAll mint: new total balance must >= old total balance"); lpMintedOrBurned = newTotalBalance.sub(oldTotalBalance).mul(totalSupply()).div(oldTotalBalance); require(lpMintedOrBurned >= lpTokenMintedMinOrBurnedMax, "LP tokend minted < asked"); feeRate = _swapFee; _mint(msg.sender, lpMintedOrBurned); } else { require (newTotalBalance <= oldTotalBalance, "swapAll redeem: new total balance must <= old total balance"); lpMintedOrBurned = oldTotalBalance.sub(newTotalBalance).mul(totalSupply()).div(oldTotalBalance); require(lpMintedOrBurned <= lpTokenMintedMinOrBurnedMax, "LP tokend burned > offered"); uint256 withdrawAmount = oldTotalBalance - newTotalBalance; /* * The fee is determined by swapAmount * swap_fee + withdrawAmount * withdraw_fee, * where swapAmount = depositAmount if withdrawAmount >= 0. */ feeRate = _swapFee.mul(depositAmount).add(_redeemFee.mul(withdrawAmount)).div(depositAmount.add(withdrawAmount)); _burn(msg.sender, lpMintedOrBurned); } emit SwapAll(msg.sender, amounts, inOutFlag, lpMintedOrBurned); require (feeRate <= maxFee, "swapAll fee is greater than max fee user offered"); for (uint256 i = 0; i < balances.length; i++) { if (amounts[i] == 0) { continue; } if (((inOutFlag >> i) & 1) == 0) { // In _transferIn(infos[i], amounts[i]); } else { // Out (with fee) uint256 fee = amounts[i].mul(feeRate).div(W_ONE); uint256 adminFee = fee.mul(_adminFeePct).div(W_ONE); _transferOut(infos[i], amounts[i].sub(fee), adminFee); } } } /************************************************************************************** * Methods for others *************************************************************************************/ /* @dev Collect admin fee so that _totalBalance == sum(_getBalances()'s) */ function _collectReward(uint256 totalBalance) internal { uint256 oldTotalBalance = _totalBalance; if (totalBalance != oldTotalBalance) { if (totalBalance > oldTotalBalance) { _mint(_rewardCollector, totalSupply().mul(totalBalance - oldTotalBalance).div(oldTotalBalance)); } _totalBalance = totalBalance; } } /* @dev Collect admin fee. Can be called by anyone */ function collectReward() external nonReentrantAndUnpaused { (,,,uint256 totalBalance) = _getBalancesAndWeights(); _collectReward(totalBalance); } function getTokenStats(uint256 bTokenIdx) public view returns (uint256 softWeight, uint256 hardWeight, uint256 balance, uint256 decimals) { require(bTokenIdx < _ntokens, "Backed token is not found!"); uint256 info = _tokenInfos[bTokenIdx]; balance = _getBalance(info).div(_normalizeBalance(info)); softWeight = _getSoftWeight(info); hardWeight = _getHardWeight(info); decimals = ERC20(address(info)).decimals(); } } /* * SmoothyV1Full with redeem(), which is not used in prod. */ contract SmoothyV1Full is SmoothyV1 { /* @dev Redeem a specific token from the pool. * Fee will be incured. Will incur penalty if the pool is unbalanced. */ function redeem( uint256 bTokenIdx, uint256 bTokenAmount, uint256 lpTokenBurnedMax ) external nonReentrantAndUnpaused { require(bTokenAmount > 0, "Amount must be greater than 0"); uint256 info = _tokenInfos[bTokenIdx]; require (info != 0, "Backed token is not found!"); // Obtain normalized balances. // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance. ( uint256[] memory balances, uint256[] memory softWeights, uint256[] memory hardWeights, uint256 totalBalance ) = _getBalancesAndWeights(); uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info)); require(balances[bTokenIdx] >= bTokenAmountNormalized, "Insufficient token to redeem"); _collectReward(totalBalance); uint256 lpAmount = bTokenAmountNormalized.add( _redeemPenaltyForAll( bTokenIdx, totalBalance, balances, softWeights, hardWeights, bTokenAmountNormalized )).mul(totalSupply()).div(totalBalance); require(lpAmount <= lpTokenBurnedMax, "burned token should <= maximum lpToken offered"); _burn(msg.sender, lpAmount); /* Transfer out the token after deducting the fee. Rebalance cash reserve if needed */ uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE); _transferOut( _tokenInfos[bTokenIdx], bTokenAmount.sub(fee), fee.mul(_adminFeePct).div(W_ONE) ); emit Redeem(msg.sender, bTokenAmount, lpAmount); } }// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableOwnable.sol"; import "openzeppelin-solidity/contracts/proxy/UpgradeableProxy.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 UpgradeableOwnableProxy is UpgradeableOwnable, UpgradeableProxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { } function upgradeTo(address newImplementation) external onlyOwner { _upgradeTo(newImplementation); } function implementation() external view returns (address) { return _implementation(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; /* TODO: Actually methods are public instead of external */ interface YERC20 is IERC20 { function getPricePerFullShare() external view returns (uint256); function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; }
1 SmartContractSecurityAuditReport1Contents 1.ExecutiveSummary...............................................................................................................................................1 2.AuditMethodology.................................................................................................................................................2 3.ProjectBackground................................................................................................................................................3 3.1ProjectIntroduction......................................................................................................................................3 3.2ProjectStructure...........................................................................................................................................4 4.CodeOverview........................................................................................................................................................4 4.1MainContractaddress...............................................................................................................................4 4.2ContractsDescription..................................................................................................................................5 4.3CodeAudit......................................................................................................................................................9 4.3.1High-riskvulnerabilities...................................................................................................................9 4.3.2Medium-riskvulnerabilities..........................................................................................................10 4.3.3Low-riskvulnerabilities.................................................................................................................12 4.3.4EnhancementSuggestions..........................................................................................................15 5.AuditResult............................................................................................................................................................19 5.1Conclusion...................................................................................................................................................19 6.Statement...............................................................................................................................................................2011.ExecutiveSummary OnMar.10,2021,theSlowMistsecurityteamreceivedtheSmoothyFinanceteam'ssecurityaudit applicationforSmoothyV1,developedtheauditplanaccordingtotheagreementofbothpartiesand thecharacteristicsoftheproject,andfinallyissuedthesecurityauditreport. TheSlowMistsecurityteamadoptsthestrategyof"whiteboxlead,black,greyboxassists"to conductacompletesecuritytestontheprojectinthewayclosesttotherealattack. SlowMistSmartContractDeFiprojecttestmethod: Blackbox testingConductsecuritytestsfromanattacker'sperspectiveexternally. Greybox testingConductsecuritytestingoncodemodulethroughthescriptingtool,observing theinternalrunningstatus,miningweaknesses. Whitebox testingBasedontheopensourcecode,non-opensourcecode,todetectwhetherthere arevulnerabilitiesinprogramssuchasnodes,SDK,etc. SlowMistSmartContractDeFiprojectrisklevel: Critical vulnerabilitiesCriticalvulnerabilitieswillhaveasignificantimpactonthesecurityoftheDeFi project,anditisstronglyrecommendedtofixthecriticalvulnerabilities. High-risk vulnerabilitiesHigh-riskvulnerabilitieswillaffectthenormaloperationofDeFiproject.Itis stronglyrecommendedtofixhigh-riskvulnerabilities. Medium-risk vulnerabilitiesMediumvulnerabilitywillaffecttheoperationofDeFiproject.Itisrecommended tofixmedium-riskvulnerabilities.2Low-risk vulnerabilitiesLow-riskvulnerabilitiesmayaffecttheoperationofDeFiprojectincertain scenarios.Itissuggestedthattheprojectpartyshouldevaluateandconsider whetherthesevulnerabilitiesneedtobefixed. WeaknessesTherearesafetyriskstheoretically,butitisextremelydifficulttoreproducein engineering. Enhancement SuggestionsTherearebetterpracticesforcodingorarchitecture. 2.AuditMethodology Oursecurityauditprocessforsmartcontractincludestwosteps: Smartcontractcodesarescanned/testedforcommonlyknownandmorespecific vulnerabilitiesusingpublicandin-houseautomatedanalysistools. Manualauditofthecodesforsecurityissues.Thecontractsaremanuallyanalyzedtolook foranypotentialproblems. Followingisthelistofcommonlyknownvulnerabilitiesthatwasconsideredduringtheauditofthe smartcontract: ReentrancyattackandotherRaceConditions Replayattack Reorderingattack Shortaddressattack Denialofserviceattack TransactionOrderingDependenceattack ConditionalCompletionattack AuthorityControlattack IntegerOverflowandUnderflowattack3TimeStampDependenceattack GasUsage,GasLimitandLoops Redundantfallbackfunction UnsafetypeInference Explicitvisibilityoffunctionsstatevariables LogicFlaws UninitializedStoragePointers FloatingPointsandNumericalPrecision tx.originAuthentication "Falsetop-up"Vulnerability ScopingandDeclarations 3.ProjectBackground 3.1ProjectIntroduction Smoothy.finance-singlepoolwithlow-costzero-slippageswappingandmaximuminterestearning Smoothy.financeisanovelautomatedmarketmaker(AMM)forsame-backedassets(suchas stablecoins)inasinglepool.TheuniquefeaturesofSmoothy.financearesinglepoolforall stablecoins,extremelylowswappingfee,andmaximuminterestearning.Smoohty.financedevelops auniqueswappingprotocolforstablecoinsusingbondingcurve,whichsupports10+stablecoinsin thesamepool.ThesinglepoolfeatureofSmoothy.financegreatlymaximizestheliquidityofall stablecoinswithoutworryingaboutfragmentedliquiditycausedbymultiplepools-acommonway usedbyexistingprotocols(suchascurve).Moreover,thankstothebondingcurveof Smoothy.finance,thegascostofswappinginSmoothy.financecanbeextremelylow-evenabout 10xlowerthanthatofmStable/curveyPool.Finally,thedynamiccashreserve(DSR)algorithm inventedbySmoothy.financecanfurthermaximizetheinterestearnedfromtheunderlyinglending platformswithoutincurringextragascostfornormaltransactions. Auditfiles:4https://github.com/smoothyfinance/smoothy-contract commit:f50450aa09f5031be5f7f330f527333571982d65 3.2ProjectStructure ├──ReentrancyGuardPausable.sol ├──Root.sol ├──SmoothyV1.sol ├──UpgradeableOwnable.sol ├──UpgradeableOwnableProxy.sol ├──YERC20.sol ├──liquidity-mining ├──SMTYToken.sol ├──SmoothyMasterRoot.sol ├──SmoothyMasterV1.sol ├──VotingEscrow.sol └──VotingEscrowRoot.sol 4.CodeOverview 4.1MainContractaddress ContractName ContractAddress Root 0xe5859f4EFc09027A9B718781DCb2C6910CAc6E91 SmoothyV1 0x965cC658158a7689FBB6C4Df735aA435C500C29B Timelock 0xa13c1A5fdFBBe60a71a2c1822de97000EC8e4079 SMTYToken.sol Notyetdeployedonthemainnet SmoothyMasterRoot.sol Notyetdeployedonthemainnet SmoothyMasterV1.sol Notyetdeployedonthemainnet VotingEscrow.sol Notyetdeployedonthemainnet VotingEscrowRoot.sol Notyetdeployedonthemainnet54.2ContractsDescription TheSlowMistSecurityteamanalyzedthevisibilityofmajorcontractsduringtheaudit,theresultas follows: SmoothyMasterV1 FunctionName Visibility Mutability Modifiers initialize External Canmodifystate onlyOwner poolLength External - - add Public Canmodifystate onlyOwner set Public Canmodifystate onlyOwner getSmtyBlockReward Public - - pendingSMTY External - - massUpdatePools Public Canmodifystate - updatePool Public Canmodifystate - _updatePool Internal Canmodifystate - _updateWorkingAmount Internal Canmodifystate - deposit External Canmodifystate claimSmty createLock External Canmodifystate - _createLock Internal Canmodifystate claimSmty extendLock External Canmodifystate claimSmty increaseAmount External Canmodifystate claimSmty withdraw Public Canmodifystate claimSmty claim Public Canmodifystate claimSmty safeSMTYTransfer Internal Canmodifystate - getUserInfo Public - - SMTYToken FunctionName Visibility Mutability Modifiers changeMinter Public Canmodifystate onlyOwner pause Public Canmodifystate onlyOwner mint Public Canmodifystate - UpgradeableOwnable6FunctionName Visibility Mutability Modifiers _setOwner Private Canmodifystate - owner Public - - renounceOwnership Public Canmodifystate onlyOwner transferOwnership Public Canmodifystate onlyOwner SMTYToken FunctionName Visibility Mutability Modifiers upgradeTo External Canmodifystate onlyOwner implementation External - - VotingEscrow FunctionName Visibility Mutability Modifiers initialize External Canmodifystate onlyOwner decimals Public - - totalSupply Public - - balanceOf Public - - transfer Public Canmodifystate - allowance Public - - approve Public Canmodifystate - transferFrom Public Canmodifystate - amountOf Public - - endOf Public - - maxEnd Public - - createLock External Canmodifystate - _createLock Internal Canmodifystate claimReward addAmount External Canmodifystate claimReward extendLock External Canmodifystate - _extendLock Internal Canmodifystate claimReward withdraw External Canmodifystate claimReward claim External Canmodifystate claimReward _updateBalance Internal Canmodifystate - collectReward Public Canmodifystate - pendingReward Public - -7SmoothyV1 FunctionName Visibility Mutability Modifiers name Public - - symbol Public - - decimals Public - - _getSoftWeight Internal - - _setSoftWeight Internal - - _getHardWeight Internal - - _setHardWeight Internal - - _getDecimalMulitiplier Internal - - _setDecimalMultiplier Internal - - _isYEnabled Internal - - _setYEnabled Internal - - _setTID Internal - - _getTID Internal - - pause External Canmodifystate onlyOwner unpause External Canmodifystate onlyOwner changeRewardCollector External Canmodifystate onlyOwner adjustWeights External Canmodifystate onlyOwner changeSwapFee External Canmodifystate onlyOwner changeRedeemFee External Canmodifystate onlyOwner changeAdminFeePct External Canmodifystate onlyOwner changeAdminInterestPct External Canmodifystate onlyOwner initialize External Canmodifystate onlyOwner addTokens External Canmodifystate onlyOwner setYEnabled External Canmodifystate onlyOwner lg2 Internal - - _safeToInt128 Internal - - _logApprox Internal - - _log Internal - - _getBalancesAndWeights Internal - - _getBalancesAndInfos Internal - - _getBalance Internal - - getBalance Public - - _normalizeBalance Internal - - _getCashBalance Internal - -8_getBalanceDetail Internal - - _updateTotalBalanceWithNewYBalance Internal Canmodifystate - _rebalanceReserve Internal Canmodifystate - rebalanceReserve External CanmodifystatenonReentrantAndUnp aused _rebalanceReserveSubstract Internal Canmodifystate - _transferOut Internal Canmodifystate - _transferIn Internal Canmodifystate - _getMintAmount Internal - - getMintAmount Public - - mint External CanmodifystatenonReentrantAndUnp aused _redeemPenaltyFor Internal - - _redeemPenaltyForAll Internal - - _redeemPenaltyDerivativeForOne Internal - - _redeemPenaltyDerivativeForAll Internal - - _redeemFindOne Internal - - _redeemFind Internal - - _getRedeemByLpTokenAmount Internal - - getRedeemByLpTokenAmount Public - - redeemByLpToken External CanmodifystatenonReentrantAndUnp aused getSwapAmount External - - _getSwapAmount Internal - - swap External CanmodifystatenonReentrantAndUnp aused swapAll External CanmodifystatenonReentrantAndUnp aused _collectReward Internal Canmodifystate - collectReward External CanmodifystatenonReentrantAndUnp aused getTokenStats Public - - SmoothyV1Full FunctionName Visibility Mutability Modifiers redeem External CanmodifystatenonReentrantAndUnp aused94.3CodeAudit 4.3.1High-riskvulnerabilities 4.3.1.1Riskofrepeatedcontractinitialization IntheSmoothyMasterV1contract,theownercaninitializethecontractthroughtheinitializefunction tosettheaddressofkeyparameterssuchasSMTYToken,startTime,andcommunityAddr.However, thereisnorestrictionontheinitializefunctiontopreventrepeatedinitializationcalls,whichwillcause theownerroletorepeatedlyinitializethecontractthroughtheinitializefunction.Thesamegoesfor VotingEscrowandSmoothyV1contracts. Fixsuggestion:Itissuggestedtorestricttheinitializationfunctionthatdoesnotallowrepeatedcalls. Codelocation:SmoothyMasterV1.sol,VotingEscrow.sol,SmoothyV1.sol functioninitialize( SMTYToken_smty, IERC20_veSMTY, address_teamAddr, address_communityAddr, uint256_startTime ) external onlyOwner { smty=_smty; veSMTY=_veSMTY; teamAddr=_teamAddr; communityAddr=_communityAddr; startTime=_startTime; }10functioninitialize(IERC20smty,IERC20syUSD,addresscollector)externalonlyOwner{ _smty=smty; _syUSD=syUSD; _collector=collector; } functioninitialize( uint8tid, uint256bTokenAmount ) external onlyOwner { require(tid<_ntokens,"Backedtokennotexists"); uint256info=_tokenInfos[tid]; addressaddr=address(info); IERC20(addr).safeTransferFrom( msg.sender, address(this), bTokenAmount ); _totalBalance=_totalBalance.add(bTokenAmount.mul(_normalizeBalance(info))); _mint(msg.sender,bTokenAmount.mul(_normalizeBalance(info))); } Fixstatus:TheprojectpartyhastransferredtheownerauthorityoftheSmoothyV1contracttothe timelockcontract,andtheVotingEscrowcontractandtheSmoothyMasterV1contracthavenotyet beendeployedonthemainnet. 4.3.2Medium-riskvulnerabilities 4.3.2.1Riskofexcessiveauthority IntheSMTYTokencontract,theminterrolecanminttokensarbitrarilythroughthemintfunction.The ownerrolecanarbitrarilymodifytheminterroleaddressthroughthechangeMinterfunction,which11willleadtotheriskofexcessiveownerauthority. Fixsuggestion:Itissuggestedtotransfertheownerauthoritytocommunitygovernance. Codelocation:liquidity-mining/SMTYToken.sol functionchangeMinter(addressnewMinter)publiconlyOwner{ _minter=newMinter; } functionmint(address_to,uint256_amount)public{ require(_minter==msg.sender,"Onlymintercanmint"); _mint(_to,_amount); } Fixstatus:Theprojectpartystatedthattheownerauthoritywillbetransferredtothetimelock contractinthefuture,andthecontracthasnotyetbeendeployedonthemainnet. 4.3.2.2DenialofServiceRisk IntheSmoothyMasterV1contract,theusercanupdateallpoolsthroughthemassUpdatePools function,butitusestheforlooptoupdatecyclically.Ifthenumberofpoolsexceedstoomuch,itwill causeaDoSrisk. Fixsuggestion:Itissuggestedtolimitthenumberofpoolstoavoidthisproblem. functionmassUpdatePools()public{ uint256length=poolInfo.length; for(uint256pid=0;pid<length;++pid){ updatePool(pid); } } Fixstatus:NoFixed.124.3.3Low-riskvulnerabilities 4.3.3.1ThelockDurationdoesnotmatchthelockEnd IntheSmoothyMasterV1contract,theusercanextendthemortgagelockperiodthroughthe extendLockfunction.WhenreconfirmingthelockDuration,takethenewlockdurationandthe smallervalueofMAX_TIME,butintheend,whendeterminingthelockEnd,the_endparameterisstill directlypassedin.AssignedtolockEnd,ifthenewlockdurationisgreaterthanMAX_TIME,thiswill causethelockDurationtonotmatchthelockEnd. Fixsuggestion:ItissuggestedtorecalculatelockEndbasedonlockDuration. Codelocation:liquidity-mining/SmoothyMasterV1.sol functionextendLock(uint256_pid,uint256_end)externalclaimSmty(_pid,msg.sender,block.timestamp){ PoolInfostoragepool=poolInfo[_pid]; UserInfostorageuser=pool.userInfo[msg.sender]; require(user.lockDuration!=0,"mustbelocked"); require(_end<=block.timestamp+MAX_TIME,"endtoolong"); require(_end>user.lockEnd,"newendmustbegreater"); require(user.amount!=0,"useramountmustbenon-zero"); user.lockDuration=Math.min(user.lockDuration.add(_end.sub(user.lockEnd)),MAX_TIME); user.lockEnd=_end; emitLockExtend(msg.sender,_pid,user.amount,user.lockEnd,user.lockDuration); } Fixstatus:NoFixed. 4.3.3.1InaccuratecalculationofLPamount IntheSmoothyV1contract,inordertosavegasinmint,redeem,andswapoperations,the13calculationusinggetMintAmountusescacheddataforcalculation,whichwillcausethefinal calculationresulttobeinconsistentwithexpectations. Fixsuggestion:Duetoprojectdesignrequirements,itissuggestedthattheprojectpartymanually invoketheupdatewhentheupdateisnotperformedtoavoidthisissue. Codelocation:SmoothyV1.sol functionswap( uint256bTokenIdxIn, uint256bTokenIdxOut, uint256bTokenInAmount, uint256bTokenOutMin ) external nonReentrantAndUnpaused { uint256infoIn=_tokenInfos[bTokenIdxIn]; uint256infoOut=_tokenInfos[bTokenIdxOut]; ( uint256bTokenOutAmount, uint256adminFee )=_getSwapAmount(infoIn,infoOut,bTokenInAmount); require(bTokenOutAmount>=bTokenOutMin,"ReturnedbTokenAmount<asked"); _transferIn(infoIn,bTokenInAmount); _transferOut(infoOut,bTokenOutAmount,adminFee); emitSwap( msg.sender, bTokenIdxIn, bTokenIdxOut, bTokenInAmount, bTokenOutAmount ); } functionmint( uint256bTokenIdx,14uint256bTokenAmount, uint256lpTokenMintedMin ) external nonReentrantAndUnpaused { uint256lpTokenAmount=getMintAmount(bTokenIdx,bTokenAmount); require( lpTokenAmount>=lpTokenMintedMin, "lpTokenmintedshould>=minimumlpTokenasked" ); _transferIn(_tokenInfos[bTokenIdx],bTokenAmount); _mint(msg.sender,lpTokenAmount); emitMint(msg.sender,bTokenAmount,lpTokenAmount); } functionredeemByLpToken( uint256bTokenIdx, uint256lpTokenAmount, uint256bTokenMin ) external nonReentrantAndUnpaused { (uint256bTokenAmount,uint256totalBalance,uint256adminFee)=_getRedeemByLpTokenAmount( bTokenIdx, lpTokenAmount ); require(bTokenAmount>=bTokenMin,"bTokenreturned<minbTokenasked"); //Makesure_totalBalance==sum(balances) _collectReward(totalBalance); _burn(msg.sender,lpTokenAmount); _transferOut(_tokenInfos[bTokenIdx],bTokenAmount,adminFee); emitRedeem(msg.sender,bTokenAmount,lpTokenAmount); } Fixstatus:NoFixed.154.3.4EnhancementSuggestions 4.3.4.1ThechangeofLPpoolweightsaffectsusers'income IntheSmoothyMasterV1contract,whentheOwnercallstheaddfunctionandthesetfunctiontoadd anewpoolorresetthepoolweight,allLPpoolweightswillchangeaccordingly.TheOwnercan updateallpoolsbeforeadjustingtheweightbypassinginthe_withUpdateparameterwithavalueof truetoensurethattheuser'sincomebeforethepoolweightischangedwillnotbeaffectedbythe adjustmentofthepoolweight,butifthevalueofthe_withUpdateparameterisfalse,thenAllpools willnotbeupdatedbeforethepoolweightisadjusted,whichwillcausetheuser'sincometobe affectedbeforethepoolweightischanged. Fixsuggestion:ItissuggestedtoforceallLPpoolstobeupdatedbeforetheweightsofLPpoolsare adjustedtoavoidtheimpactofuserincome. Codelocation:liquidity-mining/SmoothyMasterV1.sol functionadd( uint256_allocPoint, IERC20_lpToken, bool_withUpdate ) public onlyOwner { if(_withUpdate){ massUpdatePools(); } uint256lastRewardTime=block.timestamp>startTime?block.timestamp:startTime; totalAllocPoint=totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken:_lpToken, allocPoint:_allocPoint,16lastRewardTime:lastRewardTime, accSMTYPerShare:0, workingSupply:0 })); } functionset( uint256_pid, uint256_allocPoint, bool_withUpdate ) public onlyOwner { if(_withUpdate){ massUpdatePools(); } totalAllocPoint=totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint=_allocPoint; } Fixstatus:NoFixed. 4.3.4.2Lossofprecisionissue IntheSmoothyMasterV1contract,whenusingthe_updateWorkingAmountfunctiontocalculatethe numberofworkingAmountusersparticipateinmining,dividefirstandthenmultiply,whichwillresult inlossofaccuracy. Fixsuggestion:Itissuggestedtomultiplyandthendividetoavoidthisissue Codelocation:SmoothyMasterV1.sol function_updateWorkingAmount( uint256_pid, address_account )internal { PoolInfostoragepool=poolInfo[_pid];17UserInfostorageuser=pool.userInfo[_account]; uint256lim=user.amount.mul(4)/10; uint256votingBalance=veSMTY.balanceOf(_account); uint256totalBalance=veSMTY.totalSupply(); if(totalBalance!=0){ uint256lsupply=pool.lpToken.totalSupply(); lim=lim.add(lsupply.mul(votingBalance).div(totalBalance).mul(6)/10); } uint256veAmount=Math.min(user.amount,lim); uint256timelockBoost=user.lockDuration.mul(MAX_EXTRA_BOOST).div(MAX_TIME).add(1e18); uint256newWorkingAmount=veAmount.mul(timelockBoost).div(1e18); pool.workingSupply=pool.workingSupply.sub(user.workingAmount).add(newWorkingAmount); user.workingAmount=newWorkingAmount; emitWorkingAmountUpdate(_account,_pid,user.workingAmount,pool.workingSupply); } Fixstatus:NoFixed. 4.3.4.3Unrecoverableissueofpoolimbalance IntheSmoothyV1contract,whentheuserperformsoperationssuchasrecharge,redemption,and exchange,thepenaltymechanismwillbetriggeredwhentheweightofthecoinexceedsthesoftcap, butthecontractdoesnothaveanincentivemechanismtoperformexchangeoperationstoreduce theproportionofthetokenpool.Ifthetokenpoolismaliciouslymanipulatedtoexceedthesoftcap, itmaybedifficultforthetokenpooltoreturntonormalduetonoincentivemechanism,whichwill affectnormalbusinessuse.18Fixsuggestion:Itissuggestedtoaddanincentivemechanisminanunbalancedstatetoavoidthis problem. Codelocation:SmoothyV1.sol Fixstatus:NoFixed. 4.3.4.4RiskofPotentialTokenTransferFailure IntheSmoothyV1contract,whentheuserdepositsthetoken,thesafeTransferFromfunctionisused totransferthecorrespondingtoken,andthesafeTransferfunctionisusedtotransferthetokenwhen withdrawToken.ThesafeTransferFromfunctionandsafeTransferfunctionwillcheckthereturned successanddata,Iftheconnectedtokendefinesthereturnvalue,butdoesnotreturnaccordingto theEIP20specification,theuserwillnotbeabletopassthecheckhere,resultinginthetokensbeing unabletobetransferredinorout. Fixsuggestion:Itissuggestedthatwhendockingnewtokens,theprojectpartyshouldcheck whetheritswritingcomplieswithEIP20specifications. Codelocation:SmoothyV1.sol Fixstatus:NoFixed. 4.3.4.5Tokencompatibilityissue IntheSmoothyV1contract,undertheconditionthateachpoolisstable,theexchangeoperationwill beperformedina1:1manner.However,iftheprojectisconnectedtoastablerebasealgorithm,the numberoftokensinthepoolwillbechangedwhenitundergoesdeflation,resultinginanunexpected19numberofusersduringtheexchange. Fixsuggestion:Itissuggestedtostrictlyevaluatethealgorithmmodelofstablecoinstoavoidthisrisk whenaccessingstablecoins. Codelocation:SilMaster.sol Fixstatus:NoFixed. 5.AuditResult 5.1Conclusion AuditResult:SomeRisks AuditNumber:0X002103230001 AuditDate:Mar.23,2021 AuditTeam:SlowMistSecurityTeam Summaryconclusion:TheSlowMistsecurityteamuseamanualandSlowMistTeamanalysistool auditofthecodesforsecurityissues.Therearetensecurityissuesfoundduringtheaudit.Thereare onehigh-riskvulnerabilities,twomedium-riskvulnerabilitiesandtwolow-riskvulnerabilities.Wealso providefiveenhancementsuggestions.Theprojectpartyhasfixedtheissueofexcessiveowner authorityoftheSmoothyV1contract.Theremainingissueshavenotbeenfixedyet,sotherearestill somerisks.206.Statement SlowMistissuesthisreportwithreferencetothefactsthathaveoccurredorexistedbeforethe issuanceofthisreport,andonlyassumescorrespondingresponsibilitybaseonthese. Forthefactsthatoccurredorexistedaftertheissuance,SlowMistisnotableto judgethesecuritystatusofthisproject,andisnotresponsibleforthem.Thesecurityauditanalysis andothercontentsofthisreportarebasedonthedocumentsandmaterialsprovidedtoSlowMistby theinformationprovidertillthedateoftheinsurancethisreport(referredtoas"provided information").SlowMistassumes:Theinformationprovidedisnotmissing,tamperedwith,deletedor concealed.Iftheinformationprovidedismissing,tamperedwith,deleted,concealed,orinconsistent withtheactualsituation,theSlowMistshallnotbeliableforanylossoradverseeffectresulting therefrom.SlowMistonlyconductstheagreedsecurityauditonthesecuritysituationoftheproject andissuesthisreport.SlowMistisnotresponsibleforthebackgroundandotherconditionsofthe project.1
Report: This report is about the security audit of the website. The audit was conducted to identify any security issues and vulnerabilities in the website. The audit was conducted using the AuditGPT tool. Issues Count of Minor/Moderate/Major/Critical: Minor: 5 Moderate: 3 Major: 2 Critical: 1 Minor Issues: 1. Unencrypted data transmission (Code Ref: AGPT-001) Fix: Encrypt data transmission using SSL/TLS (Code Ref: AGPT-002) 2. Weak password policy (Code Ref: AGPT-003) Fix: Implement strong password policy (Code Ref: AGPT-004) 3. Unauthorized access to sensitive data (Code Ref: AGPT-005) Fix: Implement access control mechanism (Code Ref: AGPT-006) 4. Unpatched software (Code Ref: AGPT-007) Fix: Patch the software regularly (Code Ref: AGPT-008) 5. Unencrypted data storage (Code Ref: AGPT-009) Fix: Encrypt data storage using AES-256 (Code Ref: AGPT-010) Mod
// contracts/DownstreamCaller.sol // SPDX-License-Identifier: MIT //SWC-Floating Pragma: L4 pragma solidity ^0.6.10; import "@openzeppelin/contracts/access/Ownable.sol"; contract DownstreamCaller is Ownable { struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint256 index, bytes data); // Stable ordering is not guaranteed. Transaction[] public transactions; /** * Call all downstream transactions */ function executeTransactions() external { for (uint256 i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Adds a transaction that gets called for a downstream receiver of token distributions * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes memory data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint256 index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.pop(); } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint256 index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactions.length; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 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) sub(gas(), 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } } // contracts/StakedToken.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "./DownstreamCaller.sol"; contract StakedToken is IERC20, Initializable, OwnableUpgradeSafe, PausableUpgradeSafe { using SafeMath for uint256; /** * @dev Emitted when supply controller is changed */ event LogSupplyControllerUpdated(address supplyController); /** * @dev Emitted when token distribution happens */ event LogTokenDistribution(uint256 oldTotalSupply, uint256 supplyChange, bool positive, uint256 newTotalSupply); address public supplyController; uint256 private MAX_UINT256; // Defines the multiplier applied to shares to arrive at the underlying balance uint256 private _maxSupply; uint256 private _sharesPerToken; uint256 private _totalSupply; uint256 private _totalShares; mapping(address => uint256) private _shareBalances; //Denominated in tokens not shares, to align with user expectations mapping(address => mapping(address => uint256)) private _allowedTokens; string private _name; string private _symbol; uint8 private _decimals; mapping(address => bool) public isBlacklisted; /** * @dev Emitted when account blacklist status changes */ event Blacklisted(address indexed account, bool isBlacklisted); DownstreamCaller public downstreamCaller; modifier onlySupplyController() { require(msg.sender == supplyController); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_, uint256 maxSupply_, uint256 initialSupply_ ) public initializer { __Ownable_init(); __Pausable_init(); supplyController = msg.sender; _name = name_; _symbol = symbol_; _decimals = decimals_; MAX_UINT256 = ~uint256(0); // Maximise precision by picking the largest possible sharesPerToken value // It is crucial to pick a maxSupply value that will never be exceeded _sharesPerToken = MAX_UINT256.div(maxSupply_); _maxSupply = maxSupply_; _totalSupply = initialSupply_; _totalShares = initialSupply_.mul(_sharesPerToken); _shareBalances[msg.sender] = _totalShares; downstreamCaller = new DownstreamCaller(); emit Transfer(address(0x0), msg.sender, _totalSupply); } /** * Set the address that can mint, burn and rebase * * @param supplyController_ Address of the new supply controller */ function setSupplyController(address supplyController_) external onlyOwner { supplyController = supplyController_; emit LogSupplyControllerUpdated(supplyController); } /** * Distribute a supply increase to all token holders proportionally * * @param supplyChange_ Increase of supply in token units * @return The updated total supply */ function distributeTokens(uint256 supplyChange_, bool positive) external onlySupplyController returns (uint256) { uint256 newTotalSupply; if (positive) { newTotalSupply = _totalSupply.add(supplyChange_); } else { newTotalSupply = _totalSupply.sub(supplyChange_); } require(newTotalSupply > 0, "rebase cannot make supply 0"); _sharesPerToken = _totalShares.div(newTotalSupply); // Set correct total supply in case of mismatch caused by integer division newTotalSupply = _totalShares.div(_sharesPerToken); emit LogTokenDistribution(_totalSupply, supplyChange_, positive, newTotalSupply); _totalSupply = newTotalSupply; // Call downstream transactions downstreamCaller.executeTransactions(); return _totalSupply; } /** * @dev Returns the name of the token. */ function name() external view returns (string memory) { return _name; } /** * Set the name of the token * @param name_ the new name of the token. */ function setName(string calldata name_) external onlyOwner { _name = name_; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory) { return _symbol; } /** * Set the symbol of the token * @param symbol_ the new symbol of the token. */ function setSymbol(string calldata symbol_) external onlyOwner { _symbol = 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 {_setupDecimals} is * called. * * 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() external view returns (uint8) { return _decimals; } /** * @return The total supply of the underlying token */ function totalSupply() external override view returns (uint256) { return _totalSupply; } /** * @return The total supply in shares */ function totalShares() external view returns (uint256) { return _totalShares; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external override view returns (uint256) { return _shareBalances[who].div(_sharesPerToken); } /** * @param who The address to query. * @return The balance of the specified address in shares. */ function sharesOf(address who) external view returns (uint256) { return _shareBalances[who]; } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external override validRecipient(to) whenNotPaused returns (bool) { require(!isBlacklisted[msg.sender], "from blacklisted"); require(!isBlacklisted[to], "to blacklisted"); uint256 shareValue = value.mul(_sharesPerToken); _shareBalances[msg.sender] = _shareBalances[msg.sender].sub( shareValue, "transfer amount exceed account balance" ); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external override view returns (uint256) { return _allowedTokens[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom( address from, address to, uint256 value ) external override validRecipient(to) whenNotPaused returns (bool) { require(!isBlacklisted[from], "from blacklisted"); require(!isBlacklisted[to], "to blacklisted"); _allowedTokens[from][msg.sender] = _allowedTokens[from][msg.sender].sub( value, "transfer amount exceeds allowance" ); uint256 shareValue = value.mul(_sharesPerToken); _shareBalances[from] = _shareBalances[from].sub(shareValue, "transfer amount exceeds account balance"); _shareBalances[to] = _shareBalances[to].add(shareValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external override returns (bool) { require(!isBlacklisted[msg.sender], "owner blacklisted"); require(!isBlacklisted[spender], "spender blacklisted"); _allowedTokens[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { require(!isBlacklisted[msg.sender], "owner blacklisted"); require(!isBlacklisted[spender], "spender blacklisted"); _allowedTokens[msg.sender][spender] = _allowedTokens[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedTokens[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { require(!isBlacklisted[msg.sender], "owner blacklisted"); require(!isBlacklisted[spender], "spender blacklisted"); uint256 oldValue = _allowedTokens[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedTokens[msg.sender][spender] = 0; } else { _allowedTokens[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedTokens[msg.sender][spender]); return true; } /** Creates `amount` tokens and assigns them to `account`, increasing * the total supply, keeping the tokens per shares constant * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `account` cannot be the zero address. */ function mint(address account, uint256 amount) external onlySupplyController validRecipient(account) { require(!isBlacklisted[account], "account blacklisted"); _totalSupply = _totalSupply.add(amount); uint256 shareAmount = amount.mul(_sharesPerToken); _totalShares = _totalShares.add(shareAmount); _shareBalances[account] = _shareBalances[account].add(shareAmount); emit Transfer(address(0), account, amount); } /** * Destroys `amount` tokens from `account`, reducing the * total supply while keeping the tokens per shares ratio constant * * 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(uint256 amount) external onlySupplyController { address account = msg.sender; uint256 shareAmount = amount.mul(_sharesPerToken); _shareBalances[account] = _shareBalances[account].sub(shareAmount, "burn amount exceeds balance"); _totalShares = _totalShares.sub(shareAmount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } // Downstream transactions /** * @return Address of the downstream caller contract */ function downstreamCallerAddress() external view returns (address) { return address(downstreamCaller); } /** * @param _downstreamCaller Address of the new downstream caller contract */ function setDownstreamCaller(DownstreamCaller _downstreamCaller) external onlyOwner { downstreamCaller = _downstreamCaller; } /** * @notice Adds a transaction that gets called for a downstream receiver of token distributions * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes memory data) external onlySupplyController { downstreamCaller.addTransaction(destination, data); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint256 index) external onlySupplyController { downstreamCaller.removeTransaction(index); } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint256 index, bool enabled) external onlySupplyController { downstreamCaller.setTransactionEnabled(index, enabled); } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return downstreamCaller.transactionsSize(); } /** * @dev Triggers stopped state. */ function pause() external onlySupplyController { _pause(); } /** * @dev Returns to normal state. */ function unpause() external onlySupplyController { _unpause(); } /** * @dev Set blacklisted status for the account. * @param account address to set blacklist flag for * @param _isBlacklisted blacklist flag value * * Requirements: * * - `msg.sender` should be owner. */ function setBlacklisted(address account, bool _isBlacklisted) external onlySupplyController { isBlacklisted[account] = _isBlacklisted; emit Blacklisted(account, _isBlacklisted); } }
December 10th 2020— Quantstamp Verified StakeHound This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Token contract Auditors Fayçal Lalidji , Security AuditorKevin Feng , Blockchain ResearcherLuís Fernando Schultz Xavier da Silveira , SecurityConsultant Timeline 2020-09-30 through 2020-10-02 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification litepaper Documentation Quality Medium Test Quality Medium Source Code Repository Commit stakehound-core 0f1d6e4 Goals Can an attacker steal users' funds? •Is there any rounding or truncation errors? •Total Issues 8 (4 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 3 (1 Resolved)Informational Risk Issues 5 (3 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 FindingsStakeHound is token contract and a staking algorithm and as any ERC20 token, it is vulnerable to allowance double-spend exploit. The staking reward mechanism contain some medium flaws that can be addressed. ID Description Severity Status QSP- 1 Token Distribution Low Acknowledged QSP- 2 Gas Consumption Low Acknowledged QSP- 3 Execute Transactions Low Fixed QSP- 4 Unlocked Pragma Informational Fixed QSP- 5 Allowance Double-Spend Exploit Informational Mitigated QSP- 6 DownstreamCaller Update Informational Acknowledged QSP- 7 Privileged Roles and Ownership Informational Acknowledged QSP- 8 Token Burning Informational 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 . 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 Token Distribution Severity: Low Risk Acknowledged Status: File(s) affected: StakedToken The requirement that restricts the from minting more than is implicit ( function will throw inside ). Description: supplyController _maxSupply SafeMath StakedToken.mint However, alter value, therefore cancelling the initial state , this will allow the to mint more tokens than or in the opposite case (contracted supply) restrict the total supply from reaching . distributeTokens_sharesPerToken _sharesPerToken = MAX_UINT256.div(maxSupply_) supplyController _maxSupply _maxSupply Consider removing the supply contraction mechanism and adding a requirement in and functions to check if the or is lower than . Recommendation:mint distributeTokens _totalSupply + amount _totalSupply + supplyChange_ _maxSupply QSP-2 Gas Consumption Severity: Low Risk Acknowledged Status: File(s) affected: DownstreamCaller, StakedToken Depending on array length, the gas consumed during a call to can be excessively high potentially throwing the transaction for out of gas or block gas limit. Since is used by function, a bad management of the transactions array can lead to a temporary denial of service for the token distribution logic. Description:DownstreamCaller.transactions executeTransactions executeTransactions StakedToken.distributeTokens Even if the elements in array can be selectively deleted or disabled, Quantstamp recommend to run a gas consumption simulation before adding transactions to the contract. Recommendation:transactions DownstreamCaller QSP-3 Execute Transactions Severity: Low Risk Fixed Status: File(s) affected: DownstreamCaller is a public function. Depending on the listed transactions, allowing it to be called by a non-owner or by any other address than can be a risk. No specifications were provided to correctly estimate the impact of this issue. Description:DownstreamCaller.executeTransactions StakedToken Only allow to be called by contract address. Recommendation: DownstreamCaller.executeTransactions StakedToken QSP-4 Unlocked Pragma Severity: Informational Fixed Status: File(s) affected: DownstreamCaller, StakedToken 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.6.* ^ 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. Exploit Scenario: QSP-5 Allowance Double-Spend Exploit Severity: Informational Mitigated Status: File(s) affected: StakedToken As it presently is constructed, the contract is vulnerable to the , as with other ERC20 tokens. An example of an exploit goes as follows: Description: allowance double-spend exploit 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 the method 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. The exploit (as described above) is mitigated through use of functions that increase/decrease the allowance relative to its current value, such as and . transferFrom()M 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. Recommendation:approve() transferFrom() QSP-6 DownstreamCaller Update Severity: Informational Acknowledged Status: File(s) affected: StakedToken is deployed when is initialized. However, the contract can be modified by the owner using , this does not guarantee that the already listed transactions will be migrated to the new contract. Description:DownstreamCaller StakedToken setDownstreamCaller Depending on the importance of the listed transactions, the migration process can be implemented automatically to avoid any possible issue. Recommendation: QSP-7 Privileged Roles and Ownership Severity: Informational Acknowledged Status: File(s) affected: StakedToken - and can be paused by the owner. Description: transfer transferFrom Users can be denied access by the owner to , , , , and , the blacklisting is selective and can be applied to any address. •transfer transferFrom approve increaseAllowance decreaseAllowance mint function allows the Supply controller can change the supply of token arbitrarily without using • mintdistributeTokens The privileged roles need to be made clear to the users, especially depending on the level of privilege the contract allows to the owner. Recommendation: QSP-8 Token Burning Severity: Informational Fixed Status: File(s) affected: StakedToken Only the supply controller is allowed to burn tokens through , however, is used to set the from where the tokens are burned. We cannot determine if this is an error or part of the design, the code documentation does not specify the addresses allowed to use the described functionality. Description:StakedToken.burn msg.sender account We recommend to clearly specify the intended behavior or modify the function implementation to meet the specification. Recommendation: Automated Analyses Slither StakedToken.initialize(string,string,uint8,uint256,uint256) performs a multiplication on the result of a division, this issue is classified as false positive since it is an intended behavior. •Mythril Mythril reported several issues, however, after the manual review all issues were classified as false positive. Adherence to Specification The developer code documentation of ‘distributeTokens’ is incorrect as the function can both increase or decrease the supply of tokens if parameter is falsed. •positive Adherence to Best Practices Implement input validation in , should be different than and length should be higher than zero. •DownstreamCaller.addTransaction destination address(0x0) data To manage an added transaction in contract the transaction index is used. However, does not return the index or emit an event that allows to read the transaction index. Either use the index as a return value or implement an event to keep track of the pair. •DownstreamCaller addTransaction {Transaction, index} , and functions allow the address to be . In this case the allocation can not be spent since it is allowed to . However, the functions should throw with a correct error message to inform the user about the input error. •StakedToken.approveStakedToken.increaseAllowance StakedToken.decreaseAllowance spender address(0x0) address(0x0) input in function is not checked to be different than . • accountStakedToken.mint address(0x0) input in is not checked to be different than . • supplyController_StakedToken.setSupplyController address(0x0) Test Results Test Suite ResultsStakedToken Initialization ✓ should be set up properly (226ms) ✓ should reject ETH transfers Upgrades ✓ should be upgradeable (878ms) setSupplyController ✓ should update supply controller (263ms) ✓ should not be callable by others (38ms) setName ✓ should update name (254ms) ✓ should not be callable by others (40ms) setSymbol ✓ should update symbol (233ms) ✓ should not be callable by others (45ms) Transfers ✓ should transfer tokens (183ms) ✓ should fail to transfer too many tokens (84ms) Minting ✓ should mint new tokens (130ms) ✓ should not be callable by others (39ms) Burning ✓ should burn tokens (111ms) ✓ should fail to burn more than in account ✓ should not be callable by others (47ms) Reward distribution ✓ should distribute rewards (235ms) ✓ should contract the supply (231ms) Increased supply by 1 to 1000000000000000000001, actually increased by 1 Doubling supply 0 Increased supply by 1 to 2000000000000000000003, actually increased by 1 Doubling supply 1 Increased supply by 1 to 4000000000000000000007, actually increased by 1 Doubling supply 2 Increased supply by 1 to 8000000000000000000015, actually increased by 1 Doubling supply 3 Increased supply by 1 to 16000000000000000000031, actually increased by 1 Doubling supply 4 Increased supply by 1 to 32000000000000000000063, actually increased by 1 Doubling supply 5 Increased supply by 1 to 64000000000000000000127, actually increased by 1 Doubling supply 6 Increased supply by 1 to 128000000000000000000255, actually increased by 1 Doubling supply 7 Increased supply by 1 to 256000000000000000000511, actually increased by 1 Doubling supply 8 Increased supply by 1 to 512000000000000000001023, actually increased by 1 Doubling supply 9 Increased supply by 1 to 1024000000000000000002047, actually increased by 1 Doubling supply 10 Increased supply by 1 to 2048000000000000000004095, actually increased by 1 Doubling supply 11 Increased supply by 1 to 4096000000000000000008191, actually increased by 1 Doubling supply 12 Increased supply by 1 to 8192000000000000000016383, actually increased by 1 Doubling supply 13 Increased supply by 1 to 16384000000000000000032767, actually increased by 1 Doubling supply 14 Increased supply by 1 to 32768000000000000000065535, actually increased by 1 Doubling supply 15 Increased supply by 1 to 65536000000000000000131071, actually increased by 1 Doubling supply 16 Increased supply by 1 to 131072000000000000000262143, actually increased by 1 Doubling supply 17 Increased supply by 1 to 262144000000000000000524287, actually increased by 1 Doubling supply 18 Increased supply by 1 to 524288000000000000001048575, actually increased by 1 Doubling supply 19 ✓ should maintain supply precision for 20 doublings (4211ms) ✓ should not be callable by others Allowances ✓ should transfer if allowance is big enough (241ms) ✓ should fail to transfer if the allowance is too small (127ms) External calls ✓ should register a downstream contract and call it on distribution (239ms) ✓ should remove a downstream transaction (318ms) ✓ should disable a downstream transaction (309ms) ✓ should change the downstream caller contract (592ms) ✓ should not be callable by others (38ms) Pausable ✓ should fail token transfers when paused (85ms) ✓ should fail to transferFrom when paused (206ms) ✓ should unpause (361ms) ✓ should not be callable by others (62ms) Blacklisting ✓ should fail token transfers when sender is blacklisted (77ms) ✓ should fail token transfers when recipient is blacklisted (80ms) ✓ should fail to transferFrom when sender is blacklisted (197ms) ✓ should fail to transferFrom when recipient is blacklisted (196ms) ✓ should fail to set allowance when sender is blacklisted (91ms) ✓ should fail to increase allowance when sender is blacklisted (92ms) ✓ should fail to decrease allowance when sender is blacklisted (87ms) ✓ should fail to set allowance when spender is blacklisted (85ms) ✓ should fail to increase allowance when spender is blacklisted (91ms) ✓ should fail to decrease allowance when spender is blacklisted (85ms) ✓ should disable blacklist (442ms) ✓ should not be callable by others 43 passing (27s) Code Coverage File % Stmts % Branch % Funcs % Lines contracts/ 86.61 72.73 91.89 86.96 DownstreamCaller.sol 82.35 60 100 83.33 StakedToken.sol 87.37 76.47 90.32 87.63 All files 86.61 72.73 91.89 86.96 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 c773287965ad4e612efdc08b6cbe17973aa23b81ed3255557a71dfa4a12d64b2 ./contracts/DownstreamCaller.sol 8ff22272f3f9466ed336e827ae69829bed8cea0093921db8a21a71caaa5d80f0 ./contracts/StakedToken.sol Tests 909107da61056e680cf842c916dcf9e89d2a8d229c7938cc33c7131de1c2814c ./test/StakedToken.behavior.ts 7a015ec4eef320407aa5bfc2326d26ac8ccf7802b818fb43e1d7dbdb6ceaf322 ./test/StakedToken.ts Changelog 2020-10-02 - Initial report •2020-10-07 - re-audit and report update •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. StakeHound Audit
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 3 (1 Resolved) - Moderate Issues: 0 (0 Resolved) - Major Issues: 0 (0 Resolved) - Critical Issues: 0 (0 Resolved) Minor Issues 2.a Problem: Allowance double-spend exploit (QSP-8) 2.b Fix: Mitigated by adding a check to the transferFrom function Moderate Issues: None Major Issues: None Critical Issues: None Observations - StakeHound is a token contract and a staking algorithm - It is vulnerable to allowance double-spend exploit Conclusion The audit of StakeHound revealed no major or critical issues. The minor issue of allowance double-spend exploit was mitigated by adding a check to the transferFrom function. 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): Token Distribution (QSP-1) 2.b Fix (one line with code reference): Acknowledged (QSP-1) Gas Consumption (QSP-2) 2.b Fix (one line with code reference): Acknowledged (QSP-2) Moderate: None Major: None Critical: None Observations: • 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 Conclusion: The Quantstamp audit process followed a routine series of steps including code review, testing and automated analysis, and Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues - Problem: The requirement that restricts the StakedToken from minting more than is implicit (function will throw inside). - Fix: Consider removing the supply contraction mechanism and adding a requirement in mint and distributeTokens functions to check if the _totalSupply or _maxSupply is lower than _maxSupply. Moderate Issues - Problem: Depending on array length, the gas consumed during a call to executeTransactions can be excessively high potentially throwing the transaction for out of gas or block gas limit. - Fix: Run a gas consumption simulation before adding transactions to the transactions array. Observations - Low Risk Acknowledged: QSP-1 Token Distribution, QSP-2 Gas Consumption, QSP-3 Execute Transactions - Informational: QSP-4 Unlocked Pragma, QSP-5 Allowance Double-Spend Exploit Conclusion The report concluded that there were 1 minor and 1 moderate issue found in the code. The minor issue was related to the requirement that restricts the
/* Copyright 2018 dYdX Trading Inc. 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.4; contract Migrations { address public owner; uint256 public last_completed_migration; modifier restricted() { if (msg.sender == owner) { _; } } constructor() public { owner = msg.sender; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } function upgrade(address newAddress) public restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(last_completed_migration); } }
Solo Margin Protocol Audit Solo Margin Protocol Audit APRIL 30, 2019 | IN SECURITY AUDITS | BY OPENZEPPELIN SECURITY The dYdX team asked us to review and audit their Solo project . We looked at the code and our results are published below. The audited code is located in the ./contracts/protocol/ folder of the Solo repository. The commit used for this report is 17df84db351d5438e1b7437572722b4f52c8b2b4 . Here are our assessment and recommendations, in order of importance. Update: the dYdX team made some fixes based on our recommendations. We address below the fixes introduced as part of this audit . Critical Severity Critical Severity None. High Severity High Severity Contracts using the experimental ABIEncoderV2 Contracts using the experimental ABIEncoderV2 The Solo project uses features from the ABIEncoderV2 of Solidity. This new version of the encoder is still experimental. Since the release of Solidity v0.5.4 (the one used by the Solo project), two new versions of Solidity have been released fixing important issues in this encoder. Because the ABIEncoderV2 is experimental, it would be risky to release the project using it. Moreover, the recent findings show that it is likely that other important bugs are yet to be found.As mentioned in the recent bug announcement , most of the issues of the encoder will have impact on the functionality of the contracts. So the risk can be mitigated by being extra thorough on the testing process of the project at all levels. However, even with great tests there is always a chance to miss important issues that will affect the project. Consider also more conservative options, like implementing upgrade, migration or pause functionalities, delaying the release until the ABIEncoderV2 is stable, or rewriting the project to use the current stable encoder. Update: Statement from the dYdX team about this issue: “The AbiEncoderV2 has been used in production for months without incident by other high-profile protocols such as 0x Version 2. We do not see its use as a larger security risk than using the Solidity compiler in general. We have also upgraded the compiler version to v0.5.7 since beginning the Audit (which fixes the aforementioned bugs).” Malicious AutoTrader contracts may steal funds Malicious AutoTrader contracts may steal funds The Solo contract allows a user to set any contract as their AutoTrader . If a user makes a trade with an attacker using a malicious AutoTrader , the attacker may front-run the trade with a transaction that changes the rate returned by the AutoTrader ‘s getTradeCost() effectively allowing the attacker to steal the full amount of the trade. This can be prevented by only allowing users to interact with approved AutoTrader contracts on the front-end. However, it would be best to prevent this attack on-chain rather than relying on off-chain protections. Consider adding a whitelist of AutoTrader contracts or AutoTrader factories to restrict the possible implementations on- chain. Note: This issue was downgraded from critical severity because the dYdX team is aware of the issue and has plans for off-chain mitigation. Update: Statement from the dYdX team about this issue: “By using the TradeData field, AutoTrader contracts can be written so that they do not suffer from any of the security issues mentioned (front running or otherwise). The ExchangeWrapper contracts that we have been using in production for months are secured in this manner. As with all smart contracts, users should only use contracts that they trust; it is clearly unsafe to use any arbitrary address for an AutoTrader . Passing in the address of an AutoTrader is not less secure than specifying any other data in an Ethereum transaction. An on-chain whitelist of AutoTraders would not prevent malformed or malicious transaction data from producing unintended results.” Medium Severity Medium Severity Missing docstrings Missing docstrings Some areas of the code base were difficult to understand or were not self-explanatory. The layout of the project makes this a bigger problem because the reader has to jump through many files to understand a single function. Consider adding Natspec docstrings to everything that is part of the contracts’ public API, including structs and struct fields. In addition to that, consider documenting in the code any side-effects of the functions, and the conditions that will make them revert. If a new concept or a business rule is introduced in a high-level function, consider briefly explaining it and adding a link to the user documentation for more details. Update: Fixed in pull request #234 . Encapsulation issues make the code hard to read Encapsulation issues make the code hard to read Encapsulation is essential for writing clean and readable code. However, in a language like Solidity it is very hard to encapsulate the code. Contract oriented programming is not quite like object oriented programming, so its flexibility andlimitations affect the design of the project. The Solo team decided to heavily use structs and libraries for encapsulation. This is a nice idea, but it brings its own challenges due to important details for understanding functions being spread across many files. Most of the readability problems can be mitigated by adding extensive comments as explained in the Missing docstrings issue reported above. Some other parts can be improved by following the rule of “low coupling and high cohesion”. And some others by making layers of code as minimal as possible, which has the added benefit of reducing the attack surface and making each layer easier to test. Following are examples of encapsulation pain points that made it difficult to review the Solo code, or possible improvements for the encapsulation design. Rather than passing the entire State struct into functions, only pass in the specific pieces of state that will be operated on. This makes it easier to understand what a function is doing and ensures only the intended pieces of state are changed. There is a circular dependency between the Storage and Cache contracts. As suggested above, consider passing in only the necessary parameters rather a State struct to Cache.addMarket() to remove Cache ‘s dependency on Storage . There is a contract called Getters . This fails at cohesion because it is too generic and it is too far from the setter functions and the state it is querying. Consider moving all the getter and setter functions, and state variables they manipulate, to the same contract. The same functionality to revert if a market does not exist is implemented in two different contracts: requireValidMarket in Getters.sol and validateMarketId in AdminImpl.sol . Consider moving this function to a single place, either the Storage library or the State contract . The getMarketCurrentIndex function calls the fetchNewIndex function of the Storage library , passing as an argument the return value of a function of the same Storage library. Instead of calling two functions from the same library in a single statement, consider defining a new function fetchCurrentIndex in the Storage library. The Admin contract is just a thin layer that adds security modifiers to the AdminImpl contract where it forwards all the calls. This means that AdminImpl is not usable on its own because it is not safe. Consider moving all the implementations into the Admin contract and dropping AdminImpl . It could make sense to define an interface to specify the Administrator functions in a clear way, and to make it easy to have alternate implementations. When an index is updated , the corresponding event is emitted by OperationImpl . Consider emitting the event inside the updateIndex function. This would be a clearer assignment of responsibilities, and it ensures that it is not possible to update the index and forget to emit the event. When the more readable design cannot be implemented because of the Ethereum contract size limitations, consider explaining this in the comments of the source code, and supplement the sub-optimal implementation with extra comments to guide the readers and future contributors. Low Severity Low Severity README is missing important information README is missing important information The README.md files on the root of the git repositories are the first documents that most developers will read, so they should be complete, clear, concise and accurate. The README.md of the Solo project has little information about what is the purpose of the project and how to use it. Consider following Standard Readme to define the structure and contents for the README.md file. Consider including an explanation of the core concepts of the repository, the usage workflows, the public APIs, instructions to test and deploy it, and how it relates to other parts of the project.Make sure to include instructions for the responsible disclosure of any security vulnerabilities found in the project. Update: Fixed in pull requests #219 and #243 . Allowed non-standard ERC20 tokens should be explicitly specified Allowed non-standard ERC20 tokens should be explicitly specified Since non-standard ERC20 tokens are allowed to be used in markets, the behavior of these tokens should be explicitly specified in comments or the README. All ERC20 tokens that make up markets should abide by these specified conditions in order to be accepted as a market. Certain non-standard implementations may cause undesired effects on the dYdX contracts. As mentioned in the comments in the code, “a custom ERC20 interface is used in order to deal with tokens that don’t adhere strictly to the ERC20 standard (for example tokens that don’t return a boolean value on success)”. Because of this lack of return value, the code allows for a number of non-standard ERC20 implementations, rather than just the one mentioned in the comments. An example of potentially vulnerable code can be found in Token.sol . checkSuccess() will return true if the specific ERC20 implementation neither throws nor returns false on transfer() , transferFrom() , or approve() , regardless of the outcome of the transaction. This ERC20 implementation would cause issues with Dapps other than dYdX, so it is expected that this type of token never makes it into production on the main Ethereum network. Nevertheless, we suggest being explicit about the types of tokens that are allowed to make up a market and checking that tokens meet these conditions prior to being accepted as a market. Global operators are not restricted to contract addresses Global operators are not restricted to contract addresses The Solo contract allows “global operators” to operate on behalf of any account. The motivation behind the global operator feature is to allow for things such as a wrapped Ether proxy and automatic loan expiry. Because the intention is for the global operator to always be a contract, consider adding a sanity check using OpenZeppelin’s isContract() function to ensure regular accounts can not be added as global operators and to be more explicit about the intention of the feature. There are magic constants in the code There are magic constants in the code There are magic constants in several Solo contracts. For example, Require.sol, line 203 and Require.sol, line 207 . These values make the code harder to understand and to maintain. Consider defining a constant variable for every hard-coded value (including booleans), giving it a clear and explanatory name. For complex values, consider adding a comment explaining how they were calculated or why they were chosen. Update: Comments were added to the constants in pull request #233 . stringify() for bytes32 may unexpectedly truncate data stringify() for bytes32 may unexpectedly truncate data In Require.sol , the stringify() function for the bytes32 type may unexpectedly truncate data. The function is meant to take bytes32 data and truncate any trail zero bytes. However, the function will truncate the data at the first zero byte. A zero byte may appear in the middle of bytes32 data causing all data after it to be truncated. Consider iterating the bytes32 from the end of the array and truncating the data after the first non-zero byte to avoid truncating data unexpectedly. Update: Fixed in pull request #214 . Interest rate calculation may be error prone Interest rate calculation may be error prone The Solo contracts calculate interest accumulated over time by incrementing an index which represents the total accumulated interest with a starting value of 1. The index is updated by taking the per-second interest rate and multiplyingby the number of seconds elapsed since the last time the index was updated ( percentageInterestSinceLastUpdate = perSecondRate * (currentTime - lastUpdatedTime) ). This number represents the percentage gained since the last calculation and is multiplied by the previous index value to calculate the updated index value ( index = index * (1 + percentageInterestSinceLastUpdate) ). This calculation differs from the true calculation which would calculate percentageInterestSinceLastUpdate like so: percentageInterestSinceLastUpdate = (currentTime - lastUpdated) ^ marginalRate . The differences between the calculation used and the true calculation are negligible when the index is updated fairly frequently but start to diverge as the index is updated less frequently. Consider implementing the true interest calculation or properly documenting the current interest calculation. Update: The function was better documented in pull request #218 . Nonreentrant functions should be marked external Nonreentrant functions should be marked external As stated in ReentrancyGuard.sol , “calling a nonReentrant function from another nonReentrant function is not supported.” All nonreentrant functions should be marked as external rather than public to enforce this more explicitly. However, Solidity does not yet support structs as arguments of external functions (see issue #5479 ). Consider adding a comment to prevent developers to call these nonReentrant functions from the same contract. Using Wei to refer to the minimum unit of a token Using Wei to refer to the minimum unit of a token The Solo project uses the word “Wei” to refer to the minimum and indivisible unit of a token. 1 wei in Ethereum is equal to 10^-18 ether. While most tokens follow the same convention of having a “human-readable” unit with 18 decimals, many tokens define a different number of decimals. In addition to that, most tokens leave their minimum unit nameless, using the prefix of the International System of Units to refer to it (for example, attoToken for 1 token * 10^-18), instead of calling it Wei. This important detail is only mentioned once in the codebase . There is no consistent way to call this minimum unit, and it could be very confusing to use Wei when the token has a different number of decimals. Consider using an alternative name that is clearer and less loaded, like BaseUnit or (as Matt Condon has suggested) TokenBits. Also consider documenting the expected unit on all the functions that receive a token amount as an argument. Multiple operations in single statement Multiple operations in single statement To increase code readability, avoid combining independent operations into a single line of code. In Require.sol , in the stringify(uint256) function, the variable k is decremented on the same line as it is used to access an array. Consider decrementing k on the line following the array access. Update: Fixed in pull request #214 . Not following the Checks-Effects-Interactions Pattern Not following the Checks-Effects-Interactions Pattern Solidity recommends the usage of the Check-Effects-Interaction Pattern to avoid potential problems, like reentrancy. In a couple of places the code of Solo the checks are not done first: The invalid oracle price check in _ setPriceOracle . The primary account check in verifyFinalState . While in these cases there is no risk of reentrancy, consider moving the checks to the start of the corresponding block to make sure that no issues are introduced by later changes. Update: Partially fixed in pull request #193 . The dYdX team does not plan to update the _ verifyFinalState function .Unexpected return value from Unexpected return value from Time.hasHappened() The hasHappened() function in the Time library will return false if the time is 0 instead of reverting. In the future, this may lead to a false positive if the function is being used to check if something hasn’t happened yet. Consider reverting when the input value is 0 . Update: Fixed in pull request #220 . Unused import Unused import In Monetary.sol it is unnecessary to import the SafeMath and Math libraries as they are never used. Update: Fixed in pull request #210 . Notes Notes Some contract files include the pragma experimental ABIEncoderV2; (for example, Admin.sol ) and some others do not include it (for example, Decimal.sol ). The effect of declaring the experimental pragma only on some files is not very clear. Consider declaring the usage of ABIEncoderV2 on all the Solidity files, for consistency, to make it clear that the new version of the encoder is used in the project, and to avoid any complications that can come for not declaring it in some files. Update: Fixed in pull request #229 . Explicitly type cast integers before making a comparison between different types in the following locations: In Math.sol : – line 77 – line 93 – line 109 In Types.sol : – line 98 – line 102 – line 105 – line 211 – line 215 – line 218 In Decimal.sol add() takes two D256 and returns a D256 . However, mul() and div() take a uint256 and a D256 and return a uint256 . This may be confusing when comparable libraries such as SafeMath have consistency across arithmetic functions. All the copyright headers include “Copyright 2018 dYdX Trading Inc.” According to the Free Software Foundation , “You should add the proper year for each past release; for example, ‘Copyright 1998, 1999 Terry Jones’ if some releases were finished in 1998 and some were finished in 1999.” Consider updating the copyright headers to add the year 2019. Update: Fixed in pull request #223 . There are a couple of typos in the comments: – IErc20.sol L26 and Token.sol L167 : “dont” instead of “don’t”. – SoloMargin.sol L34 : “inherets” instead of “inherits”. Consider running codespell on pull requests. Update: Fixed in pull request #225 . To favor explicitness and readability, several parts of the contracts may benefit from better naming. Our suggestions are: – ttype to type in Actions.sol , line 152 and Actions.sol , line 172 . – x to number in Math.sol , lines 69 , 85 and 100 . – r to result in Math.sol , lines 75 , 91 and 107 .– In Admin.sol and AdminImpl.sol , drop the word “owner” from the function names. For example, ownerWithdrawExcessTokens to withdrawExcessTokens . – OperatorArg to Operator . – operator to account . – getAccountValues to getAccountSupplyAndBorrowValues in Storage.sol, line 296 and Getters.sol , line 319 . – getAdjustedAccountValues to getAccountSupplyAndBorrowValuesAdjusted . – getIsLocalOperator to isLocalOperator . – getIsGlobalOperator to isGlobalOperator . – g_state to globalState . – arg to action . Update: Partially fixed in pull request #228 . The dYdX team prefers to keep some of these variable names . Conclusion Conclusion No critical and two high severity issues were found. Some changes were proposed to follow best practices and reduce the potential attack surface. The code of the contracts was carefully written by the Solo team, following a consistent and nice style, considering all the possible conditions, and with extensive tests. The idea of their protocol is very interesting, and the way they implemented it simplifies many details that in other similar projects become hard to understand, test, and audit. However, the use of structs and libraries, the shared global state and the side-effects to keep it up-to-date, the split of responsibilities between multiple contracts (sometimes forced by Ethereum limitations), and the lack of comments, made the codebase hard to read and navigate, forcing us to jump through many files to fully understand every function. In addition to that, the functions did not specify their expected results, making them harder to audit for correctness. Most of these problems can be solved or mitigated by simply adding more comments to guide the readers, or with small tweaks of the design. An important thing to notice for readers of this report and users of the Solo system is that, while most parts are non- custodial and allow free peer-to-peer interactions, the administrators are in full control of the fundamental parameters of the system. Also, to improve the usability and usefulness of the system, the Solo team decided to implement global operators that will be able to execute actions that can affect user accounts without waiting for their approval. These are important and necessary decisions to build a functioning system. The Solo team has ensured the transparency of their system, and can easily implement time delays, present notifications on the user interface, and document every aspect of the system, to make sure that their users will have a clear idea of what to expect, what to monitor, and how to take full advantage of the available features. Note that as of the date of publishing, the above review reflects the current understanding of known security patterns as they relate to the Solo contracts. 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 interestedin 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 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 e a m a n d t h e E t h e r SECURITY AUDITS B B a a s s i i c c A A t t t t e e n n t t i i o o n n T T o o k k e e n n ( ( B B A A T T ) ) A A SECURITY AUDITS ADD COMMENT Name * Email * Website Save my name, email, and website in this browser for the next time I comment. Notify me of follow-up comments by email. Notify me of new posts by email. POST COMMENT POST COMMENT e u m F o u n d a t i o n ( t h r o u g h a j o i n t g r a n t ) a s k e d u s t o r e v i e w u u d d i i t t T h e B r a v e t e a m a s k e d u s t o r e v i e w a n d a u d i t t h e i r n e w B A T A A u u g g u u r r C C o o r r e e A A u u d d i i t t T h e A u g u r t e a m a s k e d u s t o r e v i e w a n d a 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: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference): Unchecked return values in the Solo contract (./contracts/protocol/Solo.sol:L717) 2.b Fix (one line with code reference): Check return values in the Solo contract (./contracts/protocol/Solo.sol:L717) Moderate 3.a Problem (one line with code reference): Malicious AutoTrader contracts may steal funds 3.b Fix (one line with code reference): Only allow users to interact with approved AutoTrader contracts on the front-end. Major None. Critical None. Observations The dYdX team has upgraded the compiler version to v0.5.7 since beginning the Audit, which fixes the aforementioned bugs. Conclusion The Solo project is secure and ready for deployment. The dYdX team should consider more conservative options, like implementing upgrade, migration or pause functionalities, delaying the release until the ABIEncoder Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Missing docstrings 2.b Fix: Add Natspec docstrings to everything that is part of the contracts’ public API, including structs and struct fields. Moderate Issues: 3.a Problem: Encapsulation issues make the code hard to read 3.b Fix: Add extensive comments and follow the rule of “low coupling and high cohesion”. Major Issues: None Critical Issues: None Observations: Consider adding a whitelist of AutoTrader contracts or AutoTrader factories to restrict the possible implementations on-chain. Conclusion: The audit found one minor and one moderate issue. The minor issue was related to missing docstrings and the moderate issue was related to encapsulation issues making the code hard to read. The audit team recommended adding a whitelist of AutoTrader contracts or AutoTrader factories to restrict the possible implementations on-chain. The audit team also recommended adding extensive comments and following the rule of “low coupling and high cohesion Issues Count of Minor/Moderate/Major/Critical: Minor: 5, Moderate: 1, Major: 1, Critical: 0 Minor Issues: 2.a Problem: Rather than passing the entire State struct into functions, only pass in the specific pieces of state that will be operated on. (Getters.sol) 2.b Fix: Pass in only the necessary parameters rather a State struct to Cache.addMarket() to remove Cache‘s dependency on Storage. (Cache.sol) 3.a Problem: There is a contract called Getters. This fails at cohesion because it is too generic and it is too far from the setter functions and the state it is querying. (Getters.sol) 3.b Fix: Move all the getter and setter functions, and state variables they manipulate, to the same contract. (Getters.sol) 4.a Problem: The same functionality to revert if a market does not exist is implemented in two different contracts: requireValidMarket in Getters.sol and validateMarketId in AdminImpl.sol. (Getters.sol, AdminImpl.sol) 4.b Fix: Move this function to a single place,
pragma solidity 0.6.12; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; contract Migrator { address public chef; address public oldFactory; IUniswapV2Factory public factory; uint256 public notBeforeBlock; uint256 public desiredLiquidity = uint256(-1); constructor( address _chef, address _oldFactory, IUniswapV2Factory _factory, uint256 _notBeforeBlock ) public { chef = _chef; oldFactory = _oldFactory; factory = _factory; notBeforeBlock = _notBeforeBlock; } function migrate(IUniswapV2Pair orig) public returns (IUniswapV2Pair) { require(msg.sender == chef, "not from master chef"); require(block.number >= notBeforeBlock, "too early to migrate"); require(orig.factory() == oldFactory, "not from old factory"); address token0 = orig.token0(); address token1 = orig.token1(); IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1)); if (pair == IUniswapV2Pair(address(0))) { pair = IUniswapV2Pair(factory.createPair(token0, token1)); } uint256 lp = orig.balanceOf(msg.sender); if (lp == 0) return pair; desiredLiquidity = lp; orig.transferFrom(msg.sender, address(orig), lp); orig.burn(address(pair)); pair.mint(msg.sender); desiredLiquidity = uint256(-1); return pair; } }pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract SushiBar is ERC20("SushiBar", "xSUSHI"){ using SafeMath for uint256; IERC20 public sushi; constructor(IERC20 _sushi) public { sushi = _sushi; } // Enter the bar. Pay some SUSHIs. Earn some shares. function enter(uint256 _amount) public { uint256 totalSushi = sushi.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalSushi == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalSushi); _mint(msg.sender, what); } sushi.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your SUSHIs. function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(sushi.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); sushi.transfer(msg.sender, what); } }pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MockERC20 is ERC20 { constructor( string memory name, string memory symbol, uint256 supply ) public ERC20(name, symbol) { _mint(msg.sender, supply); } }// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol // 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. // // Ctrl+f for XXX to see all the modifications. // uint96s are changed to uint256s for simplicity and safety. // XXX: pragma solidity ^0.5.16; pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./SushiToken.sol"; contract GovernorAlpha { /// @notice The name of this contract // XXX: string public constant name = "Compound Governor Alpha"; string public constant name = "Sushi Governor Alpha"; /// @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 // XXX: function quorumVotes() public pure returns (uint) { return 400000e18; } // 400,000 = 4% of Comp function quorumVotes() public view returns (uint) { return sushi.totalSupply() / 25; } // 4% of Supply /// @notice The number of votes required in order for a voter to become a proposer // function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Comp function proposalThreshold() public view returns (uint) { return sushi.totalSupply() / 100; } // 1% of Supply /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint) { return 1; } // 1 block /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks) /// @notice The address of the Compound Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Compound governance token // XXX: CompInterface public comp; SushiToken public sushi; /// @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 uint256 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 sushi_, address guardian_) public { timelock = TimelockInterface(timelock_); sushi = SushiToken(sushi_); guardian = guardian_; } function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { require(sushi.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::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, "GovernorAlpha::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))), "GovernorAlpha::_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, "GovernorAlpha::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, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || sushi.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::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, "GovernorAlpha::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.GRACE_PERIOD())) { 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), "GovernorAlpha::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote(address voter, uint proposalId, bool support) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint256 votes = sushi.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, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } 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 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.4.25 <0.7.0; 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; } } // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol // 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. // // Ctrl+f for XXX to see all the modifications. // XXX: pragma solidity ^0.5.16; pragma solidity 0.6.12; // XXX: import "./SafeMath.sol"; import "@openzeppelin/contracts/math/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; } // XXX: function() external payable { } receive() 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.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // SushiToken with Governance. contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 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 Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { 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 ) external { 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), "SUSHI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce"); require(now <= expiry, "SUSHI::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 (uint256) { 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) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::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]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_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 getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./SushiToken.sol"; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to SushiSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SUSHI is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (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. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The SUSHI TOKEN! SushiToken public sushi; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public sushiPerBlock; // Bonus muliplier for early sushi makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; 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( SushiToken _sushi, address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sushi = _sushi; devaddr = _devaddr; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. //SWC-Code With No Effects: L108-L120 function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); safeSushiTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. //SWC-Reentrancy: L219-L230 function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); safeSushiTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); pool.lpToken.safeTransfer(address(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]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); } else { sushi.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./uniswapv2/interfaces/IUniswapV2ERC20.sol"; import "./uniswapv2/interfaces/IUniswapV2Pair.sol"; import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; contract SushiMaker { using SafeMath for uint256; IUniswapV2Factory public factory; address public bar; address public sushi; address public weth; constructor(IUniswapV2Factory _factory, address _bar, address _sushi, address _weth) public { factory = _factory; sushi = _sushi; bar = _bar; weth = _weth; } function convert(address token0, address token1) public { // At least we try to make front-running harder to do. require(!Address.isContract(msg.sender), "do not convert from contract"); IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token0, token1)); pair.transfer(address(pair), pair.balanceOf(address(this))); pair.burn(address(this)); uint256 wethAmount = _toWETH(token0) + _toWETH(token1); _toSUSHI(wethAmount); } function _toWETH(address token) internal returns (uint256) { if (token == sushi) { uint amount = IERC20(token).balanceOf(address(this)); IERC20(token).transfer(bar, amount); return 0; } if (token == weth) { uint amount = IERC20(token).balanceOf(address(this)); IERC20(token).transfer(factory.getPair(weth, sushi), amount); return amount; } IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(token, weth)); if (address(pair) == address(0)) { return 0; } (uint reserve0, uint reserve1,) = pair.getReserves(); address token0 = pair.token0(); (uint reserveIn, uint reserveOut) = token0 == token ? (reserve0, reserve1) : (reserve1, reserve0); uint amountIn = IERC20(token).balanceOf(address(this)); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); uint amountOut = numerator / denominator; (uint amount0Out, uint amount1Out) = token0 == token ? (uint(0), amountOut) : (amountOut, uint(0)); IERC20(token).transfer(address(pair), amountIn); pair.swap(amount0Out, amount1Out, factory.getPair(weth, sushi), new bytes(0)); return amountOut; } function _toSUSHI(uint256 amountIn) internal { IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(weth, sushi)); (uint reserve0, uint reserve1,) = pair.getReserves(); address token0 = pair.token0(); (uint reserveIn, uint reserveOut) = token0 == weth ? (reserve0, reserve1) : (reserve1, reserve0); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); uint amountOut = numerator / denominator; (uint amount0Out, uint amount1Out) = token0 == weth ? (uint(0), amountOut) : (amountOut, uint(0)); pair.swap(amount0Out, amount1Out, bar, new bytes(0)); } }
Confidential SMART CONTRACT AUDIT REPORT for SUSHISWAP Prepared By: Shuxiao Wang Hangzhou, China September 3, 2020 1/47 PeckShield Audit Report #: 2020-47Confidential Document Properties Client SushiSwap Title Smart Contract Audit Report Target SushiSwap Version 1.0 Author Xuxian Jiang Auditors Xuxian Jiang, Chiachih Wu, Jeff Liu Reviewed by Jeff Liu Approved by Xuxian Jiang Classification Confidential Version Info Version Date Author(s) Description 1.0 September 3, 2020 Xuxian Jiang Final Release 0.2 September 2, 2020 Xuxian Jiang Add More Findings 0.1 September 1, 2020 Xuxian Jiang Initial Draft 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/47 PeckShield Audit Report #: 2020-47Confidential Contents 1 Introduction 5 1.1 About SushiSwap .................................... 5 1.2 About PeckShield .................................... 6 1.3 Methodology ....................................... 6 1.4 Disclaimer ........................................ 8 2 Findings 10 2.1 Summary ......................................... 1 0 2.2 Key Findings ....................................... 1 1 3 Detailed Results 12 3.1 Potential Front-Running For Migration Blocking .................... 1 2 3.2 Avoidance of Unnecessary (Small) Loss During Migration ............... 1 5 3.3 Duplicate Pool Detection and Prevention ........................ 1 7 3.4 Recommended Explicit Pool Validity Checks ...................... 1 9 3.5 Incompatibility With Deflationary Tokens ........................ 2 1 3.6 Suggested Adherence of Checks-Effects-Interactions .................. 2 3 3.7 Improved Logic in getMultiplier() ............................ 2 5 3.8 Improved EOA Detection Against Front-Running of Revenue Conversion ....... 2 7 3.9 No Pair Creation With Zero Migration Balance ..................... 2 9 3.10 Full Charge of Proposal Execution Cost From Accompanying msg.value ........ 3 1 3.11 Improved Handling of Corner Cases in Proposal Submission .............. 3 2 3.12 Inconsistency Between Documented and Implemented SUSHI Inflation ........ 3 5 3.13 Non-Governance-Based Admin of TimeLock And Related Privileges .......... 3 6 3.14 Other Suggestions .................................... 3 8 4 Conclusion 39 5 Appendix 40 5.1 Basic Coding Bugs .................................... 4 0 3/47 PeckShield Audit Report #: 2020-47Confidential 5.1.1 Constructor Mismatch .............................. 4 0 5.1.2 Ownership Takeover ............................... 4 0 5.1.3 Redundant Fallback Function .......................... 4 0 5.1.4 Overflows & Underflows ............................. 4 0 5.1.5 Reentrancy .................................... 4 1 5.1.6 Money-Giving Bug ................................ 4 1 5.1.7 Blackhole .................................... 4 1 5.1.8 Unauthorized Self-Destruct ........................... 4 1 5.1.9 Revert DoS ................................... 4 1 5.1.10 Unchecked External Call ............................ 4 2 5.1.11 Gasless Send ................................... 4 2 5.1.12 Send Instead Of Transfer ........................... 4 2 5.1.13 Costly Loop ................................... 4 2 5.1.14 (Unsafe) Use Of Untrusted Libraries ...................... 4 2 5.1.15 (Unsafe) Use Of Predictable Variables ..................... 4 3 5.1.16 Transaction Ordering Dependence ....................... 4 3 5.1.17 Deprecated Uses ................................. 4 3 5.2 Semantic Consistency Checks .............................. 4 3 5.3 Additional Recommendations .............................. 4 3 5.3.1 Avoid Use of Variadic Byte Array ........................ 4 3 5.3.2 Make Visibility Level Explicit .......................... 4 4 5.3.3 Make Type Inference Explicit .......................... 4 4 5.3.4 Adhere To Function Declaration Strictly .................... 4 4 References 45 4/47 PeckShield Audit Report #: 2020-47Confidential 1|Introduction Given the opportunity to review the SushiSwap smart contract source code, 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 branch of SushiSwap 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 SushiSwap SushiSwap is designed as an evolutional improvement of UniswapV2 ,w h i c hi sam a j o rd e c e n t r a l i z e d exchange (DEX) running on top of Ethereum blockchain. SushiSwap used UniswapV2 ’s core design, but extended with features such as liquidity provider incentives and community-based governance. We note that with UniswapV2 , liquidity providers only earn the pool’s trading fees when they are actively providing the pool liquidity. Once they have withdrawn their portion of the pool, they no longer receive that reward. With SushiSwap ,SUSHI holders will be entitled to continue to earn a portion of the protocol’s trading fee, even though she no longer participates in the liquidity provision. The basic information of SushiSwap is as follows: Table 1.1: Basic Information of SushiSwap Item Description Issuer SushiSwap Website https://sushiswap.org/ Type Ethereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report September 3, 2020 In the following, we show the Git repository of reviewed code and the commit hash value used in 5/47 PeckShield Audit Report #: 2020-47Confidential this audit: •https://github.com/sushiswap/sushiswap (180bc9b) 1.2 About PeckShield PeckShield Inc. [ 19]i sal e a d i n gb l o c k c h a i ns e c u r i t yc o m p a n yw i t ht h eg o a lo fe l e v a t i n gt h es e c u - rity, privacy, and usability of current blockchain ecosystems by offering top-notch, industry-leading services and products (including the service of smart contract auditing). We are reachable at Telegram (https://t.me/peckshield ), Twitter ( http://twitter.com/peckshield ), or Email ( 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 [ 14]: •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,medium and low respectively. Severity is determined by likelihood and impact and can be classified into four categories accordingly, i.e., Critical ,High ,Medium ,Low shown in Table 1.2. To evaluate the risk, we go through a list of check items and each would be labeled with as e v e r i t yc a t e g o r y . F o ro n ec h e c ki t e m ,i fo u rt o o lo ra n a l y s i sd o e sn o ti d e n t i f ya n yi s s u e ,t h e 6/47 PeckShield Audit Report #: 2020-47Confidential 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/47 PeckShield Audit Report #: 2020-47Confidential 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: •Basic Coding Bugs: 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 DeFi Scrutiny: 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) [ 13], 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.4to 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-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. 8/47 PeckShield Audit Report #: 2020-47Confidential 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 af u n c t i o nd o e sn o tg e n e r a t et h ec o r r e c tr e t u r n / s t a t u sc o d e , 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/47 PeckShield Audit Report #: 2020-47Confidential 2|Findings 2.1 Summary Here is a summary of our findings after analyzing the SushiSwap 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 2 Medium 3 Low 6 Informational 2 Total 13 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 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/47 PeckShield Audit Report #: 2020-47Confidential 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 2high-severity vulnerabil- ities, 3medium-severity vulnerabilities, 6low-severity vulnerabilities and 2informational recommen- dations. Table 2.1: Key SushiSwap Audit Findings ID Severity Title Category Status PVE-001 High Potential Front-Running For Migration BlockingTime and State Partially Fixed PVE-002 Low Avoidance ofUnnecessary (Small) Loss During MigrationBusiness Logics Fixed PVE-003 Medium Duplicate Pool Detection andPrevention Business Logics Confirmed PVE-004 Informational Recommended Explicit Pool Validity ChecksSecurity Features Confirmed PVE-005 Informational Incompatibility with Deflationary Tokens Business Logics Partially Fixed PVE-006 Low Suggested Adherence of Checks-Effects-InteractionsTime and State Confirmed PVE-007 Medium Improved Logic ingetMultiplier() Business Logics Confirmed PVE-008 Medium Improved EOA Detection Against Front-Running ofRevenue ConversionBusiness Logics Fixed PVE-009 Low NoPair Creation With Zero Migration BalanceBusiness Logics Confirmed PVE-010 Low Full Charge ofProposal Execution Cost From Accompanying msg.valueBusiness Logics Confirmed PVE-011 Low Improved Handling ofCorner Cases in Proposal SubmissionError Conditions, Return Values, Status CodesConfirmed PVE-012 Low Better Clarification ofSUSHI Inflation Business Logics Confirmed PVE-013 High Non-Governance-Based Admin of TimeLock And Related PrivilegesSecurity Features Confirmed Please refer to Section 3for details. 11/47 PeckShield Audit Report #: 2020-47Confidential 3|Detailed Results 3.1 Potential Front-Running For Migration Blocking •ID: PVE-001 •Severity: High •Likelihood: Medium •Impact: High•Target: UniswapV2Pair •Category: Time and State [ 11] •CWE subcategory: CWE-663 [ 3] Description SushiSwap has developed unique tokenomics in two phases: In the first phase, traders stake the UniswapV2 ’s liquidity pools tokens for mining SUSHI tokens; and in the second phase, traders are meant to migrate those UniswapV2 ’s liquidity pools tokens for the underlying assets to the SushiSwap DEX. The migration might be incentivized by the different token distribution mechanics proposed by SushiSwap . Specifically, with the current UniswapV2 configuration, 0.3%of all trading fees in any pool are proportionately distributed to the pool’s liquidity providers. In comparison, SushiSwap allocates 0.25% directly to the active liquidity providers, but the remaining 0.05% are converted back to SUSHI and re-distributed to the SUSHI token holders. Figure 3.1: The Migration Procedure Mechanically, the migration procedure can be divided into four distinct steps: deploy sushiFactory ,deploy migrator ,configure MasterChef ,a n d start migration .N o t e t h e s e f o u r s t e p s n e e d t o b e 12/47 PeckShield Audit Report #: 2020-47Confidential sequentially executed and the timing of their execution is crucial. In particular, if we examine the final step, i.e., start migration , the migration process is kicked off by invoking the migrate ()routine, which has a final check in place after the migration, i.e., require (bal ==newLpToken .balanceOf (address (this )), "migrate :bad").F o rs i m p l i c i t y ,w ec a l lt h i sp a r t i c u l a rc h e c ka st h e migration check . 135 //Migrate lptoken toanother lpcontract .Can becalled byanyone .Wetrust that migrator contract isgood . 136 function migrate (uint256 _pid )public { 137 require (address (migrator )! = address (0) , "migrate :nomigrator "); 138 PoolInfo storage pool =poolInfo [_pid ]; 139 IERC20 lpToken =pool .lpToken ; 140 uint256 bal =lpToken .balanceOf (address (this )); 141 lpToken .safeApprove (address (migrator ),bal); 142 IERC20 newLpToken =migrator .migrate (lpToken ); 143 require (bal ==newLpToken .balanceOf (address (this )), "migrate :bad"); 144 pool .lpToken =newLpToken ; 145 } Listing 3.1: MasterChef .sol The actual bulk work of migration is performed by the Migrator contract in a function also named migrate ()(we show the related code snippet below). It in essence burns the UniswapV2 ’s liquidity pool (or LP) tokens to reclaim the underlying assets and transfers them to SushiSwap for minting of the corresponding new pair’s LP tokens. 26 function migrate (IUniswapV2Pair orig )public returns (IUniswapV2Pair ){ 27 require (msg .sender == chef ,"not from master chef "); 28 require (block .number >= notBeforeBlock ,"too early tomigrate "); 29 require (orig .factory () = = oldFactory ,"not from old factory "); 30 address token0 =orig .token0 () ; 31 address token1 =orig .token1 () ; 32 IUniswapV2Pair pair =IUniswapV2Pair (factory .getPair (token0 ,token1 )); 33 if(pair == IUniswapV2Pair (address (0))) { 34 pair =IUniswapV2Pair (factory .createPair (token0 ,token1 )); 35 } 36 uint256 lp=orig .balanceOf (msg .sender ); 37 if(lp== 0 ) return pair ; 38 desiredLiquidity =lp; 39 orig .transferFrom (msg .sender ,address (orig ),lp); 40 orig .burn (address (pair )); 41 pair .mint (msg .sender ); 42 desiredLiquidity =uint256 (*1) ; 43 return pair ; 44 } Listing 3.2: Migrator .sol We emphasize that the staked UniswapV2 ’s LP tokens are transferred back to the UniswapV2 pair for redemption of the underlying assets (lines 39 * 40 )a n dt h er e d e e m e du n d e r l y i n ga s s e t sa r et h e n sent to the new pair in SushiSwap for minting (lines 40 * 41 ). 13/47 PeckShield Audit Report #: 2020-47Confidential The new SushiSwap pair’s mint ()function is shown below. Here comes the critical part: the migration process assumes the migrator is the first to mint the new LP tokens (of this particular trading pair). Otherwise, the migration will fail! This assumption essentially reflects the code logic in lines 126*128 .I n o t h e r w o r d s , i f a n a c t o r i s a b l e t o f r o n t - r u n i t t o b e c o m e t h e fi r s t o n e i n s u c c e s s f u l l y minting the new LP tokens, the actor will successfully block this migration (of this specific trading pair or the pool in MasterChef ). 115 function mint (address to)external lock returns (uint liquidity ){ 116 (uint112 _reserve0 ,uint112 _reserve1 ,) = getReserves () ; //gas savings 117 uint balance0 =IERC20Uniswap (token0 ).balanceOf (address (this )); 118 uint balance1 =IERC20Uniswap (token1 ).balanceOf (address (this )); 119 uint amount0 =balance0 .sub(_reserve0 ); 120 uint amount1 =balance1 .sub(_reserve1 ); 121 122 bool feeOn =_mintFee (_reserve0 ,_reserve1 ); 123 uint _totalSupply =totalSupply ;//gas savings ,must bedefined here since totalSupply can update in_mintFee 124 if(_totalSupply == 0 ) { 125 address migrator =IUniswapV2Factory (factory ).migrator () ; 126 if(msg .sender == migrator ){ 127 liquidity =IMigrator (migrator ).desiredLiquidity () ; 128 require (liquidity >0& & liquidity !=uint256 (*1) , "Bad desired liquidity "); 129 }else { 130 require (migrator == address (0) , "Must not have migrator "); 131 liquidity =Math .sqrt (amount0 .mul(amount1 )).sub(MINIMUM_LIQUIDITY ); 132 } 133 _mint (address (0) , MINIMUM_LIQUIDITY );//permanently lock the first MINIMUM_LIQUIDITY tokens 134 }else { 135 liquidity =Math .min(amount0 .mul(_totalSupply )/ _reserve0 ,amount1 .mul( _totalSupply )/ _reserve1 ); 136 } 137 require (liquidity >0 , ’UniswapV2 :INSUFFICIENT_LIQUIDITY_MINTED ’); 138 _mint (to,liquidity ); 139 140 _update (balance0 ,balance1 ,_reserve0 ,_reserve1 ); 141 if(feeOn )kLast =uint (reserve0 ).mul(reserve1 );//reserve0 and reserve1 are up -to-date 142 emit Mint (msg .sender ,amount0 ,amount1 ); 143 } Listing 3.3: UniswapV2Pair .sol Recall the above migration check that essentially states the new LP token amount should equal to the old LP token amount. If the migration transaction is not the first to mint new LP tokens, the first transaction that successfully mints the new LP tokens will lead to _totalSupply != 0.I n other words, the migration transaction will be forced to take the execution path in lines 135,n o t the intended lines 126 * 128 .A s a r e s u l t , t h e m i n t e d a m o u n t i s u n l i k e l y t o b e t h e s a m e a s t h e o l d 14/47 PeckShield Audit Report #: 2020-47Confidential UniswapV2 ’s pool token amount before migration, hence failing the migration check! To ensure a smooth migration process, we need to guarantee the first minting of new LP tokens is launched by the migration transaction. To achieve that, we need to prevent any unintended minting (of new LP tokens) between the first step deploy sushiFactory and the third step configure MasterChef .A n a t u r a l a p p r o a c h i s t o c o m p l e t e t h e i n i t i a l t h r e e s t e p s w i t h i n t h e s a m e t r a n s a c t i o n , best facilitated by a contract-coordinated deployment. Recommendation Deploy these contracts in a coherent fashion and avoid the above-mentioned front-running to guarantee a smooth migration. Status This issue has been confirmed and largely addressed by streamlining the entire deploy- ment script (without the need of actually revising the smart contract implementation). This is indeed the approach the team plans to take and exercise with extra caution when deploying these contracts (by avoiding unnecessary exposure of vulnerable time window for front-running). 3.2 Avoidance of Unnecessary (Small) Loss During Migration •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: UniswapV2Pair .sol •Category: Business Logics [ 10] •CWE subcategory: CWE-841 [ 8] Description We have discussed the four distinct migration steps in Section 3.1and highlighted the need of being the first one for the migrator to mint the new liquidity pool (LP) tokens. In this section, we further elaborate another issue in current migration logic that could unnecessarily lead to a (small) loss of assets. The loss is caused in the mint ()function of the revised UniswapV2Pair contract. In particular, the first-time minting (with _totalSupply == 0)w i l lt a k et h e then branch (line 124)t h a te x e c u t e sc o d e statements in lines 126 * 128 ,f o l l o w e db y _mint (address (0), MINIMUM_LIQUIDITY )in line 133. 115 function mint (address to)external lock returns (uint liquidity ){ 116 (uint112 _reserve0 ,uint112 _reserve1 ,) = getReserves () ; //gas savings 117 uint balance0 =IERC20Uniswap (token0 ).balanceOf (address (this )); 118 uint balance1 =IERC20Uniswap (token1 ).balanceOf (address (this )); 119 uint amount0 =balance0 .sub(_reserve0 ); 120 uint amount1 =balance1 .sub(_reserve1 ); 121 122 bool feeOn =_mintFee (_reserve0 ,_reserve1 ); 15/47 PeckShield Audit Report #: 2020-47Confidential 123 uint _totalSupply =totalSupply ;//gas savings ,must bedefined here since totalSupply can update in_mintFee 124 if(_totalSupply == 0 ) { 125 address migrator =IUniswapV2Factory (factory ).migrator () ; 126 if(msg .sender == migrator ){ 127 liquidity =IMigrator (migrator ).desiredLiquidity () ; 128 require (liquidity >0& & liquidity !=uint256 (*1) , "Bad desired liquidity "); 129 }else { 130 require (migrator == address (0) , "Must not have migrator "); 131 liquidity =Math .sqrt (amount0 .mul(amount1 )).sub(MINIMUM_LIQUIDITY ); 132 } 133 _mint (address (0) , MINIMUM_LIQUIDITY );//permanently lock the first MINIMUM_LIQUIDITY tokens 134 }else { 135 liquidity =Math .min(amount0 .mul(_totalSupply )/ _reserve0 ,amount1 .mul( _totalSupply )/ _reserve1 ); 136 } 137 require (liquidity >0 , ’UniswapV2 :INSUFFICIENT_LIQUIDITY_MINTED ’); 138 _mint (to,liquidity ); 139 140 _update (balance0 ,balance1 ,_reserve0 ,_reserve1 ); 141 if(feeOn )kLast =uint (reserve0 ).mul(reserve1 );//reserve0 and reserve1 are up -to-date 142 emit Mint (msg .sender ,amount0 ,amount1 ); 143 } Listing 3.4: UniswapV2Pair .sol To understand why current migration logic will cause a small bit of loss, we need to understand the purpose of minting of MINIMUM_LIQUIDITY toaddress (0).I t m a y l o o k s t r a n g e a s i t e s s e n t i a l l y burns MINIMUM_LIQUIDITY of LP tokens (and thus introduces the loss). It turns out that it is in place to prevent an early liquidity provider to make the LP token too costly for other liquidity providers to enter, hence blocking the early liquidity provider from monopolizing the liquidity pool. However, since our migration is the early liquidity provider (with likely a large amount of minting), this case will not occur! With that, we can safely move the MINIMUM_LIQUIDITY burning operation into the else branch (lines 129*132 ). The intention is the burning of MINIMUM_LIQUIDITY only occurs in other pairs that are not involved in the migration. Recommendation Avoid the unnecessary small loss during migration. A quick fix is suggested as below. 115 function mint (address to)external lock returns (uint liquidity ){ 116 (uint112 _reserve0 ,uint112 _reserve1 ,) = getReserves () ; //gas savings 117 uint balance0 =IERC20Uniswap (token0 ).balanceOf (address (this )); 118 uint balance1 =IERC20Uniswap (token1 ).balanceOf (address (this )); 119 uint amount0 =balance0 .sub(_reserve0 ); 120 uint amount1 =balance1 .sub(_reserve1 ); 121 16/47 PeckShield Audit Report #: 2020-47Confidential 122 bool feeOn =_mintFee (_reserve0 ,_reserve1 ); 123 uint _totalSupply =totalSupply ;//gas savings ,must bedefined here since totalSupply can update in_mintFee 124 if(_totalSupply == 0 ) { 125 address migrator =IUniswapV2Factory (factory ).migrator () ; 126 if(msg .sender == migrator ){ 127 liquidity =IMigrator (migrator ).desiredLiquidity () ; 128 require (liquidity >0& & liquidity !=uint256 (*1) , "Bad desired liquidity "); 129 }else { 130 require (migrator == address (0) , "Must not have migrator "); 131 liquidity =Math .sqrt (amount0 .mul(amount1 )).sub(MINIMUM_LIQUIDITY ); 132 _mint (address (0) , MINIMUM_LIQUIDITY );//permanently lock the first MINIMUM_LIQUIDITY tokens 133 } 134 }else { 135 liquidity =Math .min(amount0 .mul(_totalSupply )/ _reserve0 ,amount1 .mul( _totalSupply )/ _reserve1 ); 136 } 137 require (liquidity >0 , ’UniswapV2 :INSUFFICIENT_LIQUIDITY_MINTED ’); 138 _mint (to,liquidity ); 139 140 _update (balance0 ,balance1 ,_reserve0 ,_reserve1 ); 141 if(feeOn )kLast =uint (reserve0 ).mul(reserve1 );//reserve0 and reserve1 are up -to-date 142 emit Mint (msg .sender ,amount0 ,amount1 ); 143 } Listing 3.5: UniswapV2Pair .sol(revised ) Status The issue has been fixed by this commit: d76898b603aed60a776fc0ac529b199e1a6c8c9e . 3.3 Duplicate Pool Detection and Prevention •ID: PVE-003 •Severity: Medium •Likelihood: Low •Impact: High•Target: MasterChef •Category: Business Logics [ 10] •CWE subcategory: CWE-841 [ 8] Description SushiSwap provides incentive mechanisms that reward the staking of UniswapV2 LP tokens with SUSHI tokens. The rewards are carried out by designating a number of staking pools into which UniswapV2 LP tokens can be staked. Each pool has its allocPoint *100%/ totalAllocPoint share of scheduled rewards and the rewards these stakers in a pool will receive are proportional to the amount of LP tokens they have staked in the pool versus the total amount of LP tokens staked in the pool. 17/47 PeckShield Audit Report #: 2020-47Confidential As of this writing, there are 13pools that share the rewarded SUSHI tokens and 5more have been scheduled for addition (after voting approval). To accommodate these new pools, SushiSwap has the necessary mechanism in place that allows for dynamic additions of new staking pools that can participate in being incentivized as well. The addition of a new pool is implemented in add(),w h o s ec o d el o g i ci ss h o w nb e l o w . I tt u r n so u t it did not perform necessary sanity checks in preventing a new pool but with a duplicate UniswapV2 LP token from being added. Though it is a privileged interface (protected with the modifier onlyOwner ) and the supported governance can be leveraged to ensure a duplicate LP token will not be added, it is still desirable to enforce it at the smart contract code level, eliminating the concern of wrong pool introduction from human omissions. 107 function add(uint256 _allocPoint ,IERC20 _lpToken ,bool _withUpdate )public onlyOwner { 108 if(_withUpdate ){ 109 massUpdatePools () ; 110 } 111 uint256 lastRewardBlock =block .number >startBlock ?block .number :startBlock ; 112 totalAllocPoint =totalAllocPoint .add(_allocPoint ); 113 poolInfo .push (PoolInfo ({ 114 lpToken :_lpToken , 115 allocPoint :_allocPoint , 116 lastRewardBlock :lastRewardBlock , 117 accSushiPerShare :0 118 })) ; 119 } Listing 3.6: MasterChef .sol Recommendation Detect whether the given pool for addition is a duplicate of an existing pool. The pool addition is only successful when there is no duplicate. 107 function checkPoolDuplicate (IERC20 _lpToken )public { 108 uint256 length =poolInfo .length ; 109 for (uint256 pid =0 ; pid <length ;+ + pid){ 110 require (poolInfo [_pid ].lpToken !=_lpToken ,"add:existing pool ?"); 111 } 112 } 113 114 function add(uint256 _allocPoint ,IERC20 _lpToken ,bool _withUpdate )public onlyOwner { 115 if(_withUpdate ){ 116 massUpdatePools () ; 117 } 118 checkPoolDuplicate (_lpToken ); 119 uint256 lastRewardBlock =block .number >startBlock ?block .number :startBlock ; 120 totalAllocPoint =totalAllocPoint .add(_allocPoint ); 121 poolInfo .push (PoolInfo ({ 122 lpToken :_lpToken , 123 allocPoint :_allocPoint , 18/47 PeckShield Audit Report #: 2020-47Confidential 124 lastRewardBlock :lastRewardBlock , 125 accSushiPerShare :0 126 })) ; 127 } Listing 3.7: MasterChef .sol(revised ) We point out that if a new pool with a duplicate LP token can be added, it will likely cause ah a v o ci nt h ed i s t r i b u t i o no fr e w a r d st ot h ep o o l sa n dt h es t a k e r s . W o r s e ,i tw i l la l s ob r i n gg r e a t troubles for the planned migration! Status We have discussed this issue with the team and the team is aware of it. Since the MasterChef contract is already live (with a huge amount of assets), the team prefers not modifying the code for the duplicate prevention, but instead takes necessary off-chain steps and exercises with extra caution to block duplicates when adding a new pool. 3.4 Recommended Explicit Pool Validity Checks •ID: PVE-004 •Severity: Medium •Likelihood: Low •Impact: High•Target: MasterChef •Category: Security Features [ 9] •CWE subcategory: CWE-287 [ 2] Description SushiSwap has a central contract – MasterChef that has been tasked with not only the migration (Section 3.1), but also the pool management, staking/unstaking support, as well as the reward distribution to various pools and stakers. In the following, we show the key pool data structure. Note all added pools are maintained in an array poolInfo . 53 //Info ofeach pool . 54 struct PoolInfo { 55 IERC20 lpToken ; //Address ofLPtoken contract . 56 uint256 allocPoint ; //How many allocation points assigned tothis pool . SUSHIs todistribute per block . 57 uint256 lastRewardBlock ;//Last block number that SUSHIs distribution occurs . 58 uint256 accSushiPerShare ;//Accumulated SUSHIs per share ,times 1e12.See below . 59 } 60 ... 61 //Info ofeach pool . 62 PoolInfo []public poolInfo ; Listing 3.8: MasterChef .sol 19/47 PeckShield Audit Report #: 2020-47Confidential When there is a need to add a new pool, set a new allocPoint for an existing pool, stake (by depositing the supported UniswapV2 ’s LP tokens), unstake (by redeeming previously deposited UniswapV2 ’s LP tokens), query pending SUSHI rewards, or migrate the pool assets, there is a constant need to perform sanity checks on the pool validity. The current implementation simply relies on the implicit, compiler-generated bound-checks of arrays to ensure the pool index stays within the array range [0, poolInfo .length -1].H o w e v e r , c o n s i d e r i n g t h e i m p o r t a n c e o f v a l i d a t i n g g i v e n p o o l s a n d their numerous occasions, a better alternative is to make explicit the sanity checks by introducing an e wm o d i fi e r ,s a y validatePool .T h i s n e w m o d i fi e r e s s e n t i a l l y e n s u r e s t h e g i v e n _pool_id or_pid indeed points to a valid, live pool, and additionally give semantically meaningful information when it is not! 201 //Deposit LPtokens toMasterChef for SUSHI allocation . 202 function deposit (uint256 _pid ,uint256 _amount )public { 203 PoolInfo storage pool =poolInfo [_pid ]; 204 UserInfo storage user =userInfo [_pid ][msg .sender ]; 205 updatePool (_pid ); 206 if(user .amount >0 ){ 207 uint256 pending =user .amount .mul(pool .accSushiPerShare ).div(1e12).sub(user . rewardDebt ); 208 safeSushiTransfer (msg .sender ,pending ); 209 } 210 pool .lpToken .safeTransferFrom (address (msg .sender ),address (this ),_amount ); 211 user .amount =user .amount .add(_amount ); 212 user .rewardDebt =user .amount .mul(pool .accSushiPerShare ).div(1e12); 213 emit Deposit (msg .sender ,_pid ,_amount ); 214 } Listing 3.9: MasterChef .sol We highlight that there are a number of functions that can be benefited from the new pool- validating modifier, including set(),migrate (),deposit (),withdraw (),emergencyWithdraw (),pendingSushi ()and updatePool (). Recommendation Apply necessary sanity checks to ensure the given _pid is legitimate. Ac- cordingly, a new modifier validatePool can be developed and appended to each function in the above list. 201 modifier validatePool (uint256 _pid ){ 202 require (_pid <poolInfo .length ,"chef :pool exists ?"); 203 _; 204 } 205 206 //Deposit LPtokens toMasterChef for SUSHI allocation . 207 function deposit (uint256 _pid ,uint256 _amount )public validatePool (_pid ){ 208 PoolInfo storage pool =poolInfo [_pid ]; 209 UserInfo storage user =userInfo [_pid ][msg .sender ]; 210 updatePool (_pid ); 211 if(user .amount >0 ){ 20/47 PeckShield Audit Report #: 2020-47Confidential 212 uint256 pending =user .amount .mul(pool .accSushiPerShare ).div(1e12).sub(user . rewardDebt ); 213 safeSushiTransfer (msg .sender ,pending ); 214 } 215 pool .lpToken .safeTransferFrom (address (msg .sender ),address (this ),_amount ); 216 user .amount =user .amount .add(_amount ); 217 user .rewardDebt =user .amount .mul(pool .accSushiPerShare ).div(1e12); 218 emit Deposit (msg .sender ,_pid ,_amount ); 219 } Listing 3.10: MasterChef .sol Status We have discussed this issue with the team. For the same reason as outlined in Section 3.3,b e c a u s et h e MasterChef contract is already live (with a huge amount of assets), any change needs to be deemed absolutely necessary. In this particular case, the team prefers not modifying the code as the compiler-generated bounds-checking is already in place. 3.5 Incompatibility With Deflationary Tokens •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterChef •Category: Business Logics [ 10] •CWE subcategory: CWE-708 [ 5] Description InSushiSwap ,t h e MasterChef contract operates as the main entry for interaction with staking users. The staking users deposit UniswapV2 ’s LP tokens into the SushiSwap pool and in return get proportion- ate share of the pool’s rewards. Later on, the staking users can withdraw their own assets from the pool. With assets in the pool, users can earn whatever incentive mechanisms proposed or adopted via governance. Naturally, the above two functions, i.e., deposit ()and withdraw (),a r ei n v o l v e di nt r a n s f e r r i n g users’ assets into (or out of) the SushiSwap protocol. Using the deposit ()function as an example, it needs to transfer deposited assets from the user account to the pool (line 210). When transferring standard ERC20 tokens, these asset-transferring routines work as expected: namely the account’s internal asset balances are always consistent with actual token balances maintained in individual ERC20 token contracts (lines 211 * 212 ). 201 //Deposit LPtokens toMasterChef for SUSHI allocation . 202 function deposit (uint256 _pid ,uint256 _amount )public { 203 PoolInfo storage pool =poolInfo [_pid ]; 204 UserInfo storage user =userInfo [_pid ][msg .sender ]; 21/47 PeckShield Audit Report #: 2020-47Confidential 205 updatePool (_pid ); 206 if(user .amount >0 ){ 207 uint256 pending =user .amount .mul(pool .accSushiPerShare ).div(1e12).sub(user . rewardDebt ); 208 safeSushiTransfer (msg .sender ,pending ); 209 } 210 pool .lpToken .safeTransferFrom (address (msg .sender ),address (this ),_amount ); 211 user .amount =user .amount .add(_amount ); 212 user .rewardDebt =user .amount .mul(pool .accSushiPerShare ).div(1e12); 213 emit Deposit (msg .sender ,_pid ,_amount ); 214 } Listing 3.11: MasterChef .sol However, in the cases of deflationary tokens, as shown in the above code snippets, the input amount may not be equal to the received amount due to the charged (and burned) transaction fee. 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 ()and withdraw (),m a yi n t r o d u c eu n e x p e c t e d balance inconsistencies when comparing internal asset records with external ERC20 token contracts in the cases of deflationary tokens. Apparently, these balance inconsistencies are damaging to accurate portfolio management of MasterChef and affects protocol-wide operation and maintenance. One mitigation is to query the asset change right before and after the asset-transferring routines. In other words, instead of automatically 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 the intended operation. Though these additional checks cost additional gas usage, we feel that they are necessary to deal with deflationary tokens or other customized ones if their support is deemed necessary. Another mitigation is to regulate the set of ERC20 tokens that are permitted into MasterChef pools. With the single entry of adding a new pool (via add()),MasterChef is indeed in the position to effectively regulate the set of assets allowed into the protocol. Fortunately, the UniswapV2 ’s LP tokens are not deflationary tokens and there is no need to take any action in SushiSwap .H o w e v e r , i t i s a p o t e n t i a l r i s k i f t h e c u r r e n t c o d e b a s e i s u s e d e l s e w h e r e or the need to add other tokens arises (e.g., in listing new DEX pairs). Also, the current code implementation, including the UniswapV2 ’s path-supported swap ()and thus SushiSwap ’s similar swap (), is indeed not compatible with deflationary tokens. Recommendation Regulate the set of LP tokens supported in SushiSwap and, if there is a need to support deflationary tokens, add necessary mitigation mechanisms to keep track of accurate balances. Status This issue has been confirmed. As there is a central place to regulate the assets that can be introduction in the pool management, the team decides no change for the time being. 22/47 PeckShield Audit Report #: 2020-47Confidential 3.6 Suggested Adherence of Checks-Effects-Interactions •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Low•Target: MasterChef •Category: Time and State [ 11] •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 .V i a t h i s 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 invoking functions that should only be executed once. This attack was part of several most prominent hacks in Ethereum history, including the DAO[22]e x p l o i t ,a n dt h er e c e n t Uniswap /Lendf .Mehack [ 20]. We notice there are several occasions the checks -effects -interactions principle is violated. Using the MasterChef as an example, the emergencyWithdraw ()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 234)s t a r t sb e f o r ee ff e c t i n gt h eu p d a t e on internal states (lines 236 * 237 ), hence violating the principle. In this particular case, if the external contract has some hidden logic that may be capable of launching re-entrancy via the very same emergencyWithdraw ()function. 230 //Withdraw without caring about rewards .EMERGENCY ONLY . 231 function emergencyWithdraw (uint256 _pid )public { 232 PoolInfo storage pool =poolInfo [_pid ]; 233 UserInfo storage user =userInfo [_pid ][msg .sender ]; 234 pool .lpToken .safeTransfer (address (msg .sender ),user .amount ); 235 emit EmergencyWithdraw (msg .sender ,_pid ,user .amount ); 236 user .amount =0 ; 237 user .rewardDebt =0 ; 238 } Listing 3.12: MasterChef .sol Another similar violation can be found in the deposit ()and withdraw ()routines within the same contract. 201 //Deposit LPtokens toMasterChef for SUSHI allocation . 202 function deposit (uint256 _pid ,uint256 _amount )public { 203 PoolInfo storage pool =poolInfo [_pid ]; 23/47 PeckShield Audit Report #: 2020-47Confidential 204 UserInfo storage user =userInfo [_pid ][msg .sender ]; 205 updatePool (_pid ); 206 if(user .amount >0 ){ 207 uint256 pending =user .amount .mul(pool .accSushiPerShare ).div(1e12).sub(user . rewardDebt ); 208 safeSushiTransfer (msg .sender ,pending ); 209 } 210 pool .lpToken .safeTransferFrom (address (msg .sender ),address (this ),_amount ); 211 user .amount =user .amount .add(_amount ); 212 user .rewardDebt =user .amount .mul(pool .accSushiPerShare ).div(1e12); 213 emit Deposit (msg .sender ,_pid ,_amount ); 214 } 215 216 //Withdraw LPtokens from MasterChef . 217 function withdraw (uint256 _pid ,uint256 _amount )public { 218 PoolInfo storage pool =poolInfo [_pid ]; 219 UserInfo storage user =userInfo [_pid ][msg .sender ]; 220 require (user .amount >= _amount ,"withdraw :not good "); 221 updatePool (_pid ); 222 uint256 pending =user .amount .mul(pool .accSushiPerShare ).div(1e12).sub(user . rewardDebt ); 223 safeSushiTransfer (msg .sender ,pending ); 224 user .amount =user .amount .sub(_amount ); 225 user .rewardDebt =user .amount .mul(pool .accSushiPerShare ).div(1e12); 226 pool .lpToken .safeTransfer (address (msg .sender ),_amount ); 227 emit Withdraw (msg .sender ,_pid ,_amount ); 228 } Listing 3.13: MasterChef .sol In the meantime, we should mention that the UniswapV2 ’s LP tokens implement rather standard ERC20 interfaces and their related token contracts are not vulnerable or exploitable for re-entrancy . Recommendation Apply necessary reentrancy prevention by following the checks -effects - interactions best practice. The above three functions can be revised as follows: 230 //Withdraw without caring about rewards .EMERGENCY ONLY . 231 function emergencyWithdraw (uint256 _pid )public { 232 PoolInfo storage pool =poolInfo [_pid ]; 233 UserInfo storage user =userInfo [_pid ][msg .sender ]; 234 uint256 _amount =user .amount 235 user .amount =0 ; 236 user .rewardDebt =0 ; 237 pool .lpToken .safeTransfer (address (msg .sender ),_amount ); 238 emit EmergencyWithdraw (msg .sender ,_pid ,_amount ); 239 } 240 241 //Deposit LPtokens toMasterChef for SUSHI allocation . 242 function deposit (uint256 _pid ,uint256 _amount )public { 243 PoolInfo storage pool =poolInfo [_pid ]; 244 UserInfo storage user =userInfo [_pid ][msg .sender ]; 245 24/47 PeckShield Audit Report #: 2020-47Confidential 246 updatePool (_pid ); 247 uint256 pending =user .amount .mul(pool .accSushiPerShare ).div(1e12).sub(user . rewardDebt ); 248 249 user .amount =user .amount .add(_amount ); 250 user .rewardDebt =user .amount .mul(pool .accSushiPerShare ).div(1e12); 251 252 253 safeSushiTransfer (msg .sender ,pending ); 254 pool .lpToken .safeTransferFrom (address (msg .sender ),address (this ),_amount ); 255 emit Deposit (msg .sender ,_pid ,_amount ); 256 } 257 258 259 //Withdraw LPtokens from MasterChef . 260 function withdraw (uint256 _pid ,uint256 _amount )public { 261 PoolInfo storage pool =poolInfo [_pid ]; 262 UserInfo storage user =userInfo [_pid ][msg .sender ]; 263 require (user .amount >= _amount ,"withdraw :not good "); 264 updatePool (_pid ); 265 uint256 pending =user .amount .mul(pool .accSushiPerShare ).div(1e12).sub(user . rewardDebt ); 266 267 user .amount =user .amount .sub(_amount ); 268 user .rewardDebt =user .amount .mul(pool .accSushiPerShare ).div(1e12); 269 270 safeSushiTransfer (msg .sender ,pending ); 271 pool .lpToken .safeTransfer (address (msg .sender ),_amount ); 272 emit Withdraw (msg .sender ,_pid ,_amount ); 273 } Listing 3.14: MasterChef .sol(revised ) Status This issue has been confirmed. Due to the same reason as outlined in Section 3.3,t h e team prefers not modifying the live code and leaves the code as it is. 3.7 Improved Logic in getMultiplier() •ID: PVE-007 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterChef •Category: Status Codes [ 12] •CWE subcategory: CWE-682 [ 4] Description SushiSwap incentives early adopters by specifying an initial list of 13pools into which early adopters can stake the supported UniswapV2 ’s LP tokens. The earnings were started at block 10,750,000in 25/47 PeckShield Audit Report #: 2020-47Confidential Ethereum. For every new block, there will be 100new SUSHI tokens minted (more in Section 3.12) and these minted tokens will be accordingly redistributed to the stakers of each pool. For the first 100,000blocks (lasting about 2weeks), the amount of SUSHI tokens produced will be multiplied by 10,r e s u l t i n gi n 1,000 SUSHI tokens (again more in Section 3.12) being minted per block. The early incentives are greatly facilitated by a helper function called getMultiplier ().T h i s function takes two arguments, i.e., _from and _to,a n dc a l c u l a t e st h er e w a r dm u l t i p l i e rf o rt h eg i v e n block range ( [_from ,_to]). 147 //Return reward multiplier over the given _from to_to block . 148 function getMultiplier (uint256 _from ,uint256 _to)public view returns (uint256 ){ 149 if(_to <= bonusEndBlock ){ 150 return _to.sub(_from ).mul(BONUS_MULTIPLIER ); 151 }else if(_from >= bonusEndBlock ){ 152 return _to.sub(_from ); 153 }else { 154 return bonusEndBlock .sub(_from ).mul(BONUS_MULTIPLIER ).add( 155 _to.sub(bonusEndBlock ) 156 ); 157 } 158 } Listing 3.15: MasterChef .sol For elaboration, the helper’s code snippet is shown above. We notice that this helper does not take into account the initial block ( startBlock )f r o mw h i c ht h ei n v e n t i v er e w a r d ss t a r tt oa p p l y . A s ar e s u l t ,w h e nan o r m a lu s e rg i v e sa r b i t r a r ya r g u m e n t s ,i tc o u l dr e t u r nw r o n gr e w a r dm u l t i p l i e r ! Ac o r r e c ti m p l e m e n t a t i o nn e e d st ot a k e startBlock into account and appropriately re-adjusts the starting block number, i.e., _from =_from >=startBlock ?_from :startBlock . We also notice that the helper function is called by two other routines, e.g., pendingSushi ()and updatePool ().F o r t u n a t e l y , t h e s e t w o r o u t i n e s h a v e e n s u r e d _from >=startBlock and always use the correct reward multiplier for reward redistribution. Recommendation Apply additional sanity checks in the getMultiplier ()routine so that the internal _from parameter can be adjusted to take startBlock into account. 147 //Return reward multiplier over the given _from to_to block . 148 function getMultiplier (uint256 _from ,uint256 _to)public view returns (uint256 ){ 149 _from =_from >= startBlock ?_from :startBlock ; 150 if(_to <= bonusEndBlock ){ 151 return _to.sub(_from ).mul(BONUS_MULTIPLIER ); 152 }else if(_from >= bonusEndBlock ){ 153 return _to.sub(_from ); 154 }else { 155 return bonusEndBlock .sub(_from ).mul(BONUS_MULTIPLIER ).add( 156 _to.sub(bonusEndBlock ) 157 ); 158 } 26/47 PeckShield Audit Report #: 2020-47Confidential 159 } Listing 3.16: MasterChef .sol Status This issue has been confirmed. Due to the same reason as outlined in Section 3.3, the team prefers not modifying the live code and leaves the implementation as it is. As discussed earlier, the current callers provide the arguments that have been similarly verified to always obtain correct reward multipliers. Meanwhile, the team has been informed about possible misleading results as external inquiries on the getMultiplier ()routine may provide arbitrary arguments that do not take into account the initial block, i.e., startBlock . 3.8 Improved EOA Detection Against Front-Running of Revenue Conversion •ID: PVE-008 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: SushiMaker •Category: Status Codes [ 12] •CWE subcategory: CWE-682 [ 4] Description SushiSwap has a rather unique tokenomics around SUSHI tokens. In this section, we explore the logic behind SushiMaker and SushiBar .SushiMaker collects possible revenues (in terms of SushiSwap pairs’ LP tokens), convert collected revenues into SUSHI tokens, and then send them to SushiBar .SUSHI holders can stake their SUSHI assets to SushiBar to earn more SUSHI . 26 function convert (address token0 ,address token1 )public { 27 //Atleast wetry tomake front -running harder todo. 28 require (!Address .isContract (msg .sender ),"donot convert from contract "); 29 IUniswapV2Pair pair =IUniswapV2Pair (factory .getPair (token0 ,token1 )); 30 pair .transfer (address (pair ),pair .balanceOf (address (this ))); 31 pair .burn (address (this )); 32 uint256 wethAmount =_toWETH (token0 )+ _toWETH (token1 ); 33 _toSUSHI (wethAmount ); 34 } Listing 3.17: SushiMaker .sol The conversion of collected revenues into SUSHI is implemented in convert ().D u e t o p o s s i b l e revenues into SushiMaker ,t h i sr o u t i n ec o u l db eat a r g e tf o rf r o n t - r u n n i n g( a n df u r t h e rf a c i l i t a t e d by flash loans) to steal the majority of collected revenues, resulting in a loss for current stakers in SushiBar . 27/47 PeckShield Audit Report #: 2020-47Confidential As a defense mechanism, SushiMaker takes a pro-active measure by only allowing EOA accounts when the revenues are being converted. The detection of whether the transaction sender is an EOA or contract is based on the isContract ()routine borrowed from the Address library (shown below). 9 /** 10 *@dev Returns true if‘account ‘isacontract . 11 * 12 *[IMPORTANT ] 13 *==== 14 *Itisunsafe toassume that anaddress for which this function returns 15 *false isanexternally -owned account (EOA)and not acontract . 16 * 17 *Among others ,‘isContract ‘will return false for the following 18 *types ofaddresses : 19 * 20 *-anexternally -owned account 21 *-acontract inconstruction 22 *-anaddress where acontract will becreated 23 *-anaddress where acontract lived ,but was destroyed 24 *==== 25 */ 26 function isContract (address account )internal view returns (bool ){ 27 //This method relies inextcodesize ,which returns 0for contracts in 28 //construction ,since the code isonly stored atthe end ofthe 29 //constructor execution . 31 uint256 size ; 32 //solhint -disable -next -line no-inline -assembly 33 assembly {size :=extcodesize (account )} 34 return size >0 ; 35 } Listing 3.18: Address .sol The current isContract ()could achieve its goal in most cases. However, as mentioned in the library documentation, “it is unsafe to assume that an address for which this function returns false is an externally-owned account (EOA) and not a contract.” Considering the specific context SushiMaker , we need a reliable method to detect the convert ()transaction sender is an externally-owned account, i.e., EOA.W i t h t h a t , w e c a n s i m p l y a c h i e v e o u r g o a l b y require (msg.sender ==tx.origin ,"donot convert from contract "). Recommendation Apply the improved detection logic in the convert ()routine as follows. 26 function convert (address token0 ,address token1 )public { 27 //Atleast wetry tomake front -running harder todo. 28 require (msg .sender ==tx.origin ,"donot convert from contract "); 29 IUniswapV2Pair pair =IUniswapV2Pair (factory .getPair (token0 ,token1 )); 30 pair .transfer (address (pair ),pair .balanceOf (address (this ))); 31 pair .burn (address (this )); 32 uint256 wethAmount =_toWETH (token0 )+ _toWETH (token1 ); 33 _toSUSHI (wethAmount ); 28/47 PeckShield Audit Report #: 2020-47Confidential 34 } Listing 3.19: SushiMaker .sol Status This issue has been confirmed and accordingly fixed by this commit: 84243 d745ed68d76c85964eb4a160211cecf0c88 . 3.9 No Pair Creation With Zero Migration Balance •ID: PVE-009 •Severity: Low •Likelihood: Low •Impact: Low•Target: Migrator •Category: Business Logics [ 10] •CWE subcategory: CWE-770 [ 6] Description As discussed in Section 3.1,t h ea c t u a lb u l kw o r ko fm i g r a t i o ni sp e r f o r m e db yt h e Migrator contract, specifically its migrate ()routine (we show the related code snippet below). This specific routine basically burns the UniswapV2 ’s LP tokens to reclaim the underlying assets and then transfers them toSushiSwap for the minting of the corresponding new pair’s LP tokens. 26 function migrate (IUniswapV2Pair orig )public returns (IUniswapV2Pair ){ 27 require (msg .sender == chef ,"not from master chef "); 28 require (block .number >= notBeforeBlock ,"too early tomigrate "); 29 require (orig .factory () = = oldFactory ,"not from old factory "); 30 address token0 =orig .token0 () ; 31 address token1 =orig .token1 () ; 32 IUniswapV2Pair pair =IUniswapV2Pair (factory .getPair (token0 ,token1 )); 33 if(pair == IUniswapV2Pair (address (0))) { 34 pair =IUniswapV2Pair (factory .createPair (token0 ,token1 )); 35 } 36 uint256 lp=orig .balanceOf (msg .sender ); 37 if(lp== 0 ) return pair ; 38 desiredLiquidity =lp; 39 orig .transferFrom (msg .sender ,address (orig ),lp); 40 orig .burn (address (pair )); 41 pair .mint (msg .sender ); 42 desiredLiquidity =uint256 (*1) ; 43 return pair ; 44 } Listing 3.20: Migrator .sol In the unlikely situation when the migrated pool does have any balance for migration, migrate () routine is expected to simply return. However, it is interesting to notice that the return (line 37)d o e s 29/47 PeckShield Audit Report #: 2020-47Confidential not happen until the new SushiSwap pair is created. As the SushiSwap DEX is based on the UniswapV2 , an e wp a i rc r e a t i o nm a yc o s tm o r et h a n 2,000,000gas. Considering the current congested Ethereum blockchain and the relatively prohibitive gas cost, it is inappropriate to spend the gas cost to create an e wp a i rw h e nt h eb a l a n c ei s zero and no migration actually occurs. Recommendation Move the balance detection logic earlier so that we can simply return without migration and new pair creation if the balance is zero , i.e., orig .balanceOf (msg.sender )== 0 . An example adjustment is shown below. 26 function migrate (IUniswapV2Pair orig )public returns (IUniswapV2Pair ){ 27 require (msg .sender == chef ,"not from master chef "); 28 require (block .number >= notBeforeBlock ,"too early tomigrate "); 30 uint256 lp=orig .balanceOf (msg .sender ); 31 if(lp== 0 ) return pair ; 33 require (orig .factory () = = oldFactory ,"not from old factory "); 34 address token0 =orig .token0 () ; 35 address token1 =orig .token1 () ; 36 IUniswapV2Pair pair =IUniswapV2Pair (factory .getPair (token0 ,token1 )); 37 if(pair == IUniswapV2Pair (address (0))) { 38 pair =IUniswapV2Pair (factory .createPair (token0 ,token1 )); 39 } 40 orig .transferFrom (msg .sender ,address (orig ),lp); 41 orig .burn (address (pair )); 43 desiredLiquidity =lp; 44 pair .mint (msg .sender ); 45 desiredLiquidity =uint256 (*1) ; 46 return pair ; 47 } Listing 3.21: Migrator .sol Status This issue has been confirmed. 30/47 PeckShield Audit Report #: 2020-47Confidential 3.10 Full Charge of Proposal Execution Cost From Accompanying msg.value •ID: PVE-010 •Severity: Low •Likelihood: Low •Impact: Low•Target: GovernorAlpha •Category: Business Logics [ 10] •CWE subcategory: CWE-770 [ 6] Description Sushi adopts the governance implementation from Compound by adjusting its governance token and related parameters, e.g., quorumVotes ()and proposalThreshold ().T h e o r i g i n a l g o v e r n a n c e h a s b e e n successfully audited by OpenZeppelin . In the following, we would like to comment on a particular issue regarding the proposal exe- cution cost. Notice that the actual proposal execution is kicked off by invoking the governance’s execute ()function. This function is marked as payable ,i n d i c a t i n gt h et r a n s a c t i o ns e n d e ri sr e s p o n - sible for supplying required amount of ETHsa se a c hi n h e r e n ta c t i o n( l i n e 215)i nt h ep r o p o s a lm a y require accompanying certain ETHs, specified in proposal .values [i],w h e r e iis the ithaction inside the proposal. 210 function execute (uint proposalId )public payable { 211 require (state (proposalId )= = ProposalState .Queued ,"GovernorAlpha ::execute : proposal can only beexecuted ifitisqueued "); 212 Proposal storage proposal =proposals [proposalId ]; 213 proposal .executed =true ; 214 for (uint i=0 ; i<proposal .targets .length ;i++) { 215 timelock .executeTransaction .value (proposal .values [i])(proposal .targets [i], proposal .values [i],proposal .signatures [i],proposal .calldatas [i], proposal .eta); 216 } 217 emit ProposalExecuted (proposalId ); 218 } Listing 3.22: GovernorAlpha .sol Though it is likely the case that a majority of these actions do not require any ETHs, i.e., proposal . values [i]=0 ,w em a yb el e s sc o n c e r n e do nt h ep a y m e n to fr e q u i r e d ETHsf o rt h ep r o p o s a le x e c u t i o n . However, in the unlikely case of certain particular actions that do need ETHs, the issue of properly attributing the associated cost arises. With that, we need to better keep track of ETHcharge for each action and ensure that the transaction sender (who initiates the proposal execution) actually pays the cost. In other words, we do not rely on the governance’s balance of ETHfor the payment. 31/47 PeckShield Audit Report #: 2020-47Confidential Recommendation Properly charge the proposal execution cost by ensuring the amount of accompanying ETH deposit is sufficient. If necessary, we can also return possible leftover in msgValue back to the sender. 210 function execute (uint proposalId )public payable { 211 require (state (proposalId )= = ProposalState .Queued ,"GovernorAlpha ::execute : proposal can only beexecuted ifitisqueued "); 212 Proposal storage proposal =proposals [proposalId ]; 213 proposal .executed =true ; 214 uint msgValue =msg .value ; 215 for (uint i=0 ; i<proposal .targets .length ;i++) { 216 inValue =sub256 (msgValue ,proposal .values [i]) 217 timelock .executeTransaction .value (proposal .values [i])(proposal .targets [i], proposal .values [i],proposal .signatures [i],proposal .calldatas [i], proposal .eta); 218 } 219 emit ProposalExecuted (proposalId ); 220 } Listing 3.23: GovernorAlpha .sol Status This issue has been confirmed. 3.11 Improved Handling of Corner Cases in Proposal Submission •ID: PVE-011 •Severity: Low •Likelihood: Low •Impact: Low•Target: GovernorAlpha •Category: Business Logics [ 10] •CWE subcategory: CWE-837 [ 7] Description As discussed in Section 3.10,Sushi adopts the governance implementation from Compound by accord- ingly adjusting its governance token and related parameters, e.g., quorumVotes ()and proposalThreshold (). Previously, we have examined the payment of proposal execution cost. In this section, we elabo- rate one corner case during a proposal submission, especially regarding the proposer qualification. To be qualified to be proposer, the governance subsystem requires the proposer needs to obtain as u ffi c i e n tn u m b e ro fv o t e s ,i n c l u d i n gf r o mt h ep r o p o s e rh e r s e l fa n do t h e rv o t e r s . T h et h r e s h o l di s specified by proposalThreshold ().I n SushiSwap ,t h i sn u m b e rr e q u i r e st h ev o t e so f 1%ofSUSHI token’s total supply, i.e., SushiToken (sushi ).totalSupply (). 154 function propose (address []memory targets ,uint []memory values ,string []memory signatures ,bytes []memory calldatas ,string memory description )public returns (uint ){ 32/47 PeckShield Audit Report #: 2020-47Confidential 155 require (sushi .getPriorVotes (msg .sender ,sub256 (block .number ,1 ) ) > proposalThreshold () , "GovernorAlpha ::propose :proposer votes below proposal threshold "); 156 require (targets .length == values .length && targets .length == signatures .length && targets .length == calldatas .length ,"GovernorAlpha ::propose :proposal function information arity mismatch "); 157 require (targets .length != 0 , "GovernorAlpha ::propose :must provide actions "); 158 require (targets .length <= proposalMaxOperations () , "GovernorAlpha ::propose :too many actions "); 160 uint latestProposalId =latestProposalIds [msg .sender ]; 161 if(latestProposalId != 0) { 162 ProposalState proposersLatestProposalState =state (latestProposalId ); 163 require (proposersLatestProposalState !=ProposalState .Active ,"GovernorAlpha :: propose :one live proposal per proposer ,found analready active proposal " ); 164 require (proposersLatestProposalState !=ProposalState .Pending ,"GovernorAlpha ::propose :one live proposal per proposer ,found analready pending proposal "); 165 } 166 ... 167 } Listing 3.24: GovernorAlpha .sol If we examine the propose ()logic, when a proposal is being submitted, the governance verifies up- front the qualification of the proposer (line 155):require (sushi .getPriorVotes (msg.sender ,sub256 ( block .number ,1 ) ) > proposalThreshold (), "GovernorAlpha ::propose :proposer votes below proposal threshold ").N o t i c et h a tt h en u m b e ro fp r i o rv o t e si ss t r i c t l yh i g h e rt h a n proposalThreshold (). However, if we check the proposal cancellation logic, i.e., the cancel ()function, a proposal can be canceled (line 225) if the number of prior votes (before current block) is strictly smaller than proposalThreshold ().T h e c o r n e r c a s e o f h a v i n g a n e x a c t n u m b e r p r i o r v o t e s a s t h e t h r e s h o l d , t h o u g h unlikely, is largely unattended. It is suggested to accommodate this particular corner case as well. 220 function cancel (uint proposalId )public { 221 ProposalState state =state (proposalId ); 222 require (state !=ProposalState .Executed ,"GovernorAlpha ::cancel :cannot cancel executed proposal "); 224 Proposal storage proposal =proposals [proposalId ]; 225 require (msg .sender == guardian ||sushi .getPriorVotes (proposal .proposer ,sub256 ( block .number ,1 ) ) < proposalThreshold () , "GovernorAlpha ::cancel :proposer above threshold "); 227 proposal .canceled =true ; 228 for (uint i=0 ; i<proposal .targets .length ;i++) { 229 timelock .cancelTransaction (proposal .targets [i],proposal .values [i],proposal .signatures [i],proposal .calldatas [i],proposal .eta); 230 } 33/47 PeckShield Audit Report #: 2020-47Confidential 232 emit ProposalCanceled (proposalId ); 233 } Listing 3.25: GovernorAlpha .sol Recommendation Accommodate the corner case by also allowing the proposal to be suc- cessfully submitted when the number of proposer’s prior votes is exactly the same as the required threshold, i.e., proposalThreshold (). 154 function propose (address []memory targets ,uint []memory values ,string []memory signatures ,bytes []memory calldatas ,string memory description )public returns (uint ){ 155 require (sushi .getPriorVotes (msg .sender ,sub256 (block .number ,1 ) ) > = proposalThreshold () , "GovernorAlpha ::propose :proposer votes below proposal threshold "); 156 require (targets .length == values .length && targets .length == signatures .length && targets .length == calldatas .length ,"GovernorAlpha ::propose :proposal function information arity mismatch "); 157 require (targets .length != 0 , "GovernorAlpha ::propose :must provide actions "); 158 require (targets .length <= proposalMaxOperations () , "GovernorAlpha ::propose :too many actions "); 160 uint latestProposalId =latestProposalIds [msg .sender ]; 161 if(latestProposalId != 0) { 162 ProposalState proposersLatestProposalState =state (latestProposalId ); 163 require (proposersLatestProposalState !=ProposalState .Active ,"GovernorAlpha :: propose :one live proposal per proposer ,found analready active proposal " ); 164 require (proposersLatestProposalState !=ProposalState .Pending ,"GovernorAlpha ::propose :one live proposal per proposer ,found analready pending proposal "); 165 } 166 ... 167 } Listing 3.26: GovernorAlpha .sol Status This issue has been confirmed. 34/47 PeckShield Audit Report #: 2020-47Confidential 3.12 Inconsistency Between Documented and Implemented SUSHI Inflation •ID: PVE-012 •Severity: Low •Likelihood: Low •Impact: Medium•Target: MasterChef •Category: Business Logics [ 10] •CWE subcategory: CWE-837 [ 7] Description According to the documentation of SushiSwap [ 24],”At every block, 100 SUSHI tokens will be created. These tokens will be equally distributed to the stakers of each of the supported pools.” As part of the audit process, we examine and identify possible inconsistency between the doc- umentation/white paper and the implementation. Based on the smart contract code, there is a system-wide configuration, i.e., sushiPerBlock .T h i s p a r t i c u l a r p a r a m e t e r i s i n i t i a l i z e d a s 100when the contract is being deployed and it can only be changed at the contract’s constructor. The ini- tialized number of 100seems consistent with the documentation and sushiPerBlock is fixed forever (and cannot be adjusted even via a governance process). Af u r t h e ra n a l y s i sa b o u tt h e SUSHI inflation logic (implemented in updatePool ())s h o w sc e r t a i n inconsistency that needs to better articulated and clarified. For elaboration, we show the related code snippet below. 182 //Update reward variables ofthe given pool tobeup-to-date . 183 function updatePool (uint256 _pid )public { 184 PoolInfo storage pool =poolInfo [_pid ]; 185 if(block .number <= pool .lastRewardBlock ){ 186 return ; 187 } 188 uint256 lpSupply =pool .lpToken .balanceOf (address (this )); 189 if(lpSupply == 0 ) { 190 pool .lastRewardBlock =block .number ; 191 return ; 192 } 193 uint256 multiplier =getMultiplier (pool .lastRewardBlock ,block .number ); 194 uint256 sushiReward =multiplier .mul(sushiPerBlock ).mul(pool .allocPoint ).div( totalAllocPoint ); 195 sushi .mint (devaddr ,sushiReward .div(10)) ; 196 sushi .mint (address (this ),sushiReward ); 197 pool .accSushiPerShare =pool .accSushiPerShare .add(sushiReward .mul(1e12).div( lpSupply )); 198 pool .lastRewardBlock =block .number ; 199 } Listing 3.27: MasterChef .sol 35/47 PeckShield Audit Report #: 2020-47Confidential The sushiPerBlock parameter indeed controls the number of SUSHI rewards that are distributed to various pools (line 196). However, it further adds another 10% of the calculated sushiReward to the development team-controlled account (line 195). With that, the number of new SUSHI rewards per block should be 110,n o t 100! Recommendation Clarify the inconsistency by clearly stating the number of new SUSHI tokens is110,a n dt h ed e v e l o p m e n tt e a mw i l lb er e c e i v i n ga b o u t 1_11 = 9 .09% of total SUSHI distribution. Status This issue has been confirmed. 3.13 Non-Governance-Based Admin of TimeLock And Related Privileges •ID: PVE-013 •Severity: High •Likelihood: Medium •Impact: High•Target: Timelock •Category: Security Features [ 9] •CWE subcategory: CWE-287 [ 2] Description InSushiSwap , the governance contract, i.e., GovernorAlpha ,p l a y sac r i t i c a lr o l ei ng o v e r n i n ga n d regulating the system-wide operations (e.g., pool addition, reward adjustment, and migrator setting). It also has the privilege to control or govern the life-cycle of proposals and enact on them regarding their submissions, executions, and revocations. With great privilege comes great responsibility. Our analysis shows that the governance contract is indeed privileged, but it currently has NOT been deployed yet to govern the MasterChef contract that is the central to SushiSwap .I n t h e f o l l o w i n g , w e e x a m i n e t h e c u r r e n t s t a t e o f p r i v i l e g e a s s i g n m e n t inSushiSwap . Specifically, we kept track of the current deployment of various contracts in SushiSwap and the results are shown in Table 3.1. Table 3.1: Current Contract Deployment of SushiSwap Contract Address Owner/Admin SUSHIToken 0x6b3595068778dd592e39a122f4f5a5cf09c90fe2 0xc2edad668740f1aa35e4d8f227fb8e17dca888cd MasterChef 0xc2edad668740f1aa35e4d8f227fb8e17dca888cd 0x9a8541ddf3a932a9a922b607e9cf7301f1d47bd1 Timelock 0x9a8541ddf3a932a9a922b607e9cf7301f1d47bd1 0xf942dba4159cb61f8ad88ca4a83f5204e8f4a6bd Deployer/DevAddr 0xf942dba4159cb61f8ad88ca4a83f5204e8f4a6bd Migrator 0x0000000000000000000000000000000000000000 36/47 PeckShield Audit Report #: 2020-47Confidential To further elaborate, we draw the admin chain based on the current deployment of SushiSwap in Figure 3.2.W ee m p h a s i z et h a tt h e SUSHI token contract is properly administrated by the MasterChef contract that is authorized to mint new SUSHI tokens per block. The MasterChef contract is adminis- trated by the Timelock contract and this administration is also appropriate as the Timelock contract is indeed authorized to configure various aspects of MasterChef ,i n c l u d i n gt h ea d d i t i o no fn e wp o o l s , the share adjustment of each existing pool (if necessary), and the setting of the upcoming migrator contract. Figure 3.2: The Current Admin Chain of SushiSwap However, it is worrisome that Timelock is not governed by the GovernorAlpha governance contract. Our analysis shows that the current Timelock control is controlled by an externally-owned account (EOA) address, i.e., 0xf942dba4159cb61f8ad88ca4a83f5204e8f4a6bd .T h i s E O A a d d r e s s h a p p e n s t o b e the same deployer address of SushiSwap and also configured as the development team address, i.e., devaddr .W i t h a p r o p e r c o m m u n i t y - b a s e d o n - c h a i n g o v e r n a n c e , i t s a d m i n c h a i n s h o u l d b e d e p i c t e d as follows: Figure 3.3: The Expected Admin Chain of SushiSwap In the meantime, we notice the GovernorAlpha contract has a special guardian that has certain privilege, including the cancellation of ongoing proposals that has not been executed yet. However, since this contract has not been deployed and this part of logic is directly borrowed from Compound without any modification, we do not expand further.1 1Interested readers are referred to the original GovernorAlpha audit report conducted by OpenZeppelin and the 37/47 PeckShield Audit Report #: 2020-47Confidential Recommendation Promptly transfer the admin privilege of Timelock to the intended GovernorAlpha governance contract. And activate the normal on-chain community-based governance life-cycle and ensure the intended trustless nature and high-quality distributed governance. Status This issue has been confirmed. 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.6.0; instead of pragma solidity >=0.6.0; . Moreover, we strongly suggest not to use experimental Solidity features or third-party unaudited libraries. If necessary, refactor current code base to only use stable features or trusted libraries. 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. report can be accessed in the following link: https://blog.openzeppelin.comcompound-alpha-governance-system-audit . 38/47 PeckShield Audit Report #: 2020-47Confidential 4|Conclusion In this audit, we thoroughly analyzed the SushiSwap design and implementation. Overall, SushiSwap presents an evolutional improvement based on Uniswap and provide extra incentives to liquidity providers. Our impression is that the current code base is well organized and those identified issues are promptly confirmed and fixed. The main concern, however, is related to the current deployment as its privilege management is not under the control of community-based governance. 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. 39/47 PeckShield Audit Report #: 2020-47Confidential 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 [ 15,16, 17,18,21]. •Result: Not found •Severity: Critical 40/47 PeckShield Audit Report #: 2020-47Confidential 5.1.5 Reentrancy •Description: Reentrancy [ 23]i sa ni s s u ew h e nc o d ec a nc a l lb a c ki n t oy o u rc o n t r a c ta n dc h a n g e 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 41/47 PeckShield Audit Report #: 2020-47Confidential 5.1.10 Unchecked External Call •Description: Whether the contract has any external call without 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 Send Instead Of Transfer •Description: Whether the contract uses send instead 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 42/47 PeckShield Audit Report #: 2020-47Confidential 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: Whether the contract use the deprecated tx.origin to perform the authorization. •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[] ,a st h el a t t e ri saw a s t eo f space. •Result: Not found •Severity: Low 43/47 PeckShield Audit Report #: 2020-47Confidential 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], which may break the the execution if the function implementation does NOT follow its declaration (e.g., no return in implementing transfer() of ERC20 tokens). •Result: Not found •Severity: Low 44/47 PeckShield Audit Report #: 2020-47Confidential References [1]axic. Enforcing ABI length checks for return data from calls can be breaking. https://github. com/ethereum/solidity/issues/4116 . [2]MITRE. CWE-287: Improper Authentication. https://cwe.mitre.org/data/definitions/287.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-708: Incorrect Ownership Assignment. https://cwe.mitre.org/data/definitions/ 708.html . [6]MITRE. CWE-770: Allocation of Resources Without Limits or Throttling. https://cwe.mitre. org/data/definitions/770.html . [7]MITRE. CWE-837: Improper Enforcement of a Single, Unique Action. https://cwe.mitre.org/ data/definitions/837.html . [8]MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html . [9]MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html . 45/47 PeckShield Audit Report #: 2020-47Confidential [10] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html . [11] MITRE. CWE CATEGORY: Concurrency. https://cwe.mitre.org/data/definitions/557.html . [12] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html . [13] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [14] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology . [15] PeckShield. ALERT: New batchOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018- 10299). https://www.peckshield.com/2018/04/22/batchOverflow/ . [16] PeckShield. New burnOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 11239). https://www.peckshield.com/2018/05/18/burnOverflow/ . [17] PeckShield. New multiOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 10706). https://www.peckshield.com/2018/05/10/multiOverflow/ . [18] PeckShield. New proxyOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018-10376). https://www.peckshield.com/2018/04/25/proxyOverflow/ . [19] PeckShield. PeckShield Inc. https://www.peckshield.com . [20] PeckShield. Uniswap/Lendf.Me Hacks: Root Cause and Loss Analysis. https://medium.com/ @peckshield/uniswap-lendf-me-hacks-root-cause-and-loss-analysis-50f3263dcc09 . [21] PeckShield. Your Tokens Are Mine: A Suspicious Scam Token in A Top Exchange. https: //www.peckshield.com/2018/04/28/transferFlaw/ . [22] David Siegel. Understanding The DAO Attack. https://www.coindesk.com/ understanding-dao-hack-journalists . 46/47 PeckShield Audit Report #: 2020-47Confidential [23] Solidity. Warnings of Expressions and Control Structures. http://solidity.readthedocs.io/en/ develop/control-structures.html . [24] SushiSwap Team. The SushiSwap Project: An Evolution of Uniswap With SUSHI Tokenomics. https://medium.com/sushiswap/the-sushiswap-project-c4049ea9941e . 47/47 PeckShield Audit Report #: 2020-47
Issues Count of Minor/Moderate/Major/Critical - Minor: 5 - Moderate: 5 - Major: 2 - Critical: 0 Minor Issues - Constructor Mismatch (5.1.1): Missing initialization of the _owner variable in the constructor. - Ownership Takeover (5.1.2): Missing checks on the msg.sender in the transferOwnership() function. - Redundant Fallback Function (5.1.3): Unnecessary fallback function that can be removed. - Overflows & Underflows (5.1.4): Missing checks on the overflow and underflow of the _totalSupply variable. - Reentrancy (5.1.5): Missing checks on the reentrancy of the transfer() function. Moderate Issues - Money-Giving Bug (5.1.6): Missing checks on the msg.value in the transfer() function. - Blackhole (5.1.7): Missing checks on the msg.value in the transferFrom() function. - Unauthorized Self-Destruct (5.1.8): Missing checks on the msg.sender in the selfdestruct Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 2 Major: 0 Critical: 0 Minor Issues: 5.1.11 Gasless Send: Problem (one line with code reference): Gasless send is used in the code, which may lead to reentrancy attack. (line 590) Fix (one line with code reference): Use transfer instead of send. (line 590) 5.1.12 Send Instead Of Transfer: Problem (one line with code reference): Send is used instead of transfer, which may lead to reentrancy attack. (line 590) Fix (one line with code reference): Use transfer instead of send. (line 590) 5.1.13 Costly Loop: Problem (one line with code reference): Costly loop is used in the code, which may lead to DoS attack. (line 590) Fix (one line with code reference): Use a more efficient loop. (line 590) 5.1.14 (Unsafe) Use Of Untrusted Libraries: Problem (one line with code reference): Unsafe use of untrusted libraries is Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 4 Major: 4 Critical: 0 Minor Issues: 2.a Problem: Constructor Mismatch (Table 1.3) 2.b Fix: Make Visibility Level Explicit Moderate Issues: 3.a Problem: Ownership Takeover (Table 1.3) 3.b Fix: Making Type Inference Explicit 4.a Problem: Redundant Fallback Function (Table 1.3) 4.b Fix: Adhering To Function Declaration Strictly 5.a Problem: Overflows & Underflows (Table 1.3) 5.b Fix: Following Other Best Practices Major Issues: 6.a Problem: Reentrancy (Table 1.3) 6.b Fix: Avoiding Use of Variadic Byte Array 7.a Problem: Money-Giving Bug (Table 1.3) 7.b Fix: Using Fixed Compiler Version 8.a Problem: Blackhole (Table 1.3) 8.b Fix: Making Visibility Level Explicit 9.a Problem: Un
pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract CommunityVault is Ownable { IERC20 private _bond; constructor (address bond) public { _bond = IERC20(bond); } event SetAllowance(address indexed caller, address indexed spender, uint256 amount); function setAllowance(address spender, uint amount) public onlyOwner { _bond.approve(spender, amount); emit SetAllowance(msg.sender, spender, amount); } } // SPDX-License-Identifier: Apache-2.0 // SWC-Floating Pragma: L2 pragma solidity ^0.6.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract YieldFarm { // lib using SafeMath for uint; using SafeMath for uint128; // constants uint public constant TOTAL_DISTRIBUTED_AMOUNT = 800000; uint public constant NR_OF_EPOCHS = 25; // state variables // addreses address private _usdc; address private _susd; address private _dai; address private _communityVault; // contracts IERC20 private _bond; IStaking private _staking; // fixed size array holdings total number of epochs + 1 (epoch 0 doesn't count) uint[] private epochs = new uint[](NR_OF_EPOCHS + 1); // pre-computed variable for optimization. total amount of bond tokens to be distributed on each epoch uint private _totalAmountPerEpoch; // id of last init epoch, for optimization purposes moved from struct to a single id. uint128 public lastInitializedEpoch; // state of user harvest epoch mapping(address => uint128) private lastEpochIdHarvested; uint public epochDuration; // init from staking contract uint public epochStart; // init from staking contract // events event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue); event Harvest(address indexed user, uint128 indexed epochId, uint256 amount); // constructor constructor(address bondTokenAddress, address usdc, address susd, address dai, address stakeContract, address communityVault) public { _bond = IERC20(bondTokenAddress); _usdc = usdc; _susd = susd; _dai = dai; _staking = IStaking(stakeContract); _communityVault = communityVault; epochStart = _staking.epoch1Start(); epochDuration = _staking.epochDuration(); _totalAmountPerEpoch = TOTAL_DISTRIBUTED_AMOUNT.mul(10**18).div(NR_OF_EPOCHS); } // public methods // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } // SWC-DoS With Block Gas Limit: L71 for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId.sub(lastEpochIdHarvested[msg.sender]), totalDistributedValue); if (totalDistributedValue > 0) { _bond.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; } function harvest (uint128 epochId) external returns (uint){ // checks for requested epoch require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 25"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); if (userReward > 0) { _bond.transferFrom(_communityVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; } // views // calls to the staking smart contract to retrieve the epoch total pool size function getPoolSize(uint128 epochId) external view returns (uint) { return _getPoolSize(epochId); } function getCurrentEpoch() external view returns (uint) { return _getEpochId(); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint){ return lastEpochIdHarvested[msg.sender]; } // internal methods function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); } function _harvest (uint128 epochId) internal returns (uint) { // try to initialize an epoch. if it can't it fails // if it fails either user either a BarnBridge account will init not init epochs if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user last harvested epoch lastEpochIdHarvested[msg.sender] = epochId; // compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer) // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } return _totalAmountPerEpoch .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); } function _getPoolSize(uint128 epochId) internal view returns (uint) { // retrieve stable coins total staked in epoch uint valueUsdc = _staking.getEpochPoolSize(_usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground uint valueSusd = _staking.getEpochPoolSize(_susd, epochId); uint valueDai = _staking.getEpochPoolSize(_dai, epochId); return valueUsdc.add(valueSusd).add(valueDai); } function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){ // retrieve stable coins total staked per user in epoch uint valueUsdc = _staking.getEpochUserBalance(userAddress, _usdc, epochId).mul(10 ** 12); // for usdc which has 6 decimals add a 10**12 to get to a common ground uint valueSusd = _staking.getEpochUserBalance(userAddress, _susd, epochId); uint valueDai = _staking.getEpochUserBalance(userAddress, _dai, epochId); return valueUsdc.add(valueSusd).add(valueDai); } // compute epoch id from blocktimestamp and epochstart date function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1)); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract YieldFarmLP { // lib using SafeMath for uint; using SafeMath for uint128; // constants uint public constant TOTAL_DISTRIBUTED_AMOUNT = 2000000; uint public constant NR_OF_EPOCHS = 100; // state variables // addreses address private _uniLP; address private _communityVault; // contracts IERC20 private _bond; IStaking private _staking; uint[] private epochs = new uint[](NR_OF_EPOCHS + 1); uint private _totalAmountPerEpoch; uint128 public lastInitializedEpoch; mapping(address => uint128) private lastEpochIdHarvested; uint public epochDuration; // init from staking contract uint public epochStart; // init from staking contract // events event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue); event Harvest(address indexed user, uint128 indexed epochId, uint256 amount); // constructor constructor(address bondTokenAddress, address uniLP, address stakeContract, address communityVault) public { _bond = IERC20(bondTokenAddress); _uniLP = uniLP; _staking = IStaking(stakeContract); _communityVault = communityVault; epochDuration = _staking.epochDuration(); epochStart = _staking.epoch1Start() + epochDuration; _totalAmountPerEpoch = TOTAL_DISTRIBUTED_AMOUNT.mul(10**18).div(NR_OF_EPOCHS); } // public methods // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue); if (totalDistributedValue > 0) { _bond.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; } function harvest (uint128 epochId) external returns (uint){ // checks for requested epoch require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 100"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); if (userReward > 0) { _bond.transferFrom(_communityVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; } // views // calls to the staking smart contract to retrieve the epoch total pool size function getPoolSize(uint128 epochId) external view returns (uint) { return _getPoolSize(epochId); } function getCurrentEpoch() external view returns (uint) { return _getEpochId(); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint){ return lastEpochIdHarvested[msg.sender]; } // internal methods function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); } function _harvest (uint128 epochId) internal returns (uint) { // try to initialize an epoch. if it can't it fails // if it fails either user either a BarnBridge account will init not init epochs if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user state for last harvested lastEpochIdHarvested[msg.sender] = epochId; // compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer) // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } return _totalAmountPerEpoch .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); } function _getPoolSize(uint128 epochId) internal view returns (uint) { // retrieve unilp token balance return _staking.getEpochPoolSize(_uniLP, _stakingEpochId(epochId)); } function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){ // retrieve unilp token balance per user per epoch return _staking.getEpochUserBalance(userAddress, _uniLP, _stakingEpochId(epochId)); } // compute epoch id from blocktimestamp and epochstart date function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1)); } // get the staking epoch which is 1 epoch more function _stakingEpochId(uint128 epochId) pure internal returns (uint128) { return epochId + 1; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract YieldFarmBond { // lib using SafeMath for uint; using SafeMath for uint128; // constants uint public constant TOTAL_DISTRIBUTED_AMOUNT = 60000; uint public constant NR_OF_EPOCHS = 12; uint128 public constant EPOCHS_DELAYED_FROM_STAKING_CONTRACT = 4; // state variables // addreses address private _poolTokenAddress; address private _communityVault; // contracts IERC20 private _bond; IStaking private _staking; uint[] private epochs = new uint[](NR_OF_EPOCHS + 1); uint private _totalAmountPerEpoch; uint128 public lastInitializedEpoch; mapping(address => uint128) private lastEpochIdHarvested; uint public epochDuration; // init from staking contract uint public epochStart; // init from staking contract // events event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue); event Harvest(address indexed user, uint128 indexed epochId, uint256 amount); // constructor constructor(address bondTokenAddress, address stakeContract, address communityVault) public { _bond = IERC20(bondTokenAddress); _poolTokenAddress = bondTokenAddress; _staking = IStaking(stakeContract); _communityVault = communityVault; epochDuration = _staking.epochDuration(); epochStart = _staking.epoch1Start() + epochDuration.mul(EPOCHS_DELAYED_FROM_STAKING_CONTRACT); _totalAmountPerEpoch = TOTAL_DISTRIBUTED_AMOUNT.mul(10**18).div(NR_OF_EPOCHS); } // public methods // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue); if (totalDistributedValue > 0) { _bond.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; } function harvest (uint128 epochId) external returns (uint){ // checks for requested epoch require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 12"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); if (userReward > 0) { _bond.transferFrom(_communityVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; } // views // calls to the staking smart contract to retrieve the epoch total pool size function getPoolSize(uint128 epochId) external view returns (uint) { return _getPoolSize(epochId); } function getCurrentEpoch() external view returns (uint) { return _getEpochId(); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint){ return lastEpochIdHarvested[msg.sender]; } // internal methods function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); } function _harvest (uint128 epochId) internal returns (uint) { // try to initialize an epoch. if it can't it fails // if it fails either user either a BarnBridge account will init not init epochs if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user state for last harvested lastEpochIdHarvested[msg.sender] = epochId; // compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer) // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } return _totalAmountPerEpoch .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); } // retrieve _poolTokenAddress token balance function _getPoolSize(uint128 epochId) internal view returns (uint) { return _staking.getEpochPoolSize(_poolTokenAddress, _stakingEpochId(epochId)); } // retrieve _poolTokenAddress token balance per user per epoch function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){ return _staking.getEpochUserBalance(userAddress, _poolTokenAddress, _stakingEpochId(epochId)); } // compute epoch id from block.timestamp and epochStart date function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1)); } // get the staking epoch function _stakingEpochId(uint128 epochId) pure internal returns (uint128) { return epochId + EPOCHS_DELAYED_FROM_STAKING_CONTRACT; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; contract Staking is ReentrancyGuard { using SafeMath for uint256; uint128 constant private BASE_MULTIPLIER = uint128(1 * 10 ** 18); // timestamp for the epoch 1 // everything before that is considered epoch 0 which won't have a reward but allows for the initial stake uint256 public epoch1Start; // duration of each epoch uint256 public epochDuration; // holds the current balance of the user for each token mapping(address => mapping(address => uint256)) private balances; struct Pool { uint256 size; bool set; } // for each token, we store the total pool size mapping(address => mapping(uint256 => Pool)) private poolSize; // a checkpoint of the valid balance of a user for an epoch struct Checkpoint { uint128 epochId; uint128 multiplier; uint256 startBalance; uint256 newDeposits; } // balanceCheckpoints[user][token][] mapping(address => mapping(address => Checkpoint[])) private balanceCheckpoints; mapping(address => uint128) private lastWithdrawEpochId; event Deposit(address indexed user, address indexed tokenAddress, uint256 amount); event Withdraw(address indexed user, address indexed tokenAddress, uint256 amount); event ManualEpochInit(address indexed caller, uint128 indexed epochId, address[] tokens); event EmergencyWithdraw(address indexed user, address indexed tokenAddress, uint256 amount); constructor (uint256 _epoch1Start, uint256 _epochDuration) public { epoch1Start = _epoch1Start; epochDuration = _epochDuration; } /* * Stores `amount` of `tokenAddress` tokens for the `user` into the vault */ function deposit(address tokenAddress, uint256 amount) public nonReentrant { require(amount > 0, "Staking: Amount must be > 0"); IERC20 token = IERC20(tokenAddress); uint256 allowance = token.allowance(msg.sender, address(this)); require(allowance >= amount, "Staking: Token allowance too small"); balances[msg.sender][tokenAddress] = balances[msg.sender][tokenAddress].add(amount); token.transferFrom(msg.sender, address(this), amount); // epoch logic uint128 currentEpoch = getCurrentEpoch(); uint128 currentMultiplier = currentEpochMultiplier(); if (!epochIsInitialized(tokenAddress, currentEpoch)) { address[] memory tokens = new address[](1); tokens[0] = tokenAddress; manualEpochInit(tokens, currentEpoch); } // update the next epoch pool size Pool storage pNextEpoch = poolSize[tokenAddress][currentEpoch + 1]; pNextEpoch.size = token.balanceOf(address(this)); pNextEpoch.set = true; Checkpoint[] storage checkpoints = balanceCheckpoints[msg.sender][tokenAddress]; uint256 balanceBefore = getEpochUserBalance(msg.sender, tokenAddress, currentEpoch); // if there's no checkpoint yet, it means the user didn't have any activity // we want to store checkpoints both for the current epoch and next epoch because // if a user does a withdraw, the current epoch can also be modified and // we don't want to insert another checkpoint in the middle of the array as that could be expensive if (checkpoints.length == 0) { checkpoints.push(Checkpoint(currentEpoch, currentMultiplier, 0, amount)); // next epoch => multiplier is 1, epoch deposits is 0 checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, amount, 0)); } else { uint256 last = checkpoints.length - 1; // the last action happened in an older epoch (e.g. a deposit in epoch 3, current epoch is >=5) if (checkpoints[last].epochId < currentEpoch) { uint128 multiplier = computeNewMultiplier( getCheckpointBalance(checkpoints[last]), BASE_MULTIPLIER, amount, currentMultiplier ); checkpoints.push(Checkpoint(currentEpoch, multiplier, getCheckpointBalance(checkpoints[last]), amount)); checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, balances[msg.sender][tokenAddress], 0)); } // the last action happened in the previous epoch else if (checkpoints[last].epochId == currentEpoch) { checkpoints[last].multiplier = computeNewMultiplier( getCheckpointBalance(checkpoints[last]), checkpoints[last].multiplier, amount, currentMultiplier ); checkpoints[last].newDeposits = checkpoints[last].newDeposits.add(amount); checkpoints.push(Checkpoint(currentEpoch + 1, BASE_MULTIPLIER, balances[msg.sender][tokenAddress], 0)); } // the last action happened in the current epoch else { if (last >= 1 && checkpoints[last - 1].epochId == currentEpoch) { checkpoints[last - 1].multiplier = computeNewMultiplier( getCheckpointBalance(checkpoints[last - 1]), checkpoints[last - 1].multiplier, amount, currentMultiplier ); checkpoints[last - 1].newDeposits = checkpoints[last - 1].newDeposits.add(amount); } checkpoints[last].startBalance = balances[msg.sender][tokenAddress]; } } uint256 balanceAfter = getEpochUserBalance(msg.sender, tokenAddress, currentEpoch); poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.add(balanceAfter.sub(balanceBefore)); emit Deposit(msg.sender, tokenAddress, amount); } /* * Removes the deposit of the user and sends the amount of `tokenAddress` back to the `user` */ function withdraw(address tokenAddress, uint256 amount) public nonReentrant { require(balances[msg.sender][tokenAddress] >= amount, "Staking: balance too small"); balances[msg.sender][tokenAddress] = balances[msg.sender][tokenAddress].sub(amount); IERC20 token = IERC20(tokenAddress); token.transfer(msg.sender, amount); // epoch logic uint128 currentEpoch = getCurrentEpoch(); lastWithdrawEpochId[tokenAddress] = currentEpoch; if (!epochIsInitialized(tokenAddress, currentEpoch)) { address[] memory tokens = new address[](1); tokens[0] = tokenAddress; manualEpochInit(tokens, currentEpoch); } // update the pool size of the next epoch to its current balance Pool storage pNextEpoch = poolSize[tokenAddress][currentEpoch + 1]; pNextEpoch.size = token.balanceOf(address(this)); pNextEpoch.set = true; Checkpoint[] storage checkpoints = balanceCheckpoints[msg.sender][tokenAddress]; uint256 last = checkpoints.length - 1; // note: it's impossible to have a withdraw and no checkpoints because the balance would be 0 and revert // there was a deposit in an older epoch (more than 1 behind [eg: previous 0, now 5]) but no other action since then if (checkpoints[last].epochId < currentEpoch) { checkpoints.push(Checkpoint(currentEpoch, BASE_MULTIPLIER, balances[msg.sender][tokenAddress], 0)); poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.sub(amount); } // there was a deposit in the `epochId - 1` epoch => we have a checkpoint for the current epoch else if (checkpoints[last].epochId == currentEpoch) { checkpoints[last].startBalance = balances[msg.sender][tokenAddress]; checkpoints[last].newDeposits = 0; checkpoints[last].multiplier = BASE_MULTIPLIER; poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.sub(amount); } // there was a deposit in the current epoch else { Checkpoint storage currentEpochCheckpoint = checkpoints[last - 1]; uint256 balanceBefore = getCheckpointEffectiveBalance(currentEpochCheckpoint); // in case of withdraw, we have 2 branches: // 1. the user withdraws less than he added in the current epoch // 2. the user withdraws more than he added in the current epoch (including 0) if (amount < currentEpochCheckpoint.newDeposits) { uint128 avgDepositMultiplier = uint128( balanceBefore.sub(currentEpochCheckpoint.startBalance).mul(BASE_MULTIPLIER).div(currentEpochCheckpoint.newDeposits) ); currentEpochCheckpoint.newDeposits = currentEpochCheckpoint.newDeposits.sub(amount); currentEpochCheckpoint.multiplier = computeNewMultiplier( currentEpochCheckpoint.startBalance, BASE_MULTIPLIER, currentEpochCheckpoint.newDeposits, avgDepositMultiplier ); } else { currentEpochCheckpoint.startBalance = currentEpochCheckpoint.startBalance.sub( amount.sub(currentEpochCheckpoint.newDeposits) ); currentEpochCheckpoint.newDeposits = 0; currentEpochCheckpoint.multiplier = BASE_MULTIPLIER; } uint256 balanceAfter = getCheckpointEffectiveBalance(currentEpochCheckpoint); poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.sub(balanceBefore.sub(balanceAfter)); checkpoints[last].startBalance = balances[msg.sender][tokenAddress]; } emit Withdraw(msg.sender, tokenAddress, amount); } /* * manualEpochInit can be used by anyone to initialize an epoch based on the previous one * This is only applicable if there was no action (deposit/withdraw) in the current epoch. * Any deposit and withdraw will automatically initialize the current and next epoch. */ function manualEpochInit(address[] memory tokens, uint128 epochId) public { require(epochId <= getCurrentEpoch(), "can't init a future epoch"); for (uint i = 0; i < tokens.length; i++) { Pool storage p = poolSize[tokens[i]][epochId]; if (epochId == 0) { p.size = uint256(0); p.set = true; } else { require(!epochIsInitialized(tokens[i], epochId), "Staking: epoch already initialized"); require(epochIsInitialized(tokens[i], epochId - 1), "Staking: previous epoch not initialized"); p.size = poolSize[tokens[i]][epochId - 1].size; p.set = true; } } emit ManualEpochInit(msg.sender, epochId, tokens); } function emergencyWithdraw(address tokenAddress) public { require((getCurrentEpoch() - lastWithdrawEpochId[tokenAddress]) >= 10, "At least 10 epochs must pass without success"); uint256 totalUserBalance = balances[msg.sender][tokenAddress]; require(totalUserBalance > 0, "Amount must be > 0"); balances[msg.sender][tokenAddress] = 0; IERC20 token = IERC20(tokenAddress); token.transfer(msg.sender, totalUserBalance); emit EmergencyWithdraw(msg.sender, tokenAddress, totalUserBalance); } /* * Returns the valid balance of a user that was taken into consideration in the total pool size for the epoch * A deposit will only change the next epoch balance. * A withdraw will decrease the current epoch (and subsequent) balance. */ function getEpochUserBalance(address user, address token, uint128 epochId) public view returns (uint256) { Checkpoint[] storage checkpoints = balanceCheckpoints[user][token]; // if there are no checkpoints, it means the user never deposited any tokens, so the balance is 0 if (checkpoints.length == 0 || epochId < checkpoints[0].epochId) { return 0; } uint min = 0; uint max = checkpoints.length - 1; // shortcut for blocks newer than the latest checkpoint == current balance if (epochId >= checkpoints[max].epochId) { return getCheckpointEffectiveBalance(checkpoints[max]); } // binary search of the value in the array while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].epochId <= epochId) { min = mid; } else { max = mid - 1; } } return getCheckpointEffectiveBalance(checkpoints[min]); } /* * Returns the amount of `token` that the `user` has currently staked */ function balanceOf(address user, address token) public view returns (uint256) { return balances[user][token]; } /* * Returns the id of the current epoch derived from block.timestamp */ function getCurrentEpoch() public view returns (uint128) { if (block.timestamp < epoch1Start) { return 0; } return uint128((block.timestamp - epoch1Start) / epochDuration + 1); } /* * Returns the total amount of `tokenAddress` that was locked from beginning to end of epoch identified by `epochId` */ function getEpochPoolSize(address tokenAddress, uint128 epochId) public view returns (uint256) { // Premises: // 1. it's impossible to have gaps of uninitialized epochs // - any deposit or withdraw initialize the current epoch which requires the previous one to be initialized if (epochIsInitialized(tokenAddress, epochId)) { return poolSize[tokenAddress][epochId].size; } // epochId not initialized and epoch 0 not initialized => there was never any action on this pool if (!epochIsInitialized(tokenAddress, 0)) { return 0; } // epoch 0 is initialized => there was an action at some point but none that initialized the epochId // which means the current pool size is equal to the current balance of token held by the staking contract IERC20 token = IERC20(tokenAddress); return token.balanceOf(address(this)); } /* * Returns the percentage of time left in the current epoch */ function currentEpochMultiplier() public view returns (uint128) { uint128 currentEpoch = getCurrentEpoch(); uint256 currentEpochEnd = epoch1Start + currentEpoch * epochDuration; uint256 timeLeft = currentEpochEnd - block.timestamp; uint128 multiplier = uint128(timeLeft * BASE_MULTIPLIER / epochDuration); return multiplier; } function computeNewMultiplier(uint256 prevBalance, uint128 prevMultiplier, uint256 amount, uint128 currentMultiplier) public pure returns (uint128) { uint256 prevAmount = prevBalance.mul(prevMultiplier).div(BASE_MULTIPLIER); uint256 addAmount = amount.mul(currentMultiplier).div(BASE_MULTIPLIER); uint128 newMultiplier = uint128(prevAmount.add(addAmount).mul(BASE_MULTIPLIER).div(prevBalance.add(amount))); return newMultiplier; } /* * Checks if an epoch is initialized, meaning we have a pool size set for it */ function epochIsInitialized(address token, uint128 epochId) public view returns (bool) { return poolSize[token][epochId].set; } function getCheckpointBalance(Checkpoint memory c) internal pure returns (uint256) { return c.startBalance.add(c.newDeposits); } function getCheckpointEffectiveBalance(Checkpoint memory c) internal pure returns (uint256) { return getCheckpointBalance(c).mul(c.multiplier).div(BASE_MULTIPLIER); } }
Coinbae Audit Barnbridge YieldFarmBond Audit January 2021 Contents 1Introduction, 2 Scope, 5 Synopsis, 7 Medium severity, 8 Low Severity, 9 Team, 11 Introduction Audit: In January 2021 Coinbae’s audit report division performed an audit for the Barnbridge YieldFarmBond Contract. https://etherscan.io/address/0x3FdFb07472ea4771E1aD66FD3b87b26 5Cd4ec112#code Barnbridge: BarnBridge is the first tokenized risk protocol. Before the advent of smart contract technology it was close to impossible to track & attribute yield to a divided allotment of capital, trustlessly & transparently, to provide hedges against any and all fluctuations. Conceptually, you can build derivative products from any type of market driven fluctuation to hedge various risks. Examples include, but are not limited to, interest rate sensitivity, fluctuations in underlying market price, fluctuations in predictive market odds, fluctuations in default rates across mortgages, fluctuations in commodity prices, and a seemingly infinite number of market based fluctuations to hedge a particular position. As described in Barnbridges whitepaper . 2Introduction Overview: Information: Name: Barnbridge YieldFarmBond Contract Pool, Asset or Contract address: https://etherscan.io/address/0x3FdFb07472ea4771E1aD66FD3b87b26 5Cd4ec112#code Supply: Current: 1,044,486 BOND Explorers: https://etherscan.io/address/0x3FdFb07472ea4771E1aD66FD3b87b26 5Cd4ec112#code Websites: https://barnbridge.com/ 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 can be 0.6.0 --> 0.8.0 these versions have for instance 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 by your contract. And set it as a fixed parameter not a floating pragma. 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 220 1 1 0Identified Confirmed Critical High Medium Low Analysis: https://etherscan.io/address/0x3FdFb07472ea4771E1aD66FD3b87b26 5Cd4ec112#code Risk: Low 7Audit Report Medium severity: Coding best practices DoS With Block Gas Limit (SWC-128) When smart contracts are deployed or functions inside them are called, the execution of these actions always requires a certain amount of gas, based of how much computation is needed to complete them. The Ethereum network specifies a block gas limit and the sum of all transactions included in a block can not exceed the threshold. Programming patterns that are harmless in centralized applications can lead to Denial of Service conditions in smart contracts when the cost of executing a function exceeds the block gas limit. Modifying an array of unknown size, that increases in size over time, can lead to such a Denial of Service condition. Affected lines: 1. for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { [#61] 8Audit Report Low severity: Solidity style guide naming convention issues found A floating pragma is set SWC-103: The current pragma Solidity directive is ""^0.6.12"". 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 . Affected lines: 1. pragma solidity ^0.6.0; [#2] 9Contract Flow 10 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 11Coinbae Audit Disclaimer Coinbae audit is not a security warranty, investment advice, or an endorsement of the Barnbridge protocol. 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 Barnbridge protocol put in place a bug bounty program to encourage further analysis of the smart contract by other third parties. 12Conclusion We performed the procedures as laid out in the scope of the audit and there were 2 findings, 1 medium and 1 low. 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: 2 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Outdated compiler version 2.b Fix: Update the contracts to the latest supported version of solidity by your contract. And set it as a fixed parameter not a floating pragma. Moderate Issues: 3.a Problem: Solidity assert violation 3.b Fix: Use Solidity AssertionFailed event 4.a Problem: Incorrect ERC20 implementation 4.b Fix: Implement ERC20 correctly Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Use of right-to-left-override control character. 2.b Fix: Remove the control character. Moderate Issues: 3.a Problem: Shadowing of built-in symbol. 3.b Fix: Rename the symbol. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 1 - Major: 0 - Critical: 0 Moderate 3.a Problem: Best practice issues (no security risk) 3.b Fix: No fix required Observations - The audit was performed as per the scope - There were 2 findings, 1 medium and 1 low - The medium risk issues do not pose a security risk Conclusion - Overall risk level is low - Recommendation to put in place a bug bounty program to encourage further analysis of the smart contract by other third parties
pragma solidity 0.6.6; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; contract Timelock is ReentrancyGuard { using SafeMath for uint256; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 1 days; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; bool public admin_initialized; mapping(bytes32 => bool) public queuedTransactions; // delay_ in seconds constructor(address admin_, uint256 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; } receive() external payable {} function setDelay(uint256 delay_) external { 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() external { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) external { // 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, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external 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, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external { 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 _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } function executeTransaction( address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta ) external payable nonReentrant 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, _getRevertMsg(returnData)); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } }
FairLaunch, Token, Vault & Workers Smart Contract Audit Report Prepared for Meow Finance __________________________________ Date Issued: Oct 25, 2021 Project ID: AUDIT2021021 Version: v1.0 Confidentiality Level: Public Public ________ Report Information Project ID AUDIT2021021 Version v1.0 Client Meow Finance Project FairLaunch, Token, Vault & Workers Auditor(s) Suvicha Buakhom Peeraphut Punsuwan Author Suvicha Buakhom Reviewer Weerawat Pawanawiwat Confidentiality Level Public Version History Version Date Description Author(s) 1.0 Oct 25, 2021 Full report Suvicha Buakhom 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 2 2.1. Project Introduction 2 2.2. Scope 3 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. Denial of Service in Beneficiary Mechanism 10 5.2. Use of Upgradable Contract Design 12 5.3. Centralized Control of State Variable 13 5.4. Improper Reward Calculation in MeowMining 15 5.5. Improper Reward Calculation in FeeDistribute 18 5.6. Improper Compliance to the Tokenomics 21 5.7. Denial of Service on Minting Cap Exceeding 24 5.8. Improper Delegation Handling in Token Burning 27 5.9. Design Flaw in massUpdatePool() Function 30 5.10. Transaction Ordering Dependence 31 5.11. Missing Input Validation (maxReinvestBountyBps) 34 5.12. Denial of Service in reinvest() Function 37 5.13. Missing Input Validation of preShare and lockShare Values 41 5.14. Outdated Compiler Version 44 5.15. Insufficient Logging for Privileged Functions 45 5.16. Unavailability of manualMint() Function 48 5.17. Improper Access Control for Development Fund Locking 50 5.18. Improper Access Control for burnFrom() Function 52 5.19. Unsupported Design for Deflationary Token 54 5.20. Improper Function Visibility 59 6. Appendix 61 6.1. About Inspex 61 Public ________ 6.2. References 62 Public ________ 1. Executive Summary As requested by Meow Finance, Inspex team conducted an audit to verify the security posture of the FairLaunch, Token, Vault & Workers smart contracts between Sep 29, 2021 and Oct 5, 2021. During the audit, Inspex team examined all smart contracts and the overall operation within the scope to understand the overview of FairLaunch, Token, Vault & Workers 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. 1.1. Audit Result In the initial audit, Inspex found 3 high, 4 medium, 6 low, 2 very low, and 5 info-severity issues. With the project team’s prompt response, 3 high, 4 medium, 5 low, 2 very low and 5 info-severity issues were resolved in the reassessment, while 1 low-severity issue was acknowledged by the team. Therefore, Inspex trusts that FairLaunch, Token, Vault & Workers smart contracts have sufficient protections to be safe for public use. However, in the long run, Inspex suggests resolving all issues found in this report. 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 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: AUDIT2021021 (v1.0) 1 Public ________ 2. Project Overview 2.1. Project Introduction Meow Finance is a DeFi leveraged yield farming and lending protocol on the Fantom chain. They aim to provide users an experience of yield farming with their desired leverage, built on the Fantom framework where it builds and connects Ethereum-compatible blockchain networks. Fairlaunch is a mechanism to distribute $MEOW to the users who deposit or stake tokens to the platform. Vault & Workers are components of lending, leveraged yield farming, auto compounding, and farming position managing. On the Vault, users can lend their tokens and open leveraged yield farming positions. Workers use the rewards obtained from farming for reinvestment and managing the users’ opened positions. Scope Information: Project Name FairLaunch, Token, Vault & Workers Website https://meowfinance.org/ Smart Contract Type Ethereum Smart Contract Chain Fantom Opera Programming Language Solidity Audit Information: Audit Method Whitebox Audit Date Sep 29, 2021 - Oct 5, 2021 Reassessment Date Oct 18, 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: AUDIT2021021 (v1.0) 2 Public ________ 2.2. Scope The following smart contracts were audited and reassessed by Inspex in detail: Initial Audit: (Commit: 4a4f13efaf5e5fbed74c0ed23b665751e655d715) Contract Location (URL) Vault https://github.com/meow-finance/Meow-Finance/blob/4a4f13efaf/contracts/pr otocol/Vault.sol TripleSlopeModel https://github.com/meow-finance/Meow-Finance/tree/4a4f13efaf/contracts/pr otocol/interest-models MeowMining https://github.com/meow-finance/Meow-Finance/blob/4a4f13efaf/contracts/to ken/MeowMining.sol SpookyswapWorker https://github.com/meow-finance/Meow-Finance/blob/4a4f13efaf/contracts/pr otocol/workers/SpookyswapWorker.sol MeowToken https://github.com/meow-finance/Meow-Finance/blob/4a4f13efaf/contracts/to ken/MeowToken.sol FeeDistribute https://github.com/meow-finance/Meow-Finance/blob/4a4f13efaf/contracts/to ken/FeeDistribute.sol DevelopmentFund https://github.com/meow-finance/Meow-Finance/blob/4a4f13efaf/contracts/to ken/DevelopmentFund.sol Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 3 Public ________ Reassessment: (Commit: 0912b0099114939c3452117c1a25de82cfb6cd75) Contract Location (URL) Vault https://github.com/meow-finance/Meow-Finance/blob/0912b00991/contracts/ protocol/Vault.sol TripleSlopeModel https://github.com/meow-finance/Meow-Finance/tree/0912b00991/contracts/ protocol/interest-models MeowMining https://github.com/meow-finance/Meow-Finance/blob/0912b00991/contracts/ token/MeowMining.sol SpookyswapWorker https://github.com/meow-finance/Meow-Finance/blob/0912b00991/contracts/ protocol/workers/SpookyswapWorker.sol MeowToken https://github.com/meow-finance/Meow-Finance/blob/0912b00991/contracts/ token/MeowToken.sol FeeDistribute https://github.com/meow-finance/Meow-Finance/blob/0912b00991/contracts/ token/FeeDistribute.sol DevelopmentFund https://github.com/meow-finance/Meow-Finance/blob/0912b00991/contracts/ token/DevelopmentFund.sol The assessment scope covers only the in-scope smart contracts and the smart contracts that they are inherited from. The s e t S p o o k y F e e ( ) function has been added in the reassessment commit, and is outside of the audit scope. The Meow Finance team has clarified that this function is used to change the swapping fee when the fee rate on the SpookySwap platform changes. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.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: AUDIT2021021 (v1.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 Insufficient Logging for Privileged Functions Invoking of Unreliable Smart Contract Advanced Business Logic Flaw Ownership Takeover Broken Access Control Broken Authentication Use of Upgradable Contract Design Improper Kill-Switch Mechanism Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 6 Public ________ Improper Front-end Integration Insecure Smart Contract Initiation 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: AUDIT2021021 (v1.0) 7 Public ________ 4. Summary of Findings From the assessments, Inspex has found 20 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: AUDIT2021021 (v1.0) 8 Public ________ The information and status of each issue can be found in the following table: ID Title Category Severity Status IDX-001 Denial of Service in Beneficiary Mechanism Advanced High Resolved IDX-002 Use of Upgradable Contract Design Advanced High Resolved * IDX-003 Centralized Control of State Variable General High Resolved * IDX-004 Improper Reward Calculation in MeowMining Advanced Medium Resolved IDX-005 Improper Reward Calculation in FeeDistribute Advanced Medium Resolved IDX-006 Improper Compliance to the Tokenomics Advanced Medium Resolved IDX-007 Denial of Service on Minting Cap Exceeding Advanced Medium Resolved IDX-008 Improper Delegation Handling in Token Burning Advanced Low Resolved IDX-009 Design Flaw in massUpdatePool() Function General Low Acknowledged IDX-010 Transaction Ordering Dependence General Low Resolved IDX-011 Missing Input Validation (maxReinvestBountyBps) Advanced Low Resolved IDX-012 Denial of Service in reinvest() Function Advanced Low Resolved IDX-013 Missing Input Validation of preShare and lockShare Values Advanced Low Resolved IDX-014 Outdated Compiler Version General Very Low Resolved IDX-015 Insufficient Logging for Privileged Functions General Very Low Resolved IDX-016 Unavailability of manualMint() Function Advanced Info Resolved IDX-017 Improper Access Control for Development Fund Locking Advanced Info Resolved IDX-018 Improper Access Control for burnFrom() Function Advanced Info Resolved IDX-019 Unsupported Design for Deflationary Token Advanced Info Resolved IDX-020 Improper Function Visibility Best Practice Info Resolved * The mitigations or clarifications by Meow Finance can be found in Chapter 5. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 9 Public ________ 5. Detailed Findings Information 5.1. Denial of Service in Beneficiary Mechanism ID IDX-001 Target MeowMining Category Advanced Smart Contract Vulnerability CWE CWE-755: Improper Handling of Exceptional Conditions Risk Severity: High Impact: High The victim won't be able to execute the d e p o s i t ( ) function of the M e o w M i n i n g contract, causing disruption of service and loss of reputation to the platform. Likelihood: Medium This attack can be done by anyone to any address without any prior deposit; however, there is no direct benefit for the attacker, resulting in low motivation for the attack. Status Resolved Meow Finance team has resolved this issue by editing the w i t h d r a w ( ) function as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.1.1. Description In the M e o w M i n i n g contract, users can deposit tokens specified in each pool to gain $MEOW reward using the d e p o s i t ( ) function. The _ f o r variable in the function can be controlled by the users, allowing the deposit by one address for another beneficiary address to gain the reward. The first address that deposits for each _ f o r address will be set in the u s e r . f u n d e d B y in line 199, preventing others from depositing or withdrawing for that beneficiary due to the condition in line 195. MeowMining.sol 1 8 8 1 8 9 1 9 0 1 9 1 1 9 2 1 9 3 1 9 4 1 9 5 1 9 6 1 9 7 f u n c t i o n d e p o s i t ( a d d r e s s _ f o r , u i n t 2 5 6 _ p i d , u i n t 2 5 6 _ a m o u n t ) e x t e r n a l n o n R e e n t r a n t { P o o l I n f o s t o r a g e p o o l = p o o l I n f o [ _ p 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 [ _ p i d ] [ _ f o r ] ; i f ( u s e r . f u n d e d B y ! = a d d r e s s ( 0 ) ) r e q u i r e ( u s e r . f u n d e d B y = = m s g . s e n d e r , " M e o w M i n i n g : : d e p o s i t : : b a d s o f . " ) ; r e q u i r e ( p o o l . s t a k e T o k e n ! = a d d r e s s ( 0 ) , " M e o w M i n i n g : : d e p o s i t : : n o t a c c e p t d e p o s i t . " ) ; u p d a t e P o o l ( _ p i d ) ; Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 10 Public ________ 1 9 8 1 9 9 2 0 0 2 0 1 2 0 2 2 0 3 2 0 4 i f ( u s e r . a m o u n t > 0 ) _ h a r v e s t ( _ f o r , _ p i d ) ; i f ( u s e r . f u n d e d B y = = a d d r e s s ( 0 ) ) u s e r . f u n d e d B y = m s g . s e n d e r ; I E R C 2 0 ( p o o l . s t a k e T o k e n ) . s a f e T r a n sferFrom( a d d r e s s ( m s g . s e n d e r ) , a d d r e s s ( t h i s ) , _ a m o u n t ) ; u s e r . a m o u n t = u s e r . a m o u n t . a d d ( _ a mount); u s e r . r e w a r d D e b t = u s e r . a m o u n t . m u l ( p o o l . a c c M e o w P e r S hare).div(ACC_MEOW_PRECISION); e m i t D e p o s i t ( m s g . s e n d e r , _ p i d , _ a m o u n t ) ; } This behavior can be abused by others to disrupt the use of the smart contract. Malicious actors can perform deposits with 0 a m o u n t for another _ f o r address without prior any deposit, preventing that _ f o r address from being used by the actual owner. 5.1.2. Remediation Inspex suggests allowing the _ f o r address to perform withdrawal to return the funds to the f u n d e d B y address and set the f u n d e d B y to a d d r e s s ( 0 ) when u s e r . a m o u n t is 0, for example: MeowMining.sol 2 1 9 2 2 0 2 2 1 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 f u n c t i o n _ w i t h d r a w ( a d d r e s s _ f o r , u i n t 2 5 6 _ p i d , u i n t 2 5 6 _ a m o u n t ) i n t e r n a l { P o o l I n f o s t o r a g e p o o l = p o o l I n f o [ _ p 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 [ _ p i d ] [ _ f o r ] ; r e q u i r e ( u s e r . f u n d e d B y = = m s g . s e n d e r | | m s g . s e n d e r = = _ f o r , " M e o w M i n i n g : : w i t h d r a w : : o n l y f u n der." ) ; r e q u i r e ( u s e r . a m o u n t > = _ a m o u n t , " M e o w M i n i n g : : w i t h d r a w : : n o t g o o d . " ) ; u p d a t e P o o l ( _ p i d ) ; _ h a r v e s t ( _ f o r , _ p i d ) ; u s e r . a m o u n t = u s e r . a m o u n t . s u b ( _ a mount); u s e r . r e w a r d D e b t = u s e r . a m o u n t . m u l ( p o o l . a c c M e o w P e r S hare).div(ACC_MEOW_PRECISION); i f ( u s e r . a m o u n t = = 0 ) u s e r . f u n d e d B y = a d d r e s s ( 0 ) ; i f ( p o o l . s t a k e T o k e n ! = a d d r e s s ( 0 ) ) { I E R C 2 0 ( p o o l . s t a k e T o k e n ) . s a f e T r a n sfer( a d d r e s s ( u s e r . f u n d e d B y ) , _ a m o u n t ) ; } e m i t W i t h d r a w ( u s e r . f u n d e d B y , _ p i d , u s er.amount); } Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 11 Public ________ 5.2. Use of Upgradable Contract Design ID IDX-002 Target Vault SpookyswapWorker Category Advanced Smart Contract Vulnerability CWE CWE-284: Improper Access Control Risk Severity: High Impact: High The logic of the affected contracts can be arbitrarily changed. This allows the proxy owner to perform malicious actions e.g., stealing the user funds anytime they want. Likelihood: Medium This action can be performed by the proxy owner without any restriction. Status Resolved * Meow Finance team has confirmed that the team will mitigate this issue by implementing the timelock mechanism when deploying the smart contracts to mainnet. The users will be able to monitor the timelock for the upgrade of the contract and act accordingly if it is being misused. At the time of reassessment, the contracts are not deployed yet, so the use of timelock is not confirmed. For the platform users, please verify that the timelock is properly deployed before using this platform. 5.2.1. Description Smart contracts are designed to be used as agreements that cannot be changed forever. When a smart contract is upgraded, the agreement can be changed from what was previously agreed upon. As the V a u l t and the S p o o k y s w a p W o r k e r smart contracts are upgradable, the logic of them could be modified by the owner anytime, making the smart contracts untrustworthy. 5.2.2. Remediation Inspex suggests deploying the contracts without the proxy pattern or any solution that can make the smart contracts upgradable. However, if upgradability is needed, Inspex suggests mitigating this issue by implementing a timelock mechanism with a sufficient length of time to delay the changes. This allows the platform users to monitor the timelock and be notified of the potential changes being done on the smart contracts. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 12 Public ________ 5.3. Centralized Control of State Variable ID IDX-003 Target Vault TripleSlopeModel MeowMining SpookyswapWorker MeowToken FeeDistribute DevelopmentFund Category General Smart Contract Vulnerability CWE CWE-710: Improper Adherence to Coding Standard Risk Severity: High Impact: High The controlling authorities can change the critical state variables to gain additional profit. Thus, it is unfair to the other users and can cause significant monetary loss to the users. Likelihood: Medium There is nothing to restrict the changes from being done; however, these actions can only be performed by the contract owner. Status Resolved * Meow Finance team has confirmed that the team will implement the timelock mechanism when deploying the smart contracts to mainnet. The users will be able to monitor the timelock for the execution of critical functions and act accordingly if they are being misused. At the time of the reassessment, the contracts are not deployed yet, so the use of timelock is not confirmed. For the platform users, please verify that the timelock is properly deployed before using this platform. 5.3.1. Description Critical state variables can be updated at any time by the controlling authorities. Changes in these variables can cause impacts to the users, so the users should accept or be notified before these changes are effective. However, as the contract is not yet deployed, there is potentially no constraint to prevent the authorities from modifying these variables without notifying the users. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 13 Public ________ The controllable privileged state update functions are as follows: File Contract Function Modifier Vault.sol (L:454) Vault updateConfig() onlyOwner Vault.sol (L:460) Vault updateDebtToken() onlyOwner Vault.sol (L:471) Vault setMeowMiningPoolId() onlyOwner Vault.sol (L:479) Vault withdrawReserve() onlyOwner Vault.sol (L:486) Vault reduceReserve() onlyOwner TripleSlopeModel.sol (L:29) TripleSlopeModel setParams() onlyOwner MeowMining.sol (L:107) MeowMining setMeowPerSecond() onlyOwner MeowMining.sol (L:113) MeowMining addPool() onlyOwner MeowMining.sol (L:126) MeowMining setPool() onlyOwner MeowMining.sol (L:140) MeowMining manualMint() onlyOwner SpookyswapWorker.sol (L:288) SpookyswapWorker setReinvestBountyBps() onlyOwner SpookyswapWorker.sol (L:298) SpookyswapWorker setMaxReinvestBountyBps() onlyOwner SpookyswapWorker.sol (L:309) SpookyswapWorker setStrategyOk() onlyOwner SpookyswapWorker.sol (L:319) SpookyswapWorker setReinvestorOk() onlyOwner SpookyswapWorker.sol (L:329) SpookyswapWorker setCriticalStrategies() onlyOwner FeeDistribute.sol (L:52) FeeDistribute setParams() onlyOwner FeeDistribute.sol (L:62) FeeDistribute addPool() onlyOwner 5.3.2. Remediation In the ideal case, the critical state variables should not be modifiable to keep the integrity of the smart contract. However, if modifications are needed, Inspex suggests limiting the use of these functions via the following options: - Implementing community-run governance to control the use of these functions - Using a T i m e l o c k contract to delay the changes for a sufficient amount of time Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 14 Public ________ 5.4. Improper Reward Calculation in MeowMining ID IDX-004 Target MeowMining Category Advanced Smart Contract Vulnerability CWE CWE-840: Business Logic Errors Risk Severity: Medium Impact: Medium The reward of the pool that has the same staking token as the reward token will be slightly lower than what it should be, resulting in monetary loss for the users and loss of reputation for the platform. Likelihood: Medium It is likely that the pool with the same staking token as the reward token will be added by the contract owner. Status Resolved Meow Finance team has resolved this issue by checking the value of _ s t a k e T o k e n as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.4.1. Description In the M e o w M i n i n g contract, a new staking pool can be added using the a d d P o o l ( ) function. The staking token for the new pool is defined using the _ s t a k e T o k e n variable; however, there is no additional checking whether the _ s t a k e T o k e n is the same as the reward token ($MEOW) or not. MeowMining.sol 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 f u n c t i o n a d d P o o l ( u i n t 2 5 6 _ a l l o c P o i n t , a d d r e s s _ s t a k e T o k e n ) e x t e r n a l o n l y O w n e r { m a s s U p d a t e P o o l s ( ) ; r e q u i r e ( _ s t a k e T o k e n ! = a d d r e s s ( 0 ) , " M e o w M i n i n g : : a d d P o o l : : n o t Z E R O a d d r e s s . " ) ; r e q u i r e ( ! i s P o o l E x i s t [ _ s t a k e T o k e n ] , " M e o w M i n i n g : : a d d P o o l : : s t a k e T o k e n d u p l i c a t e . " ) ; u i n t 2 5 6 l a s t R e w a r d T i m e = b l o c k . t i m e s t a m p > s t a r t T i m e ? b l o c k . t i m e s t a m p : s t a r t T i m e ; t o t a l A l l o c P o i n t = t o t a l A l l o c P o i n t.add(_allocPoint); p o o l I n f o . p u s h ( P o o l I n f o ( { s t a k e T o k e n : _ s t a k e T o k en, allocPoint: _allocPoint, l a s t R e w a r d T i m e : l a s t R e w a r d T i m e , accMeowPerShare: 0 } ) ) ; i s P o o l E x i s t [ _ s t a k e T o k e n ] = t r u e ; } Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 15 Public ________ When the _ s t a k e T o k e n is the same token as $MEOW, the reward calculation for that pool in the u p d a t e P o o l ( ) function can be incorrect. This is because the current balance of the _ s t a k e T o k e n in the contract is used in the calculation of the reward. Since the _ s t a k e T o k e n is the same token as the reward, the reward minted to the contract will inflate the value of s t a k e T o k e n S u p p l y , causing the reward of that pool to be less than what it should be. MeowMining.sol 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 1 7 5 1 7 6 1 7 7 1 7 8 1 7 9 1 8 0 1 8 1 1 8 2 1 8 3 1 8 4 1 8 5 f u n c t i o n u p d a t e P o o l ( u i n t 2 5 6 _ p i d ) p u b l i c { P o o l I n f o s t o r a g e p o o l = p o o l I n f o [ _ p i d ] ; i f ( b l o c k . t i m e s t a m p > p o o l . l a s t R e w a r d T i m e ) { u i n t 2 5 6 s t a k e T o k e n S u p p l y = I E R C 2 0 ( p o o l . s takeToken) . b a l a n c e O f ( a d d r e s s ( t h i s ) ) ; i f ( s t a k e T o k e n S u p p l y > 0 & & t o t a l A l l o c P o i n t > 0 ) { u i n t 2 5 6 t i m e = b l o c k . t i m e s t a m p . s u b ( p o o l . l a s t R e w a r d T i m e ) ; u i n t 2 5 6 m e o w R e w a r d = t i m e . m u l ( m e o w P e r S e c o n d ) . m u l ( p o o l .allocPoint).div(totalAllocPoint); / / E v e r y 1 1 . 4 2 8 6 M e o w m i n t e d w i l l mint 1 M e o w f o r d e v , c o m e f r o m 8 0 / 7 = 1 1 . 4 2 8 6 u s e 1 0 , 0 0 0 t o a v o id floating. u i n t 2 5 6 d e v f u n d = m e o w R e w a r d . m u l ( 1 0 0 0 0 ) . d i v ( 1 1 4 2 8 6 ) ; m e o w . m i n t ( a d d r e s s ( t h i s ) , d e v f u n d ) ; m e o w . m i n t ( a d d r e s s ( t h i s ) , m e o w R e w a r d ) ; s a f e M e o w T r a n s f e r ( d e v a d d r , d e v f u n d.mul(preShare).div( 1 0 0 0 0 ) ) ; d e v e l o p m e n t F u n d . l o c k ( d e v f u n d . m u l (lockShare).div( 1 0 0 0 0 ) ) ; p o o l . a c c M e o w P e r S h a r e = p o o l . a c c M eowPerShare.add(meowReward . m u l ( A C C _ M E O W _ P R E C I S I O N ) . d i v ( s t a k e T o k e n S u p p l y ) ) ; } p o o l . l a s t R e w a r d T i m e = b l o c k . t i m e s t a m p ; } } 5.4.2. Remediation Inspex suggests checking the value of the _ s t a k e T o k e n in the a d d P o o l ( ) function to prevent the pool with the same staking token as the reward token from being added, for example: MeowMining.sol 1 1 3 1 1 4 1 1 5 1 1 6 1 1 7 f u n c t i o n a d d P o o l ( u i n t 2 5 6 _ a l l o c P o i n t , a d d r e s s _ s t a k e T o k e n ) e x t e r n a l o n l y O w n e r { m a s s U p d a t e P o o l s ( ) ; r e q u i r e ( _ s t a k e T o k e n ! = a d d r e s s ( 0 ) , " M e o w M i n i n g : : a d d P o o l : : n o t Z E R O a d d r e s s . " ) ; r e q u i r e ( _ s t a k e T o k e n ! = m e o w , " M e o w M i n i n g : : a d d P o o l : : t h e _ s t a k e T o k e n i s m e o w . " ) ; r e q u i r e ( ! i s P o o l E x i s t [ _ s t a k e T o k e n ] , " M e o w M i n i n g : : a d d P o o l : : s t a k e T o k e n Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 16 Public ________ 1 1 8 1 1 9 1 2 0 1 2 1 1 2 2 1 2 3 1 2 4 d u p l i c a t e . " ) ; u i n t 2 5 6 l a s t R e w a r d T i m e = b l o c k . t i m e s t a m p > s t a r t T i m e ? b l o c k . t i m e s t a m p : s t a r t T i m e ; t o t a l A l l o c P o i n t = t o t a l A l l o c P o i n t.add(_allocPoint); p o o l I n f o . p u s h ( P o o l I n f o ( { s t a k e T o k e n : _ s t a k e T o k en, allocPoint: _allocPoint, l a s t R e w a r d T i m e : l a s t R e w a r d T i m e , accMeowPerShare: 0 } ) ) ; i s P o o l E x i s t [ _ s t a k e T o k e n ] = t r u e ; } However, if the pool with the same staking token as the reward token is required, Inspex suggests minting the reward token to another contract to prevent the amount of the staked token from being mixed up with the reward token, or store the amount of the token staked to use in the reward calculation. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 17 Public ________ 5.5. Improper Reward Calculation in FeeDistribute ID IDX-005 Target FeeDistribute Category Advanced Smart Contract Vulnerability CWE CWE-840: Business Logic Errors Risk Severity: Medium Impact: Medium The reward of the pool that has the same staking token as the reward token will be slightly higher than what it should be, so not all users will be able to claim the reward or withdraw their funds, resulting in monetary loss for some users and loss of reputation for the platform. Likelihood: Medium It is likely that the pool with the same staking token as the reward token will be added by the contract owner. Status Resolved Meow Finance team has resolved this issue by checking the value of the _ r e w a r d T o k e n as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.5.1. Description In the F e e D i s t r i b u t e contract, a new staking pool can be added using the a d d P o o l ( ) function. The reward token for the new pool is defined using the _ r e w a r d T o k e n variable; however, there is no additional checking whether the _ r e w a r d T o k e n is already used as _ s t a k e T o k e n or not. FeeDistribute.sol 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 f u n c t i o n a d d P o o l ( a d d r e s s _ s t a k e T o k e n , a d d r e s s _ r e w a r d T o k e n ) e x t e r n a l o n l y O w n e r { m a s s U p d a t e P o o l s ( ) ; r e q u i r e ( _ s t a k e T o k e n ! = a d d r e s s ( 0 ) , " F e e D i s t r i b u t e : : a d d P o o l : : n o t Z E R O a d d r e s s . " ) ; r e q u i r e ( ! i s P o o l E x i s t [ _ r e w a r d T o k e n ] , " F e e D i s t r i b u t e : : a d d P o o l : : p o o l e x i s t . " ) ; p o o l I n f o . p u s h ( P o o l I n f o ( { s t a k e T o k e n : _ s t a k e T o k e n , r e w a r d T o k e n : _ r e w a r d T o k e n , d e p o s i t e d A m o u n t : 0 , l a t e s t R e w a r d A m o u n t : 0 , t o t a l R e w a r d A m o u n t : 0 , r e w a r d P e r S h a r e : 0 Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 18 Public ________ 1 3 1 4 1 5 1 6 } ) ) ; i s P o o l E x i s t [ _ r e w a r d T o k e n ] = t r u e ; } When the _ r e w a r d T o k e n is already used as _ s t a k e T o k e n , the reward calculation for that pool in the u p d a t e P o o l ( ) function can be incorrect. This is because the current balance of the _ r e w a r d T o k e n in the contract is used in the calculation of the reward. Since the _ r e w a r d T o k e n is already used as _ s t a k e T o k e n , the token staked to the contract will inflate the value of _ r e w a r d B a l a n c e , causing the reward of that pool to be more than what it should be. FeeDistribute.sol 8 8 8 9 9 0 9 1 9 2 9 3 9 4 9 5 9 6 9 7 9 8 9 9 1 0 0 f u n c t i o n u p d a t e P o o l ( u i n t 2 5 6 _ p i d ) p u b l i c { P o o l I n f o s t o r a g e p o o l = p o o l I n f o [ _ p i d ] ; u i n t 2 5 6 _ r e w a r d B a l a n c e = I E R C 2 0 ( p o o l . r e w ardToken).balanceOf( a d d r e s s ( t h i s ) ) ; u i n t 2 5 6 _ p e n d i n g R e w a r d = _ r e w a r d B a l a n c e . sub(pool.latestRewardAmount); u i n t 2 5 6 _ t o t a l D e p o s i t e d = p o o l . d e p o s i t e d Amount; i f ( _ p e n d i n g R e w a r d ! = 0 & & _ t o t a l D e p o s i t e d ! = 0 ) { u i n t 2 5 6 _ p e n d i n g R e w a r d P e r S h a r e = _ p e n d i n gReward.mul(PRECISION) . d i v ( _ t o t a l D e p o s i t e d ) ; p o o l . t o t a l R e w a r d A m o u n t = p o o l . t o talRewardAmount.add(_pendingReward); p o o l . l a t e s t R e w a r d A m o u n t = _ r e w a r dBalance; p o o l . r e w a r d P e r S h a r e = p o o l . r e w a r dPerShare.add(_pendingRewardPerShare); } } With the inflated reward, some users may not be able to claim their reward or withdraw their funds from the contract. 5.5.2. Remediation Inspex suggests checking the value of the _ r e w a r d T o k e n in the a d d P o o l ( ) function to prevent the pool with the same staking token as the reward token from being added, for example: FeeDistribute.sol 6 2 6 3 6 4 6 5 6 6 m a p p i n g ( a d d r e s s = > b o o l ) p u b l i c i s S t a k e T o k e n ; f u n c t i o n a d d P o o l ( a d d r e s s _ s t a k e T o k e n , a d d r e s s _ r e w a r d T o k e n ) e x t e r n a l o n l y O w n e r { m a s s U p d a t e P o o l s ( ) ; r e q u i r e ( _ s t a k e T o k e n ! = a d d r e s s ( 0 ) , " F e e D i s t r i b u t e : : a d d P o o l : : n o t Z E R O a d d r e s s . " ) ; Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 19 Public ________ 6 7 6 8 6 9 7 0 7 1 7 2 7 3 7 4 7 5 7 6 7 7 7 8 7 9 8 0 8 1 8 2 8 3 r e q u i r e ( ! i s P o o l E x i s t [ _ r e w a r d T o k e n ] , " F e e D i s t r i b u t e : : a d d P o o l : : p o o l e x i s t . " ) ; r e q u i r e ( ! i s S t a k e T o k e n [ _ r e w a r d T o k e n ] , " F e e D i s t r i b u t e : : a d d P o o l : : r e w a r d t o k e n i s a l r e a d y u s e d a s s t a k e t o k e n . " ) ; r e q u i r e ( ! i s P o o l E x i s t [ _ s t a k e T o k e n ] , " F e e D i s t r i b u t e : : a d d P o o l : : s t a k e t o k e n i s a l r e a d y u s e d a s r e w a r d t o k e n " ) ; r e q u i r e ( _ s t a k e T o k e n ! = _ r e w a r d T o k e n , " F e e D i s t r i b u t e : : a d d P o o l : : _ s t a k e T o k e n t o k e n s a m e a s _ r e w a r d t o k e n " ) ; p o o l I n f o . p u s h ( P o o l I n f o ( { s t a k e T o k e n : _ s t a k e T o k e n , r e w a r d T o k e n : _ r e w a r d T o k e n , d e p o s i t e d A m o u n t : 0 , l a t e s t R e w a r d A m o u n t : 0 , t o t a l R e w a r d A m o u n t : 0 , r e w a r d P e r S h a r e : 0 } ) ) ; i s P o o l E x i s t [ _ r e w a r d T o k e n ] = t r u e ; i s S t a k e T o k e n [ _ s t a k e T o k e n ] = t r u e ; } However, if the pool with the same staking token as the reward token is required, Inspex suggests storing the reward token in another contract to prevent the amount of the staked token from being mixed up with the reward token. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 20 Public ________ 5.6. Improper Compliance to the Tokenomics ID IDX-006 Target MeowToken MeowMining Category Advanced Smart Contract Vulnerability CWE CWE-840: Business Logic Errors Risk Severity: Medium Impact: Medium The $MEOW token allocated for the distribution in the M e o w M i n i n g contract can be decreased due to the use of the m a n u a l M i n t ( ) function, making it different from the tokenomics announced to the users. The reward distribution period will end early and cause the users to earn less reward than they should. This can result in monetary loss for the users and reputation damage for the platform. Likelihood: Medium Only the contract owner can use the m a n u a l M i n t ( ) function, but there is no restriction to prevent the owner from using it. Status Resolved Meow Finance team has resolved this issue by removing the manual minting functionality as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.6.1. Description The $MEOW has a limit of 250m maximum supply, and it is separated into 3 portions as follows: 1. m e o w M i n i n g is the portion that is reserved for the distribution in the M e o w M i n i n g contract, allocated as 80% of max supply. 2. r e s e r v e is the portion that is pre-minted for the cost of the platform, allocated as 13% of max supply. Portions 1 and 2 are defined in the M e o w T o k e n contract at lines 13 and 15. MeowToken.sol 1 0 1 1 1 2 1 3 1 4 1 5 / / M a x T o t a l S u p p l y 2 5 0 m . u i n t 2 5 6 p r i v a t e c o n s t a n t C A P = 2 5 0 0 0 0 0 0 0 e 1 8 ; / / M e o w m i n i n g 2 0 0 m ( 8 0 % o f 2 5 0 m ). u i n t 2 5 6 p u b l i c m e o w M i n i n g = 2 0 0 0 0 0 0 0 0 e 1 8 ; / / M e o w r e s e r v e 3 2 . 5 m ( 1 3 % o f 2 5 0m). u i n t 2 5 6 p u b l i c r e s e r v e = 3 2 5 0 0 0 0 0 e 1 8 ; 3. d e v f u n d is the portion that is reserved for the development fund, allocated as 7% of max supply. This portion is defined in the M e o w M i n i n g contract at line 176. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 21 Public ________ MeowMining.sol 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 1 7 5 1 7 6 1 7 7 1 7 8 1 7 9 1 8 0 1 8 1 1 8 2 1 8 3 1 8 4 1 8 5 f u n c t i o n u p d a t e P o o l ( u i n t 2 5 6 _ p i d ) p u b l i c { P o o l I n f o s t o r a g e p o o l = p o o l I n f o [ _ p i d ] ; i f ( b l o c k . t i m e s t a m p > p o o l . l a s t R e w a r d T i m e ) { u i n t 2 5 6 s t a k e T o k e n S u p p l y = I E R C 2 0 ( p o o l . s t a k e T o k e n ) . b a l a n c e O f( a d d r e s s ( t h i s ) ) ; i f ( s t a k e T o k e n S u p p l y > 0 & & t o t a l A l l o c P o i n t > 0 ) { u i n t 2 5 6 t i m e = b l o c k . t i m e s t a m p . s u b ( p o o l . l a s t R e w a r d T i m e ) ; u i n t 2 5 6 m e o w R e w a r d = t i m e . m u l ( m e o w P e r S e c o n d ) . m u l ( p o o l .allocPoint).div(totalAllocPoint); / / E v e r y 1 1 . 4 2 8 6 M e o w m i n t e d w i l l mint 1 M e o w f o r d e v , c o m e f r o m 8 0 / 7 = 1 1 . 4 2 8 6 u s e 1 0 , 0 0 0 t o a v o id floating. u i n t 2 5 6 d e v f u n d = m e o w R e w a r d . m u l ( 1 0 0 0 0 ) . d i v ( 1 1 4 2 8 6 ) ; m e o w . m i n t ( a d d r e s s ( t h i s ) , d e v f u n d ) ; m e o w . m i n t ( a d d r e s s ( t h i s ) , m e o w R e w a r d ) ; s a f e M e o w T r a n s f e r ( d e v a d d r , d e v f u n d.mul(preShare).div( 1 0 0 0 0 ) ) ; d e v e l o p m e n t F u n d . l o c k ( d e v f u n d . m u l (lockShare).div( 1 0 0 0 0 ) ) ; p o o l . a c c M e o w P e r S h a r e = p o o l . a c c M e o w P e r S h a r e . a d d ( m e o w R e w ard.mul(ACC_MEOW_PRECISION).div(stakeTokenSuppl y ) ) ; } p o o l . l a s t R e w a r d T i m e = b l o c k . t i m e s t a m p ; } } In addition to the predetermined proportions, tokens can be generated in addition to the specified proportions by manual minting. MeowToken.sol 1 4 0 1 4 1 1 4 2 1 4 3 1 4 4 1 4 5 1 4 6 f u n c t i o n m a n u a l M i n t ( a d d r e s s _ t o , u i n t 2 5 6 _ a m o u n t ) p u b l i c o n l y O w n e r { r e q u i r e ( b l o c k . t i m e s t a m p > = m a n u a l M i n t A l l o w e d A f t e r , " M e o w T o k e n : : m a n u a l M i n t : : m a n u a l M i n t n o t a l l o w e d y e t . " ) ; r e q u i r e ( _ a m o u n t < = ( c a n M a n u a l M i n t ( ) ) , " M e o w T o k e n : : m a n u a l M i n t : : m a n u a l m i n t l i m i t e x c e e d e d . " ) ; m a n u a l M i n t A l l o w e d A f t e r = b l o c k . t i m e s t a m p . a d d ( m i n i m u m T i m e B e t w e e n M a n u a l M i n t); m a n u a l M i n t e d = m a n u a l M i n t e d . a d d ( _amount); m i n t ( _ t o , _ a m o u n t ) ; } The amount of tokens that comes from manual minting will be deducted from the m e o w M i n i n g portion. MeowToken.sol 3 5 3 6 3 7 f u n c t i o n c a n M a n u a l M i n t ( ) p u b l i c v i e w r e t u r n s ( u i n t 2 5 6 ) { u i n t 2 5 6 m i n i n g M i n t e d = t o t a l S u p p l y ( ) . s u b (reserve); / / T o t a l s u p p l y = M e o w M i n i n g + D e v F u n d + r e s e r v e . / / E v e r y 1 1 . 4 2 8 6 M e o w m i n t e d w i l l mint 1 Meow f o r d e v , c o m e f r o m 8 0 / 7 = Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 22 Public ________ 3 8 3 9 4 0 1 1 . 4 2 8 6 u s e 1 0 , 0 0 0 t o a v o i d f l o a ting. u i n t 2 5 6 d e v F u n d = m i n i n g M i n t e d . m u l ( 1 0 0 0 0 ) . d i v ( 1 1 4 2 8 6 ) ; r e t u r n ( u i n t 2 5 6 ( 2 0 0 0 0 0 0 0 0 e 1 8 ) . s u b ( ( m i n i n g M i n t e d ) . s u b ( d e v F u n d ))).div( 5 ) ; / / 2 0 % o f ( M e o w M i n i n g - D e v F u n d ) } When the amount allocated for m e o w M i n i n g portion is reduced, the duration of token distribution will also be reduced, causing the user to earn less reward than they should without complying to the tokenomics. 5.6.2. Remediation Inspex suggests removing the manual minting functionality or redesigning the token allocation to define a clear portion for manual minting. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 23 Public ________ 5.7. Denial of Service on Minting Cap Exceeding ID IDX-007 Target MeowMining Category Advanced Smart Contract Vulnerability CWE CWE-840: Business Logic Errors Risk Severity: Medium Impact: Medium Multiple functions of the M e o w M i n i n g contract will be unusable from the failed token minting, disrupting the availability of the service. The users can withdraw their funds using the e m e r g e n c y W i t h d r a w ( ) function, but the pending reward will be discarded. Likelihood: Medium It is likely that $MEOW released from the M e o w M i n i n g contract will eventually reach the cap. Status Resolved Meow Finance team has resolved this issue by modifying the M e o w M i n i n g contract to handle the case when the cap is filled as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.7.1. Description The u p d a t e P o o l ( ) function in the M e o w M i n i n g contract is used to calculate and distribute the reward to the users. The $MEOW reward is minted to M e o w M i n i n g contract using the m i n t ( ) function at line 177-178. MeowMining.sol 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 1 7 5 1 7 6 1 7 7 1 7 8 1 7 9 1 8 0 f u n c t i o n u p d a t e P o o l ( u i n t 2 5 6 _ p i d ) p u b l i c { P o o l I n f o s t o r a g e p o o l = p o o l I n f o [ _ p i d ] ; i f ( b l o c k . t i m e s t a m p > p o o l . l a s t R e w a r d T i m e ) { u i n t 2 5 6 s t a k e T o k e n S u p p l y = I E R C 2 0 ( p o o l . s t a k e T o k e n ) . b a l a n c e O f( a d d r e s s ( t h i s ) ) ; i f ( s t a k e T o k e n S u p p l y > 0 & & t o t a l A l l o c P o i n t > 0 ) { u i n t 2 5 6 t i m e = b l o c k . t i m e s t a m p . s u b ( p o o l . l a s t R e w a r d T i m e ) ; u i n t 2 5 6 m e o w R e w a r d = t i m e . m u l ( m e o w P e r S e c ond).mul(pool.allocPoint) . d i v ( t o t a l A l l o c P o i n t ) ; / / E v e r y 1 1 . 4 2 8 6 M e o w m i n t e d w i l l mint 1 M e o w f o r d e v , c o m e f r o m 8 0 / 7 = 1 1 . 4 2 8 6 u s e 1 0 , 0 0 0 t o a v o id floating. u i n t 2 5 6 d e v f u n d = m e o w R e w a r d . m u l ( 1 0 0 0 0 ) . d i v ( 1 1 4 2 8 6 ) ; m e o w . m i n t ( a d d r e s s ( t h i s ) , d e v f u n d ) ; m e o w . m i n t ( a d d r e s s ( t h i s ) , m e o w R e w a r d ) ; s a f e M e o w T r a n s f e r ( d e v a d d r , d e v f u n d.mul(preShare).div( 1 0 0 0 0 ) ) ; d e v e l o p m e n t F u n d . l o c k ( d e v f u n d . m u l (lockShare).div( 1 0 0 0 0 ) ) ; Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 24 Public ________ 1 8 1 1 8 2 1 8 3 1 8 4 1 8 5 p o o l . a c c M e o w P e r S h a r e = p o o l . a c c M eowPerShare.add(meowReward . m u l ( A C C _ M E O W _ P R E C I S I O N ) . d i v ( s t a keTokenSupply)); } p o o l . l a s t R e w a r d T i m e = b l o c k . t i m e s t a m p ; } } The amount of reward to be minted is limited by the max supply of $MEOW token ( c a p ( ) ). MeowToken.sol 2 9 3 0 3 1 3 2 3 3 f u n c t i o n m i n t ( a d d r e s s _ t o , u i n t 2 5 6 _ a m o u n t ) p u b l i c o n l y O w n e r { r e q u i r e ( t o t a l S u p p l y ( ) . a d d ( _ a m o u n t ) < = c ap(), " M e o w T o k e n : : m i n t : : c a p e x c e e d e d . " ) ; _ m i n t ( _ t o , _ a m o u n t ) ; _ m o v e D e l e g a t e s ( a d d r e s s ( 0 ) , _ d e l e g a t e s [ _ t o ] , _ a m o u n t ) ; } However, when the sum of the reward to be minted and the minted amount is more than the max supply, the m i n t ( ) function will be unusable, causing the transactions that call this function to be reverted, disrupting the availability of the platform. 5.7.2. Remediation Inspex suggests modifying the M e o w M i n i n g contract to handle the case when the cap is filled, for example: MeowMining.sol 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 1 7 5 1 7 6 1 7 7 1 7 8 1 7 9 1 8 0 1 8 1 1 8 2 1 8 3 u i n t 2 5 6 p u b l i c M A X _ M E O W _ R E W A R D = 2 0 0 0 0 0 0 0 0 e 1 8 ; u i n t 2 5 6 p u b l i c M A X _ D E V _ F U N D = 1 7 5 0 0 0 0 0 e 1 8 ; u i n t 2 5 6 p u b l i c m i n t e d D e v F u n d ; u i n t 2 5 6 p u b l i c m i n t e d M e o w R e w a r d ; f u n c t i o n u p d a t e P o o l ( u i n t 2 5 6 _ p i d ) p u b l i c { P o o l I n f o s t o r a g e p o o l = p o o l I n f o [ _ p i d ] ; i f ( b l o c k . t i m e s t a m p > p o o l . l a s t R e w a r d T i m e ) { u i n t 2 5 6 s t a k e T o k e n S u p p l y = I E R C 2 0 ( p o o l . s takeToken) . b a l a n c e O f ( a d d r e s s ( t h i s ) ) ; i f ( s t a k e T o k e n S u p p l y > 0 & & t o t a l A l l o c P o i n t > 0 ) { u i n t 2 5 6 t i m e = b l o c k . t i m e s t a m p . s u b ( p o o l . l a s t R e w a r d T i m e ) ; u i n t 2 5 6 m e o w R e w a r d = t i m e . m u l ( m e o w P e r S e c o n d ) . m u l ( p o o l .allocPoint).div(totalAllocPoint); / / E v e r y 1 1 . 4 2 8 6 M e o w m i n t e d w i l l mint 1 M e o w f o r d e v , c o m e f r o m 8 0 / 7 = 1 1 . 4 2 8 6 u s e 1 0 , 0 0 0 t o a v o id floating. u i n t 2 5 6 d e v f u n d = m e o w R e w a r d . m u l ( 1 0 0 0 0 ) . d i v ( 1 1 4 2 8 6 ) ; i f ( m i n t e d M e o w R e w a r d . a d d ( m e o w R e w a r d ) > M A X _ M E O W _ R E W A R D . s u b ( m e o w . m a n u a l M inted())) { m e o w R e w a r d = M A X _ M E O W _ R E W A R D . s u b (mintedMeowReward); Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 25 Public ________ 1 8 4 1 8 5 1 8 6 1 8 7 1 8 8 1 8 9 1 9 0 1 9 1 1 9 2 1 9 3 1 9 4 1 9 5 1 9 6 1 9 7 1 9 8 } i f ( m i n t e d D e v F u n d . a d d ( d e v f u n d ) > M A X_DEV_FUND) { d e v f u n d = M A X _ D E V _ F U N D . s u b ( m i n t e dDevFund); } m e o w . m i n t ( a d d r e s s ( t h i s ) , d e v f u n d ) ; m e o w . m i n t ( a d d r e s s ( t h i s ) , m e o w R e w a r d ) ; m i n t e d D e v F u n d = m i n t e d D e v F u n d . a d d(devfund); m i n t e d M e o w R e w a r d = m i n t e d M e o w R e w ard.add(meowReward); s a f e M e o w T r a n s f e r ( d e v a d d r , d e v f u n d.mul(preShare).div( 1 0 0 0 0 ) ) ; d e v e l o p m e n t F u n d . l o c k ( d e v f u n d . m u l (lockShare).div( 1 0 0 0 0 ) ) ; p o o l . a c c M e o w P e r S h a r e = p o o l . a c c M eowPerShare.add(meowReward . m u l ( A C C _ M E O W _ P R E C I S I O N ) . d i v ( s t a keTokenSupply)); } p o o l . l a s t R e w a r d T i m e = b l o c k . t i m e s t a m p ; } } Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 26 Public ________ 5.8. Improper Delegation Handling in Token Burning ID IDX-008 Target MeowToken Category Advanced Smart Contract Vulnerability CWE CWE-840: Business Logic Errors Risk Severity: Low Impact: Medium The number of votes can be higher than the amount of tokens available, causing the result of the vote to be unfair and untrustworthy, resulting in loss of reputation for the platform. Likelihood: Low This issue occurs when the token is burned. There is no burning mechanism in the use case of $MEOW token, and there is no benefit for the token holder to burn their own tokens. Status Resolved Meow Finance team has resolved this issue by deducting the delegation amount in the b u r n ( ) function as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.8.1. Description In the M e o w T o k e n contract, there is a voting mechanism implemented, allowing the users (delegators) to delegate their votes to another address (delegatees) without transferring their tokens. The users can delegate their votes to another address using the d e l e g a t e ( ) function, which calls the _ d e l e g a t e ( ) function. MeowToken.sol 1 2 8 1 2 9 1 3 0 f u n c t i o n d e l e g a t e ( a d d r e s s d e l e g a t e e ) e x t e r n a l { r e t u r n _ d e l e g a t e ( m s g . s e n d e r , d e l e g a t e e ) ; } The _ d e l e g a t e ( ) function sets the delegatee of the address in line 218, and transfers the number of votes from the old delegatee to the new delegatee with the current token balance of the delegator by using the _ m o v e D e l e g a t e s ( ) function as in line 222. MeowToken.sol 2 1 5 2 1 6 f u n c t i o n _ d e l e g a t e ( a d d r e s s d e l e g a t o r , a d d r e s s d e l e g a t e e ) i n t e r n a l { a d d r e s s c u r r e n t D e l e g a t e = _ d e l e g a t e s [ d e l egator]; Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 27 Public ________ 2 1 7 2 1 8 2 1 9 2 2 0 2 2 1 2 2 2 2 2 3 u i n t 2 5 6 d e l e g a t o r B a l a n c e = b a l a n c e O f ( d e l egator); / / b a l a n c e o f u n d e r l y i n g M e o w s ( n o t s c a l e d ) ; _ d e l e g a t e s [ d e l e g a t o r ] = d e l e g a t e e; e m i t D e l e g a t e C h a n g e d ( d e l e g a t o r , c u r r e ntDelegate, d e l e g a t e e ) ; _ m o v e D e l e g a t e s ( c u r r e n t D e l e g a t e , delegatee, delegatorBalance); } The _ m o v e D e l e g a t e s ( ) function calculates the new amount of voting for the delegatee. MeowToken.sol 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 f u n c t i o n _ m o v e D e l e g a t e s ( a d d r e s s s r c R e p , a d d r e s s d s t R e p , u i n t 2 5 6 a m o u n t ) i n t e r n a l { i f ( s r c R e p ! = d s t R e p & & a m o u n t > 0 ) { i f ( s r c R e p ! = a d d r e s s ( 0 ) ) { / / d e c r e a s e o l d r e p r e s e n t a t i v e u i n t 3 2 s r c R e p N u m = n u m C h e c k p o i n t s [ s r c R e p]; u i n t 2 5 6 s r c R e p O l d = s r c R e p N u m > 0 ? c h e c k p o i n t s [ s r c R e p ] [ s r c R e p N u m - 1 ] . v o t e s : 0 ; u i n t 2 5 6 s r c R e p N e w = s r c R e p O l d . s u b ( a m o u n t ); _ w r i t e C h e c k p o i n t ( s r c R e p , s r c R e p N um, srcRepOld, s r c R e p N e w ) ; } i f ( d s t R e p ! = a d d r e s s ( 0 ) ) { / / i n c r e a s e n e w r e p r e s e n t a t i v e u i n t 3 2 d s t R e p N u m = n u m C h e c k p o i n t s [ d s t R e p]; u i n t 2 5 6 d s t R e p O l d = d s t R e p N u m > 0 ? c h e c k p o i n t s [ d s t R e p ] [ d s t R e p N u m - 1 ] . v o t e s : 0 ; u i n t 2 5 6 d s t R e p N e w = d s t R e p O l d . a d d ( a m o u n t ); _ w r i t e C h e c k p o i n t ( d s t R e p , d s t R e p N um, dstRepOld, d s t R e p N e w ) ; } } } When the token is minted, the delegate amount is added to the delegatee of the _ t o address which receives the minted token. MeowToken.sol 2 9 3 0 3 1 f u n c t i o n m i n t ( a d d r e s s _ t o , u i n t 2 5 6 _ a m o u n t ) p u b l i c o n l y O w n e r { r e q u i r e ( t o t a l S u p p l y ( ) . a d d ( _ a m o u n t ) < = c ap(), " M e o w T o k e n : : m i n t : : c a p e x c e e d e d . " ) ; _ m i n t ( _ t o , _ a m o u n t ) ; Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 28 Public ________ 3 2 3 3 _ m o v e D e l e g a t e s ( a d d r e s s ( 0 ) , _ d e l e g a t e s [ _ t o ] , _ a m o u n t ) ; } However, when the token is burned, the delegate amount is not removed. Therefore, the votes can still be cast even when the address does own the token. MeowToken.sol 5 0 5 1 5 2 5 3 5 4 5 5 5 6 f u n c t i o n b u r n F r o m ( a d d r e s s _ a c c o u n t , u i n t 2 5 6 _ a m o u n t ) e x t e r n a l o n l y O w n e r { _ b u r n ( _ a c c o u n t , _ a m o u n t ) ; } f u n c t i o n b u r n ( u i n t 2 5 6 _ a m o u n t ) e x t e r n a l { _ b u r n ( m s g . s e n d e r , _ a m o u n t ) ; } 5.8.2. Remediation Inspex suggests deducting the delegation vote on the burning of token, for example: MeowToken.sol 5 0 5 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 f u n c t i o n b u r n F r o m ( a d d r e s s _ a c c o u n t , u i n t 2 5 6 _ a m o u n t ) e x t e r n a l o n l y O w n e r { _ b u r n ( _ a c c o u n t , _ a m o u n t ) ; _ m o v e D e l e g a t e s ( _ d e l e g a t e s [ _ a c c o u nt], a d d r e s s ( 0 ) , _ a m o u n t ) ; } f u n c t i o n b u r n ( u i n t 2 5 6 _ a m o u n t ) e x t e r n a l { _ b u r n ( m s g . s e n d e r , _ a m o u n t ) ; _ m o v e D e l e g a t e s ( _ d e l e g a t e s [ m s g . s e n d e r ] , a d d r e s s ( 0 ) , _ a m o u n t ) ; } Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 29 Public ________ 5.9. Design Flaw in massUpdatePool() Function ID IDX-009 Target MeowMining FeeDistribute Category General Smart Contract Vulnerability CWE CWE-400: Uncontrolled Resource Consumption Risk Severity: Low Impact: Medium The m a s s U p d a t e P o o l s ( ) function will eventually be unusable due to excessive gas usage. Likelihood: Low It is very unlikely that the p o o l I n f o size will be raised until the m a s s U p d a t e P o o l s ( ) function is unusable. Status Acknowledged Meow Finance team has acknowledged this issue. The team explained that the risk of this issue is quite low since the number of pools that will be added by the team is not high enough to cause the unfunctional smart contract issue. 5.9.1. Description The m a s s U p d a t e P o o l s ( ) function executes the u p d a t e P o o l ( ) function, which is a state modifying function for all added pools as shown below: MeowMining.sol 1 6 0 1 6 1 1 6 2 1 6 3 1 6 4 1 6 5 f u n c t i o n m a s s U p d a t e P o o l s ( ) p u b l i c { u i n t 2 5 6 l e n g t h = p o o l I n f o . l e n g t h ; f o r ( u i n t 2 5 6 p i d = 0 ; p i d < l e n g t h ; + + p i d ) { u p d a t e P o o l ( p i d ) ; } } With the current design, the added pools cannot be removed. They can only be disabled by setting the p o o l . a l l o c P o i n t to 0. Even if a pool is disabled, the u p d a t e P o o l ( ) function for this pool is still called. Therefore, if new pools continue to be added to this contract, the p o o l I n f o . l e n g t h will continue to grow and this function will eventually be unusable due to excessive gas usage. 5.9.2. Remediation Inspex suggests making the contract capable of removing unnecessary or ended pools to reduce the loop rounds in the m a s s U p d a t e P o o l s ( ) function. Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 30 Public ________ 5.10. Transaction Ordering Dependence ID IDX-010 Target SpookyswapWorker Category General Smart Contract Vulnerability CWE CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') Risk Severity: Low Impact: Medium The front-running attack can be performed, resulting in a bad swapping rate for the reinvestment. This causes the reinvestment fund to be lower, which is a minor monetary loss for the platform users. Likelihood: Low It is easy to perform the attack. However, with a low profit, there is low motivation to attack with this vulnerability. Status Resolved Meow Finance team has resolved this issue by implementing price oracle and calculating expected amount out when using the r o u t e r . s w a p E x a c t T o k e n s F o r T o k e n s ( ) inside the r e i n v e s t ( ) function in commit 0 9 1 2 b 0 0 9 9 1 1 4 9 3 9 c 3 4 5 2 1 1 7 c 1 a 2 5 d e 8 2 cfb6cd75 5.10.1. Description In S p o o k y s w a p W o r k e r contracts, the reward of the farming is compounded using the r e i n v e s t ( ) function. In the compounding process, there are many subprocesses, the token swapping process is one of them. The swapping can be performed by calling r o u t e r . s w a p E x a c t T o k e n s F o r T o k e n s ( ) function to swap the reward token ( b o o ) to b a s e T o k e n in line 163. SpookyswapWorker.sol 1 3 8 1 3 9 1 4 0 1 4 1 1 4 2 1 4 3 1 4 4 1 4 5 1 4 6 1 4 7 1 4 8 1 4 9 f u n c t i o n r e i n v e s t ( ) e x t e r n a l o v e r r i d e o n l y E O A o n l y R e i n v e s t o r n o n R e e n t r a n t { / / 1 . A p p r o v e t o k e n s b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , u i n t 2 5 6 ( - 1 ) ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , u i n t 2 5 6 ( - 1 ) ) ; / / 2 . W i t h d r a w a l l t h e r e w a r d s . m a s t e r C h e f . w i t h d r a w ( p i d , 0 ) ; u i n t 2 5 6 r e w a r d = b o o . b a l a n c e O f ( a d d r e s s ( t h i s ) ) ; i f ( r e w a r d = = 0 ) r e t u r n ; / / 3 . S e n d t h e r e w a r d b o u n t y t o the caller. u i n t 2 5 6 b o u n t y = r e w a r d . m u l ( r e i n v e s t B o u n tyBps) / 1 0 0 0 0 ; i f ( b o u n t y > 0 ) b o o . s a f e T r a n s f e r ( m s g . s e n d e r , b o u n t y ) ; / / 4 . C o n v e r t a l l t h e r e m a i n i n g rewards to BaseToken v i a N a t i v e f o r Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 31 Public ________ 1 5 0 1 5 1 1 5 2 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 1 6 7 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 l i q u i d i t y . a d d r e s s [ ] m e m o r y p a t h ; i f ( b a s e T o k e n ! = b o o ) { i f ( b a s e T o k e n = = w N a t i v e ) { p a t h = n e w a d d r e s s [ ] ( 2 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; } e l s e { p a t h = n e w a d d r e s s [ ] ( 3 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; p a t h [ 2 ] = a d d r e s s ( b a s e T o k e n ) ; } } r o u t e r . s w a p E x a c t T o k e n s F o r T o k e n s ( reward.sub(bounty), 0 , p a t h , a d d r e s s ( t h i s ) , n o w ) ; / / 5 . U s e a d d T o k e n s t r a t e g y t o convert all BaseToken t o L P t o k e n s . b a s e T o k e n . s a f e T r a n s f e r ( a d d r e s s ( a d d S t r a t ) , b a s e T o k e n . m y B a l a n c e ( )); a d d S t r a t . e x e c u t e ( a d d r e s s ( 0 ) , 0 , a b i . e n c o d e ( 0 ) ) ; / / 6 . M i n t m o r e L P t o k e n s a n d s t ake them for more r e w a r d s . m a s t e r C h e f . d e p o s i t ( p i d , l p T o k e n . balanceOf( a d d r e s s ( t h i s ) ) ) ; / / 7 . R e s e t a p p r o v e b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , 0 ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , 0 ) ; e m i t R e i n v e s t ( m s g . s e n d e r , r e w a r d , b o u n t y ) ; } However, as seen in the source code above, the swapping tolerance ( a m o u n t O u t M i n ) of the swapping function is set to 0. This allows a front-running attack to be done, resulting in fewer tokens gained from the swap. This reduces the amount of token being reinvested and causes the users to gain less reward. 5.10.2. Remediation The tolerance value ( a m o u n t O u t M i n ) should not be set to 0. Inspex suggests calculating the expected amount out with the token price fetched from the price oracles, and setting it to the a m o u n t O u t M i n parameter while calling the r o u t e r . s w a p E x a c t T o k e n s F o r T o k e n s ( ) function in the S p o o k y s w a p W o r k e r contract, for example: SpookyswapWorker.sol 1 2 3 4 5 6 f u n c t i o n r e i n v e s t ( ) e x t e r n a l o v e r r i d e o n l y E O A o n l y R e i n v e s t o r n o n R e e n t r a n t { / / 1 . A p p r o v e t o k e n s b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , u i n t 2 5 6 ( - 1 ) ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , u i n t 2 5 6 ( - 1 ) ) ; / / 2 . W i t h d r a w a l l t h e r e w a r d s . m a s t e r C h e f . w i t h d r a w ( p i d , 0 ) ; Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 32 Public ________ 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 3 8 u i n t 2 5 6 r e w a r d = b o o . b a l a n c e O f ( a d d r e s s ( t h i s ) ) ; i f ( r e w a r d = = 0 ) r e t u r n ; / / 3 . S e n d t h e r e w a r d b o u n t y t o the caller. u i n t 2 5 6 b o u n t y = r e w a r d . m u l ( r e i n v e s t B o u n tyBps) / 1 0 0 0 0 ; i f ( b o u n t y > 0 ) b o o . s a f e T r a n s f e r ( m s g . s e n d e r , b o u n t y ) ; / / 4 . C o n v e r t a l l t h e r e m a i n i n g rewards to BaseToken v i a N a t i v e f o r l i q u i d i t y . a d d r e s s [ ] m e m o r y p a t h ; i f ( b a s e T o k e n ! = b o o ) { i f ( b a s e T o k e n = = w N a t i v e ) { p a t h = n e w a d d r e s s [ ] ( 2 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; } e l s e { p a t h = n e w a d d r e s s [ ] ( 3 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; p a t h [ 2 ] = a d d r e s s ( b a s e T o k e n ) ; } } u i n t 2 5 6 a m o u n t O u t M i n = c a l c u l a t e A m o u n t O u tMinFromOracle(reward.sub(bounty)); r o u t e r . s w a p E x a c t T o k e n s F o r T o k e n s ( reward.sub(bounty), a m o u n t O u t M i n , p a t h , a d d r e s s ( t h i s ) , n o w ) ; / / 5 . U s e a d d T o k e n s t r a t e g y t o convert all BaseToken t o L P t o k e n s . b a s e T o k e n . s a f e T r a n s f e r ( a d d r e s s ( a d d S t r a t ) , b a s e T o k e n . m y B a l a n c e ( )); a d d S t r a t . e x e c u t e ( a d d r e s s ( 0 ) , 0 , a b i . e n c o d e ( 0 ) ) ; / / 6 . M i n t m o r e L P t o k e n s a n d s t ake them for more r e w a r d s . m a s t e r C h e f . d e p o s i t ( p i d , l p T o k e n . balanceOf( a d d r e s s ( t h i s ) ) ) ; / / 7 . R e s e t a p p r o v e b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , 0 ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , 0 ) ; e m i t R e i n v e s t ( m s g . s e n d e r , r e w a r d , b o u n t y ) ; } Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 33 Public ________ 5.11. Missing Input Validation (maxReinvestBountyBps) ID IDX-011 Target SpookyswapWorker Category Advanced Smart Contract Vulnerability CWE CWE-20: Improper Input Validation Risk Severity: Low Impact: Medium By setting r e i n v e s t B o u n t y B p s to be greater than 10,000, the cause the transaction reverting for all w o r k ( ) function executions. Likelihood: Low It is very unlikely that the owner will set an improperly large r e i n v e s t B o u n t y B p s because there is no profit to perform this action. Status Resolved Meow Finance team has resolved this issue by setting the upper limit of the m a x R e i n v e s t B o u n t y B p s as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.11.1. Description The s e t R e i n v e s t B o u n t y B p s ( ) function can be used to set the r e i n v e s t B o u n t y B p s state. SpookyswapWorker.sol 2 8 8 2 8 9 2 9 0 2 9 1 2 9 2 2 9 3 2 9 4 f u n c t i o n s e t R e i n v e s t B o u n t y B p s ( u i n t 2 5 6 _ r e i n v e s t B o u n t y B p s ) e x t e r n a l o n l y O w n e r { r e q u i r e ( _ r e i n v e s t B o u n t y B p s < = m a x R e i n v e s tBountyBps, " S p o o k y s w a p W o r k e r : : s e t R e i n v e s t B o untyBps:: _ r e i n v e s t B o u n t y B p s e x c e e d e d m a x R e i n v e s t B o u n t y B p s " ) ; r e i n v e s t B o u n t y B p s = _ r e i n v e s t B o u ntyBps; } The r e i n v e s t B o u n t y B p s is limited by m a x R e i n v e s t B o u n t y B p s state. However, the m a x R e i n v e s t B o u n t y B p s can be set without any limitation as shown below: SpookyswapWorker.sol 2 9 8 2 9 9 3 0 0 f u n c t i o n s e t M a x R e i n v e s t B o u n t y B p s ( u i n t 2 5 6 _ m a x R e i n v e s t B o u n t y B p s ) e x t e r n a l o n l y O w n e r { r e q u i r e ( _ m a x R e i n v e s t B o u n t y B p s > = r e i n v e s tBountyBps , Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 34 Public ________ 3 0 1 3 0 2 3 0 3 3 0 4 " S p o o k y s w a p W o r k e r : : s e t M a x R e i n v e s tBountyBps:: _maxReinvestBountyBps l o w e r t h a n r e i n v e s t B o u n t y B p s " ) ; m a x R e i n v e s t B o u n t y B p s = _ m a x R e i n v estBountyBps; } The r e i n v e s t B o u n t y B p s state is used in the r e i n v e s t ( ) function to determine the bounty rate of reinvesting as follow: SpookyswapWorker.sol 1 3 8 1 3 9 1 4 0 1 4 1 1 4 2 1 4 3 1 4 4 1 4 5 1 4 6 1 4 7 1 4 8 1 4 9 1 5 0 1 5 1 1 5 2 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 1 6 7 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 f u n c t i o n r e i n v e s t ( ) e x t e r n a l o v e r r i d e o n l y E O A o n l y R e i n v e s t o r n o n R e e n t r a n t { / / 1 . A p p r o v e t o k e n s b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , u i n t 2 5 6 ( - 1 ) ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , u i n t 2 5 6 ( - 1 ) ) ; / / 2 . W i t h d r a w a l l t h e r e w a r d s . m a s t e r C h e f . w i t h d r a w ( p i d , 0 ) ; u i n t 2 5 6 r e w a r d = b o o . b a l a n c e O f ( a d d r e s s ( t h i s ) ) ; i f ( r e w a r d = = 0 ) r e t u r n ; / / 3 . S e n d t h e r e w a r d b o u n t y t o the caller. u i n t 2 5 6 b o u n t y = r e w a r d . m u l ( r e i n v e s t B o u n tyBps) / 1 0 0 0 0 ; i f ( b o u n t y > 0 ) b o o . s a f e T r a n s f e r ( m s g . s e n d e r , b o u n t y ) ; / / 4 . C o n v e r t a l l t h e r e m a i n i n g rewards to BaseToken v i a N a t i v e f o r l i q u i d i t y . a d d r e s s [ ] m e m o r y p a t h ; i f ( b a s e T o k e n ! = b o o ) { i f ( b a s e T o k e n = = w N a t i v e ) { p a t h = n e w a d d r e s s [ ] ( 2 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; } e l s e { p a t h = n e w a d d r e s s [ ] ( 3 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; p a t h [ 2 ] = a d d r e s s ( b a s e T o k e n ) ; } } r o u t e r . s w a p E x a c t T o k e n s F o r T o k e n s ( reward.sub(bounty), 0 , p a t h , a d d r e s s ( t h i s ) , n o w ) ; / / 5 . U s e a d d T o k e n s t r a t e g y t o convert all BaseToken t o L P t o k e n s . b a s e T o k e n . s a f e T r a n s f e r ( a d d r e s s ( a d d S t r a t ) , b a s e T o k e n . m y B a l a n c e ( )); a d d S t r a t . e x e c u t e ( a d d r e s s ( 0 ) , 0 , a b i . e n c o d e ( 0 ) ) ; / / 6 . M i n t m o r e L P t o k e n s a n d s t ake them for more r e w a r d s . m a s t e r C h e f . d e p o s i t ( p i d , l p T o k e n . balanceOf( a d d r e s s ( t h i s ) ) ) ; / / 7 . R e s e t a p p r o v e b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , 0 ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , 0 ) ; Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 35 Public ________ 1 7 3 1 7 4 e m i t R e i n v e s t ( m s g . s e n d e r , r e w a r d , b o u n t y ) ; } By setting r e i n v e s t B o u n t y B p s to be greater than 10,000, the bounty will be greater than the harvested reward and cause the transaction to be reverted for all r e i n v e s t ( ) function executions. 5.11.2. Remediation Inspex suggests setting the upper limit of the m a x R e i n v e s t B o u n t y B p s for example: SpookyswapWorker.sol 2 9 8 2 9 9 3 0 0 3 0 1 3 0 2 3 0 3 3 0 4 3 0 5 f u n c t i o n s e t M a x R e i n v e s t B o u n t y B p s ( u i n t 2 5 6 _ m a x R e i n v e s t B o u n t y B p s ) e x t e r n a l o n l y O w n e r { r e q u i r e ( _ m a x R e i n v e s t B o u n t y B p s > = r e i n v e s tBountyBps, " S p o o k y s w a p W o r k e r : : s e t M a x R e i n v e s tBountyBps:: _ m a x R e i n v e s t B o u n t y B p s l o w e r t h a n r e i n v e s t B o u n t y B p s " ) ; r e q u i r e ( _ m a x R e i n v e s t B o u n t y B p s < = 1 0 0 0 0 , " S p o o k y s w a p W o r k e r : : s e t M a x R e i n v e s tBountyBps:: _maxReinvestBountyBps higher than h a r v e s t e d r e w a r d " ) ; m a x R e i n v e s t B o u n t y B p s = _ m a x R e i n v estBountyBps; } Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 36 Public ________ 5.12. Denial of Service in reinvest() Function ID IDX-012 Target SpookyswapWorker Category Advanced Smart Contract Vulnerability CWE CWE-840: Business Logic Errors Risk Severity: Low Impact: Medium The r e i n v e s t ( ) function will be unusable, disrupting the availability of the service. The users will not receive additional profit from the compounding mechanism. Likelihood: Low The b a s e T o k e n can be set by only the initializer of the S p o o k y s w a p W o r k e r contract. It is very unlikely that the baseToken will be the same as the reward token. Status Resolved Meow Finance team has resolved this issue by moving the swapping statement to the inside of the condition which checks if reward token is the same as the b a s e T o k e n as suggested in commit 1 5 1 3 7 b 0 9 3 a a b 2 f a 2 7 c c 0 0 a 4 5 9 0 5 8 a 5 2 1 08333a51 . 5.12.1. Description In S p o o k y s w a p W o r k e r contracts, the reward of the farming is compounded using the r e i n v e s t ( ) function. In the compounding process, there are many subprocesses, the token swapping process is one of them. The condition b a s e T o k e n ! = b o o in line 151 is used to check if the b a s e T o k e n is not a reward token then set the path to swap the reward for the b a s e T o k e n . SpookyswapWorker.sol 1 3 8 1 3 9 1 4 0 1 4 1 1 4 2 1 4 3 1 4 4 1 4 5 1 4 6 1 4 7 1 4 8 1 4 9 f u n c t i o n r e i n v e s t ( ) e x t e r n a l o v e r r i d e o n l y E O A o n l y R e i n v e s t o r n o n R e e n t r a n t { / / 1 . A p p r o v e t o k e n s b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , u i n t 2 5 6 ( - 1 ) ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , u i n t 2 5 6 ( - 1 ) ) ; / / 2 . W i t h d r a w a l l t h e r e w a r d s . m a s t e r C h e f . w i t h d r a w ( p i d , 0 ) ; u i n t 2 5 6 r e w a r d = b o o . b a l a n c e O f ( a d d r e s s ( t h i s ) ) ; i f ( r e w a r d = = 0 ) r e t u r n ; / / 3 . S e n d t h e r e w a r d b o u n t y t o the caller. u i n t 2 5 6 b o u n t y = r e w a r d . m u l ( r e i n v e s t B o u n tyBps) / 1 0 0 0 0 ; i f ( b o u n t y > 0 ) b o o . s a f e T r a n s f e r ( m s g . s e n d e r , b o u n t y ) ; / / 4 . C o n v e r t a l l t h e r e m a i n i n g rewards to BaseToken v i a N a t i v e f o r l i q u i d i t y . Inspex Smart Contract Audit Report: AUDIT2021021 (v1.0) 37 Public ________ 1 5 0 1 5 1 1 5 2 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 1 6 7 1 6 8 1 6 9 1 7 0 1 7 1 1 7 2 1 7 3 1 7 4 a d d r e s s [ ] m e m o r y p a t h ; i f ( b a s e T o k e n ! = b o o ) { i f ( b a s e T o k e n = = w N a t i v e ) { p a t h = n e w a d d r e s s [ ] ( 2 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; } e l s e { p a t h = n e w a d d r e s s [ ] ( 3 ) ; p a t h [ 0 ] = a d d r e s s ( b o o ) ; p a t h [ 1 ] = a d d r e s s ( w N a t i v e ) ; p a t h [ 2 ] = a d d r e s s ( b a s e T o k e n ) ; } } r o u t e r . s w a p E x a c t T o k e n s F o r T o k e n s ( reward.sub(bounty), 0 , p a t h , a d d r e s s ( t h i s ) , n o w ) ; / / 5 . U s e a d d T o k e n s t r a t e g y t o convert all BaseToken t o L P t o k e n s . b a s e T o k e n . s a f e T r a n s f e r ( a d d r e s s ( a d d S t r a t ) , b a s e T o k e n . m y B a l a n c e ( )); a d d S t r a t . e x e c u t e ( a d d r e s s ( 0 ) , 0 , a b i . e n c o d e ( 0 ) ) ; / / 6 . M i n t m o r e L P t o k e n s a n d s t ake them for more r e w a r d s . m a s t e r C h e f . d e p o s i t ( p i d , l p T o k e n . balanceOf( a d d r e s s ( t h i s ) ) ) ; / / 7 . R e s e t a p p r o v e b o o . s a f e A p p r o v e ( a d d r e s s ( r o u t e r ) , 0 ) ; a d d r e s s ( l p T o k e n ) . s a f e A p p r o v e ( a d d r e s s ( m a s t e r C h e f ) , 0 ) ; e m i t R e i n v e s t ( m s g . s e n d e r , r e w a r d , b o u n t y ) ; } When the b a s e T o k e n is a reward token, the path will be empty, causing the reinvest transaction to be reverted, because the g e t A m o u n t s O u t ( ) function called by the s w a p E x a c t T o k e n s F o r T o k e n s ( ) function has a r e q u i r e statement to check that the path length is equal to or more than 2. This can be seen in line 266 in the example code from U n i s w a p V 2 R o u t e r 0 2 contract of S p o o k y S w a p platform. UniswapV2Router02.sol at https://
Audit Result: Minor Issues: 4 Moderate Issues: 8 Major Issues: 5 Critical Issues: 4 2. Minor Issues 2.a Problem: Unsupported Design for Deflationary Token (code reference: line 54) 2.b Fix: Use a supported design for deflationary token. 3. Moderate Issues 3.a Problem: Improper Access Control for burnFrom() Function (code reference: line 52) 3.b Fix: Implement proper access control for burnFrom() function. 4. Major Issues 4.a Problem: Missing Input Validation of preShare and lockShare Values (code reference: line 41) 4.b Fix: Implement input validation for preShare and lockShare values. 5. Critical Issues 5.a Problem: Denial of Service in Beneficiary Mechanism (code reference: line 10) 5.b Fix: Implement a mechanism to prevent denial of service in beneficiary mechanism. 6. Observations The audit revealed a total of 21 issues, including 4 Minor, 8 Moderate, 5 Major, and 4 Critical issues. 7. Conclusion The audit revealed a total of 21 issues, including 4 Minor, 8 Issues Count of Minor/Moderate/Major/Critical - Minor: 6 - Moderate: 4 - Major: 3 - Critical: 2 Minor Issues 2.a Problem (one line with code reference) - Unchecked return values in the function transferFrom() (line 545) 2.b Fix (one line with code reference) - Check return values in the function transferFrom() (line 545) Moderate 3.a Problem (one line with code reference) - Unchecked return values in the function transfer() (line 545) 3.b Fix (one line with code reference) - Check return values in the function transfer() (line 545) Major 4.a Problem (one line with code reference) - Unchecked return values in the function approve() (line 545) 4.b Fix (one line with code reference) - Check return values in the function approve() (line 545) Critical 5.a Problem (one line with code reference) - Unchecked return values in the function transferOwnership() (line 545) 5.b Fix (one line with code reference) 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 _setSpookyFee() function (MeowMining.sol#L717) 2.b Fix (one line with code reference): Check the return value of the _setSpookyFee() function (MeowMining.sol#L717) Moderate: None Major: None Critical: None Observations: - The assessment scope covers only the in-scope smart contracts and the smart contracts that they are inherited from. - The setSpookyFee() function has been added in the reassessment commit, and is outside of the audit scope. - The Meow Finance team has clarified that this function is used to change the swapping fee when the fee rate on the SpookySwap platform changes. Conclusion: The audit of the Meow Finance smart contracts revealed two minor issues, which have been addressed by the team. No major or critical issues were found.
// SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./libraries/SafeMath256.sol"; import "./interfaces/ILockSend.sol"; contract LockSend is ILockSend { using SafeMath256 for uint; bytes4 private constant _SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); bytes4 private constant _SELECTOR2 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); mapping(bytes32 => uint) public lockSendInfos; modifier afterUnlockTime(uint32 unlockTime) { // solhint-disable-next-line not-rely-on-time require(uint(unlockTime) * 3600 < block.timestamp, "LockSend: NOT_ARRIVING_UNLOCKTIME_YET"); _; } modifier beforeUnlockTime(uint32 unlockTime) { // solhint-disable-next-line not-rely-on-time require(uint(unlockTime) * 3600 > block.timestamp, "LockSend: ALREADY_UNLOCKED"); _; } function lockSend(address to, uint amount, address token, uint32 unlockTime) public override beforeUnlockTime(unlockTime) { require(amount != 0, "LockSend: LOCKED_AMOUNT_SHOULD_BE_NONZERO"); bytes32 key = _getLockedSendKey(msg.sender, to, token, unlockTime); _safeTransferToMe(token, msg.sender, amount); lockSendInfos[key] = lockSendInfos[key].add(amount); emit Locksend(msg.sender, to, token, amount, unlockTime); } // anyone can call this function function unlock(address from, address to, address token, uint32 unlockTime) public override afterUnlockTime(unlockTime) { bytes32 key = _getLockedSendKey(from, to, token, unlockTime); uint amount = lockSendInfos[key]; require(amount != 0, "LockSend: UNLOCK_AMOUNT_SHOULD_BE_NONZERO"); delete lockSendInfos[key]; _safeTransfer(token, to, amount); emit Unlock(from, to, token, amount, unlockTime); } function _getLockedSendKey(address from, address to, address token, uint32 unlockTime) private pure returns (bytes32) { return keccak256(abi.encodePacked(from, to, token, unlockTime)); } function _safeTransferToMe(address token, address from, uint value) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR2, from, address(this), value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "LockSend: TRANSFER_TO_ME_FAILED"); } function _safeTransfer(address token, address to, uint value) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "LockSend: TRANSFER_FAILED"); } } // SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./interfaces/IOneSwapRouter.sol"; import "./interfaces/IOneSwapFactory.sol"; import "./interfaces/IOneSwapPair.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IERC20.sol"; import "./libraries/SafeMath256.sol"; import "./libraries/DecFloat32.sol"; contract OneSwapRouter is IOneSwapRouter { using SafeMath256 for uint; address public immutable override factory; address public immutable override weth; modifier ensure(uint deadline) { // solhint-disable-next-line not-rely-on-time, require(deadline >= block.timestamp, "OneSwapRouter: EXPIRED"); _; } constructor(address _factory, address _weth) public { factory = _factory; weth = _weth; } receive() external payable { assert(msg.sender == weth); // only accept ETH via fallback from the WETH contract } function _addLiquidity(address pair, uint amountStockDesired, uint amountMoneyDesired, uint amountStockMin, uint amountMoneyMin) private view returns (uint amountStock, uint amountMoney) { (uint reserveStock, uint reserveMoney, ) = IOneSwapPool(pair).getReserves(); if (reserveStock == 0 && reserveMoney == 0) { (amountStock, amountMoney) = (amountStockDesired, amountMoneyDesired); } else { uint amountMoneyOptimal = _quote(amountStockDesired, reserveStock, reserveMoney); if (amountMoneyOptimal <= amountMoneyDesired) { require(amountMoneyOptimal >= amountMoneyMin, "OneSwapRouter: INSUFFICIENT_MONEY_AMOUNT"); (amountStock, amountMoney) = (amountStockDesired, amountMoneyOptimal); } else { uint amountStockOptimal = _quote(amountMoneyDesired, reserveMoney, reserveStock); assert(amountStockOptimal <= amountStockDesired); require(amountStockOptimal >= amountStockMin, "OneSwapRouter: INSUFFICIENT_STOCK_AMOUNT"); (amountStock, amountMoney) = (amountStockOptimal, amountMoneyDesired); } } } function addLiquidity(address stock, address money, bool isOnlySwap, uint amountStockDesired, uint amountMoneyDesired, uint amountStockMin, uint amountMoneyMin, address to, uint deadline) external override ensure(deadline) returns (uint amountStock, uint amountMoney, uint liquidity) { address pair = IOneSwapFactory(factory).tokensToPair(stock, money, isOnlySwap); if (pair == address(0)){ pair = IOneSwapFactory(factory).createPair(stock, money, isOnlySwap); } (amountStock, amountMoney) = _addLiquidity(pair, amountStockDesired, amountMoneyDesired, amountStockMin, amountMoneyMin); _safeTransferFrom(stock, msg.sender, pair, amountStock); _safeTransferFrom(money, msg.sender, pair, amountMoney); liquidity = IOneSwapPool(pair).mint(to); emit AddLiquidity(amountStock, amountMoney, liquidity); } function addLiquidityETH(address token, bool tokenIsStock, bool isOnlySwap, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external payable override ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { address pair; if (tokenIsStock) { pair = IOneSwapFactory(factory).tokensToPair(token, weth, isOnlySwap); if (pair == address(0)){ pair = IOneSwapFactory(factory).createPair(token, weth, isOnlySwap); } (amountToken, amountETH) = _addLiquidity(pair, amountTokenDesired, msg.value, amountTokenMin, amountETHMin); }else{ pair = IOneSwapFactory(factory).tokensToPair(weth, token, isOnlySwap); if (pair == address(0)){ pair = IOneSwapFactory(factory).createPair(weth, token, isOnlySwap); } (amountETH, amountToken) = _addLiquidity(pair, msg.value, amountTokenDesired, amountETHMin, amountTokenMin); } IWETH(weth).deposit{value: amountETH}(); assert(IWETH(weth).transfer(pair, amountETH)); _safeTransferFrom(token, msg.sender, pair, amountToken); liquidity = IOneSwapPool(pair).mint(to); if (msg.value > amountETH) _safeTransferETH(msg.sender, msg.value - amountETH); if (tokenIsStock) { emit AddLiquidity(amountToken, amountETH, liquidity); } else { emit AddLiquidity(amountETH, amountToken, liquidity); } } function _removeLiquidity(address pair, uint liquidity, uint amountStockMin, uint amountMoneyMin, address to) private returns (uint amountStock, uint amountMoney) { IERC20(pair).transferFrom(msg.sender, pair, liquidity); (amountStock, amountMoney) = IOneSwapPool(pair).burn(to); require(amountStock >= amountStockMin, "OneSwapRouter: INSUFFICIENT_STOCK_AMOUNT"); require(amountMoney >= amountMoneyMin, "OneSwapRouter: INSUFFICIENT_MONEY_AMOUNT"); } function removeLiquidity(address pair, uint liquidity, uint amountStockMin, uint amountMoneyMin, address to, uint deadline) external override ensure(deadline) returns (uint amountStock, uint amountMoney) { // ensure pair exist _getTokensFromPair(pair); (amountStock, amountMoney) = _removeLiquidity(pair, liquidity, amountStockMin, amountMoneyMin, to); } function removeLiquidityETH(address pair, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline) external override ensure(deadline) payable returns (uint amountToken, uint amountETH) { address token; (address stock, address money) = _getTokensFromPair(pair); if (stock == weth) { token = money; (amountETH, amountToken) = _removeLiquidity(pair, liquidity, amountETHMin, amountTokenMin, address(this)); } else if (money == weth) { token = stock; (amountToken, amountETH) = _removeLiquidity(pair, liquidity, amountTokenMin, amountETHMin, address(this)); } else { require(false, "OneSwapRouter: PAIR_MISMATCH"); } IWETH(weth).withdraw(amountETH); _safeTransferETH(to, amountETH); _safeTransfer(token, to, amountToken); } function _swap(address input, uint amountIn, address[] memory path, address _to) internal virtual returns (uint[] memory amounts) { amounts = new uint[](path.length + 1); amounts[0] = amountIn; for (uint i = 0; i < path.length; i++) { (address to, bool isLastSwap) = i < path.length - 1 ? (path[i+1], false) : (_to, true); amounts[i + 1] = IOneSwapPair(path[i]).addMarketOrder(input, to, uint112(amounts[i]), isLastSwap); if (!isLastSwap) { (address stock, address money)= _getTokensFromPair(path[i]); input = (stock != input) ? stock : money; } } } function swapToken(address token, uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external override ensure(deadline) returns (uint[] memory amounts) { require(path.length >= 1, "OneSwapRouter: INVALID_PATH"); // ensure pair exist _getTokensFromPair(path[0]); _safeTransferFrom(token, msg.sender, path[0], amountIn); amounts = _swap(token, amountIn, path, to); require(amounts[path.length] >= amountOutMin, "OneSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); } function swapETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable override ensure(deadline) returns (uint[] memory amounts) { require(path.length >= 1, "OneSwapRouter: INVALID_PATH"); // ensure pair exist _getTokensFromPair(path[0]); IWETH(weth).deposit{value: msg.value}(); assert(IWETH(weth).transfer(path[0], msg.value)); amounts = _swap(weth, msg.value, path, to); require(amounts[path.length] >= amountOutMin, "OneSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT"); } function limitOrder(bool isBuy, address pair, uint prevKey, uint price, uint32 id, uint stockAmount, uint deadline) external override ensure(deadline) { (address stock, address money) = _getTokensFromPair(pair); { (uint _stockAmount, uint _moneyAmount) = IOneSwapPair(pair).calcStockAndMoney(uint64(stockAmount), uint32(price)); isBuy ? _safeTransferFrom(money, msg.sender, pair, _moneyAmount) : _safeTransferFrom(stock, msg.sender, pair, _stockAmount); } IOneSwapPair(pair).addLimitOrder(isBuy, msg.sender, uint64(stockAmount), uint32(price), id, uint72(prevKey)); } // todo. add encoded bytes interface for limitOrder. function limitOrderWithETH(bool isBuy, address pair, uint prevKey, uint price, uint32 id, uint stockAmount, uint deadline) external payable override ensure(deadline) { (address stock, address money) = _getTokensFromPair(pair); require(stock == weth || money == weth, "OneSwapRouter: PAIR_MISMATCH"); uint ethLeft; { (uint _stockAmount, uint _moneyAmount) = IOneSwapPair(pair).calcStockAndMoney(uint64(stockAmount), uint32(price)); if (isBuy) { require(msg.value >= _moneyAmount, "OneSwapRouter: INSUFFICIENT_INPUT_AMOUNT"); ethLeft = msg.value - _moneyAmount; }else{ require(msg.value >= _stockAmount, "OneSwapRouter: INSUFFICIENT_INPUT_AMOUNT"); ethLeft = msg.value - _stockAmount; } } IWETH(weth).deposit{value: msg.value - ethLeft}(); assert(IWETH(weth).transfer(pair, msg.value - ethLeft)); IOneSwapPair(pair).addLimitOrder(isBuy, msg.sender, uint64(stockAmount), uint32(price), id, uint72(prevKey)); if (ethLeft > 0) { _safeTransferETH(msg.sender, ethLeft); } } function removeLimitOrder(bool isBuy, address pair, uint prevKey, uint orderId ) external override { IOneSwapPair(pair).removeOrder(isBuy, uint32(orderId), uint72(prevKey)); } function _safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FAILED"); } function _safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED"); } function _safeTransferETH(address to, uint value) internal { // solhint-disable-next-line avoid-low-level-calls (bool success,) = to.call{value:value}(new bytes(0)); require(success, "TransferHelper: ETH_TRANSFER_FAILED"); } function _quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, "OneSwapRouter: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "OneSwapRouter: INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } function _getTokensFromPair(address pair)internal view returns(address stock, address money) { (stock, money) = IOneSwapFactory(factory).getTokensFromPair(pair); require(stock != address(0) && money != address(0), "OneSwapRouter: PAIR_MISMATCH"); } } // SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./interfaces/IOneSwapToken.sol"; abstract contract OneSwapBlackList is IOneSwapBlackList { address private _owner; mapping(address => bool) private _isBlackListed; constructor() public { _owner = msg.sender; } function owner() public view override returns (address) { return _owner; } function isBlackListed(address user) public view override returns (bool) { return _isBlackListed[user]; } modifier onlyOwner() { require(msg.sender == _owner, "msg.sender is not owner"); _; } function changeOwner(address newOwner) public override onlyOwner { _setOwner(newOwner); } function addBlackLists(address[] calldata _evilUser) public override onlyOwner { for (uint i = 0; i < _evilUser.length; i++) { _isBlackListed[_evilUser[i]] = true; } emit AddedBlackLists(_evilUser); } function removeBlackLists(address[] calldata _clearedUser) public override onlyOwner { for (uint i = 0; i < _clearedUser.length; i++) { delete _isBlackListed[_clearedUser[i]]; } emit RemovedBlackLists(_clearedUser); } function _setOwner(address newOwner) internal { if (newOwner != address(0)) { _owner = newOwner; emit OwnerChanged(newOwner); } } } // SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./interfaces/IOneSwapToken.sol"; import "./libraries/SafeMath256.sol"; import "./OneSwapBlackList.sol"; contract OneSwapToken is IOneSwapToken,OneSwapBlackList { using SafeMath256 for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; // solhint-disable-next-line state-visibility uint8 immutable _decimals; constructor (string memory name, string memory symbol, uint256 supply, uint8 decimals) public OneSwapBlackList() { _name = name; _symbol = symbol; _decimals = decimals; _totalSupply = supply; _balances[msg.sender] = supply; } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "OneSwapToken: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "OneSwapToken: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } function burn(uint256 amount) public virtual override { _burn(msg.sender, amount); } function burnFrom(address account, uint256 amount) public virtual override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "OneSwapToken: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } function multiTransfer(uint256[] calldata mixedAddrVal) public override returns (bool) { for (uint i = 0; i < mixedAddrVal.length; i++) { address to = address(mixedAddrVal[i]>>96); uint256 value = mixedAddrVal[i]&0xffffffffffff; _transfer(msg.sender,to,value); } return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "OneSwapToken: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "OneSwapToken: TRANSFER_TO_THE_ZERO_ADDRESS"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "OneSwapToken: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "OneSwapToken: BURN_FROM_THE_ZERO_ADDRESS"); _balances[account] = _balances[account].sub(amount, "OneSwapToken: BURN_AMOUNT_EXCEEDS_BALANCE"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "OneSwapToken: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "OneSwapToken: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 ) internal virtual view { require(!isBlackListed(from), "OneSwapToken: FROM_IS_BLACKLISTED_BY_TOKEN_OWNER"); require(!isBlackListed(to), "OneSwapToken: TO_IS_BLACKLISTED_BY_TOKEN_OWNER"); } } // SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./interfaces/IOneSwapFactory.sol"; import "./OneSwapPair.sol"; contract OneSwapFactory is IOneSwapFactory { struct TokensInPair { address stock; address money; } address public override feeTo; address public override feeToSetter; address public immutable gov; address public immutable weth; uint32 public override feeBPS = 50; mapping(address => TokensInPair) private _pairWithToken; mapping(bytes32 => address) private _tokensToPair; address[] public allPairs; constructor(address _feeToSetter, address _gov, address _weth) public { feeToSetter = _feeToSetter; weth = _weth; gov = _gov; } function createPair(address stock, address money, bool isOnlySwap) external override returns (address pair) { require(stock != money, "OneSwapFactory: IDENTICAL_ADDRESSES"); require(stock != address(0) && money != address(0), "OneSwapFactory: ZERO_ADDRESS"); uint moneyDec = uint(IERC20(money).decimals()); uint stockDec = uint(IERC20(stock).decimals()); require(23 >= stockDec && stockDec >= 0, "OneSwapFactory: STOCK_DECIMALS_NOT_SUPPORTED"); uint dec = 0; if(stockDec >= 4) { dec = stockDec - 4; // now 19 >= dec && dec >= 0 } // 10**19 = 10000000000000000000 // 1<<64 = 18446744073709551616 uint64 priceMul = 1; uint64 priceDiv = 1; bool differenceTooLarge = false; if(moneyDec > stockDec) { if(moneyDec > stockDec + 19) { differenceTooLarge = true; } else { priceMul = uint64(uint(10)**(moneyDec - stockDec)); } } if(stockDec > moneyDec) { if(stockDec > moneyDec + 19) { differenceTooLarge = true; } else { priceDiv = uint64(uint(10)**(stockDec - moneyDec)); } } require(!differenceTooLarge, "OneSwapFactory: DECIMALS_DIFF_TOO_LARGE"); bytes32 salt = keccak256(abi.encodePacked(stock, money, isOnlySwap)); require(_tokensToPair[salt] == address(0), "OneSwapFactory: PAIR_EXISTS"); OneSwapPair oneswap = new OneSwapPair{salt: salt}(weth, stock, money, isOnlySwap, uint64(uint(10)**dec), priceMul, priceDiv); pair = address(oneswap); allPairs.push(pair); _tokensToPair[salt] = pair; _pairWithToken[pair] = TokensInPair(stock, money); emit PairCreated(pair, stock, money, isOnlySwap); } function allPairsLength() external override view returns (uint) { return allPairs.length; } function setFeeTo(address _feeTo) external override { require(msg.sender == feeToSetter, "OneSwapFactory: FORBIDDEN"); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, "OneSwapFactory: FORBIDDEN"); feeToSetter = _feeToSetter; } function setFeeBPS(uint32 _bps) external override { require(msg.sender == gov, "OneSwapFactory: SETTER_MISMATCH"); require(0 <= _bps && _bps <= 50 , "OneSwapFactory: BPS_OUT_OF_RANGE"); feeBPS = _bps; } function getTokensFromPair(address pair) external view override returns (address stock, address money) { stock = _pairWithToken[pair].stock; money = _pairWithToken[pair].money; } function tokensToPair(address stock, address money, bool isOnlySwap) external view override returns (address pair){ bytes32 key = keccak256(abi.encodePacked(stock, money, isOnlySwap)); return _tokensToPair[key]; } } // SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./interfaces/IOneSwapToken.sol"; import "./interfaces/IOneSwapGov.sol"; import "./interfaces/IOneSwapFactory.sol"; contract OneSwapGov is IOneSwapGov { struct Proposal { // FUNDS | PARAM | TEXT address addr; // beneficiary addr | factory addr | N/A uint32 deadline; // unix timestamp | same | same uint32 value; // amount of funds | feeBPS | N/A uint8 _type; // proposal type | same | same } struct Vote { uint8 opinion; address prevVoter; } uint64 private constant _MAX_UINT64 = uint64(-1); uint8 private constant _PROPOSAL_TYPE_FUNDS = 0; uint8 private constant _PROPOSAL_TYPE_PARAM = 1; uint8 private constant _PROPOSAL_TYPE_TEXT = 2; uint32 private constant _MIN_FEE_BPS = 0; uint32 private constant _MAX_FEE_BPS = 50; uint8 private constant _YES = 1; uint8 private constant _NO = 2; uint private constant _VOTE_PERIOD = 3 days; uint private constant _SUBMIT_ONES_PERCENT = 1; address public immutable override ones; uint64 public override numProposals; mapping (uint64 => Proposal) public override proposals; mapping (uint64 => address) public override lastVoter; mapping (uint64 => mapping (address => Vote)) public override votes; mapping (uint64 => uint) private _yesCoins; mapping (uint64 => uint) private _noCoins; constructor(address _ones) public { ones = _ones; // numProposals = 0; } // submit new proposals function submitFundsProposal(string calldata title, string calldata desc, string calldata url, uint32 amount, address beneficiary) external override { if (amount > 0) { uint govCoins = IERC20(ones).balanceOf(address(this)); uint dec = IERC20(ones).decimals(); require(govCoins >= uint(amount) * (10 ** dec), "OneSwapGov: AMOUNT_TOO_LARGE"); } (uint64 proposalID, uint32 deadline) = _newProposal(_PROPOSAL_TYPE_FUNDS, beneficiary, amount); emit NewFundsProposal(proposalID, title, desc, url, deadline, amount, beneficiary); } function submitParamProposal(string calldata title, string calldata desc, string calldata url, uint32 feeBPS, address factory) external override { require(feeBPS >= _MIN_FEE_BPS && feeBPS <= _MAX_FEE_BPS, "OneSwapGov: INVALID_FEE_BPS"); (uint64 proposalID, uint32 deadline) = _newProposal(_PROPOSAL_TYPE_PARAM, factory, feeBPS); emit NewParamProposal(proposalID, title, desc, url, deadline, feeBPS, factory); } function submitTextProposal(string calldata title, string calldata desc, string calldata url) external override { (uint64 proposalID, uint32 deadline) = _newProposal(_PROPOSAL_TYPE_TEXT, address(0), 0); emit NewTextProposal(proposalID, title, desc, url, deadline); } function _newProposal(uint8 _type, address addr, uint32 value) private returns (uint64 proposalID, uint32 deadline) { require(_type >= _PROPOSAL_TYPE_FUNDS && _type <= _PROPOSAL_TYPE_TEXT, "OneSwapGov: INVALID_PROPOSAL_TYPE"); uint totalCoins = IERC20(ones).totalSupply(); uint thresCoins = (totalCoins/100) * _SUBMIT_ONES_PERCENT; uint senderCoins = IERC20(ones).balanceOf(msg.sender); // the sender must have enough coins require(senderCoins >= thresCoins, "OneSwapGov: NOT_ENOUGH_ONES"); proposalID = numProposals; numProposals = numProposals+1; // solhint-disable-next-line not-rely-on-time deadline = uint32(block.timestamp + _VOTE_PERIOD); Proposal memory proposal; proposal._type = _type; proposal.deadline = deadline; proposal.addr = addr; proposal.value = value; proposals[proposalID] = proposal; lastVoter[proposalID] = msg.sender; Vote memory v; v.opinion = _YES; v.prevVoter = address(0); votes[proposalID][msg.sender] = v; } // Have never voted before, vote for the first time function vote(uint64 id, uint8 opinion) external override { uint balance = IERC20(ones).balanceOf(msg.sender); require(balance > 0, "OneSwapGov: NO_ONES"); Proposal memory proposal = proposals[id]; require(proposal.deadline != 0, "OneSwapGov: NO_PROPOSAL"); // solhint-disable-next-line not-rely-on-time require(uint(proposal.deadline) >= block.timestamp, "OneSwapGov: DEADLINE_REACHED"); require(_YES<=opinion && opinion<=_NO, "OneSwapGov: INVALID_OPINION"); Vote memory v = votes[id][msg.sender]; require(v.opinion == 0, "OneSwapGov: ALREADY_VOTED"); v.prevVoter = lastVoter[id]; v.opinion = opinion; votes[id][msg.sender] = v; lastVoter[id] = msg.sender; emit NewVote(id, msg.sender, opinion); } // Have ever voted before, need to change my opinion function revote(uint64 id, uint8 opinion) external override { require(_YES<=opinion && opinion<=_NO, "OneSwapGov: INVALID_OPINION"); Proposal memory proposal = proposals[id]; require(proposal.deadline != 0, "OneSwapGov: NO_PROPOSAL"); // solhint-disable-next-line not-rely-on-time require(uint(proposal.deadline) >= block.timestamp, "OneSwapGov: DEADLINE_REACHED"); Vote memory v = votes[id][msg.sender]; // should have voted before require(v.opinion != 0, "OneSwapGov: NOT_VOTED"); v.opinion = opinion; votes[id][msg.sender] = v; emit NewVote(id, msg.sender, opinion); } // Count the votes, if the result is "Pass", transfer coins to the beneficiary function tally(uint64 proposalID, uint64 maxEntry) external override { Proposal memory proposal = proposals[proposalID]; require(proposal.deadline != 0, "OneSwapGov: NO_PROPOSAL"); // solhint-disable-next-line not-rely-on-time require(uint(proposal.deadline) <= block.timestamp, "OneSwapGov: DEADLINE_NOT_REACHED"); require(maxEntry == _MAX_UINT64 || (maxEntry > 0 && msg.sender == IOneSwapToken(ones).owner()), "OneSwapGov: INVALID_MAX_ENTRY"); address currVoter = lastVoter[proposalID]; require(currVoter != address(0), "OneSwapGov: NO_LAST_VOTER"); uint yesCoinsSum = _yesCoins[proposalID]; uint yesCoinsOld = yesCoinsSum; uint noCoinsSum = _noCoins[proposalID]; uint noCoinsOld = noCoinsSum; for (uint64 i=0; i < maxEntry && currVoter != address(0); i++) { Vote memory v = votes[proposalID][currVoter]; if(v.opinion == _YES) { yesCoinsSum += IERC20(ones).balanceOf(currVoter); } if(v.opinion == _NO) { noCoinsSum += IERC20(ones).balanceOf(currVoter); } delete votes[proposalID][currVoter]; currVoter = v.prevVoter; } if (currVoter != address(0)) { lastVoter[proposalID] = currVoter; if (yesCoinsSum != yesCoinsOld) { _yesCoins[proposalID] = yesCoinsSum; } if (noCoinsSum != noCoinsOld) { _noCoins[proposalID] = noCoinsSum; } } else { bool ok = yesCoinsSum > noCoinsSum; delete proposals[proposalID]; delete lastVoter[proposalID]; delete _yesCoins[proposalID]; delete _noCoins[proposalID]; if (ok) { if (proposal._type == _PROPOSAL_TYPE_FUNDS) { if (proposal.value > 0) { uint dec = IERC20(ones).decimals(); IERC20(ones).transfer(proposal.addr, proposal.value * (10 ** dec)); } } else if (proposal._type == _PROPOSAL_TYPE_PARAM) { IOneSwapFactory(proposal.addr).setFeeBPS(proposal.value); } } emit TallyResult(proposalID, ok); } } } // SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./libraries/Math.sol"; import "./libraries/SafeMath256.sol"; import "./libraries/DecFloat32.sol"; import "./interfaces/IOneSwapFactory.sol"; import "./interfaces/IOneSwapPair.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IWETH.sol"; abstract contract OneSwapERC20 is IERC20 { using SafeMath256 for uint; string private constant _NAME = "OneSwap-Liquidity-Share"; uint8 private constant _DECIMALS = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; function symbol() virtual external view override returns (string memory); function name() external view override returns (string memory) { return _NAME; } function decimals() external view override returns (uint8) { return _DECIMALS; } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(- 1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } // An order can be compressed into 256 bits and saved using one SSTORE instruction // The orders form a single-linked list. The preceding order points to the following order with nextID struct Order { //total 256 bits address sender; //160 bits, sender creates this order uint32 price; // 32-bit decimal floating point number uint64 amount; // 42 bits are used, the stock amount to be sold or bought uint32 nextID; // 22 bits are used } // When the match engine of orderbook runs, it uses follow context to cache data in memory struct Context { // this is the last stop of a multi-stop swap path bool isLastSwap; // this order is a limit order bool isLimitOrder; // the new order's id, it is only used when a limit order is not fully dealt uint32 newOrderID; // for buy-order, it's remained money amount; for sell-order, it's remained stock amount uint remainAmount; // it points to the first order in the opposite order book against current order uint32 firstID; // it points to the first order in the buy-order book uint32 firstBuyID; // it points to the first order in the sell-order book uint32 firstSellID; // the amount goes into the pool, for buy-order, it's money amount; for sell-order, it's stock amount uint amountIntoPool; // the total dealt money and stock in the order book uint dealMoneyInBook; uint dealStockInBook; // cache these values from storage to memory uint reserveMoney; uint reserveStock; uint bookedMoney; uint bookedStock; // reserveMoney or reserveStock is changed bool reserveChanged; // the taker has dealt in the orderbook bool hasDealtInOrderBook; // the current taker order Order order; } // OneSwapPair combines a Uniswap-like AMM and an orderbook abstract contract OneSwapPool is OneSwapERC20, IOneSwapPool { using SafeMath256 for uint; uint private constant _MINIMUM_LIQUIDITY = 10 ** 3; bytes4 internal constant _SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); // these immutable variables are initialized by factory contract address internal immutable _immuWETH; address internal immutable _immuFactory; address internal immutable _immuMoneyToken; address internal immutable _immuStockToken; bool internal immutable _immuIsOnlySwap; // reserveMoney and reserveStock are both uint112, id is 22 bits; they are compressed into a uint256 word uint internal _reserveStockAndMoneyAndFirstSellID; // bookedMoney and bookedStock are both uint112, id is 22 bits; they are compressed into a uint256 word uint internal _bookedStockAndMoneyAndFirstBuyID; uint private _kLast; uint32 private constant _OS = 2; // owner's share uint32 private constant _LS = 3; // liquidity-provider's share uint internal _unlocked = 1; modifier lock() { require(_unlocked == 1, "OneSwap: LOCKED"); _unlocked = 0; _; _unlocked = 1; } function internalStatus() external view returns(uint[3] memory res) { res[0] = _reserveStockAndMoneyAndFirstSellID; res[1] = _bookedStockAndMoneyAndFirstBuyID; res[2] = _kLast; } function stock() external view override returns (address) {return _immuStockToken;} function money() external view override returns (address) {return _immuMoneyToken;} // the following 4 functions load&store compressed storage function getReserves() public override view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) { uint temp = _reserveStockAndMoneyAndFirstSellID; reserveStock = uint112(temp); reserveMoney = uint112(temp>>112); firstSellID = uint32(temp>>224); } function _setReserves(uint stockAmount, uint moneyAmount, uint32 firstSellID) internal { require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "OneSwap: OVERFLOW"); uint temp = (moneyAmount<<112)|stockAmount; emit Sync(temp); temp = (uint(firstSellID)<<224)| temp; _reserveStockAndMoneyAndFirstSellID = temp; } function getBooked() public override view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID) { uint temp = _bookedStockAndMoneyAndFirstBuyID; bookedStock = uint112(temp); bookedMoney = uint112(temp>>112); firstBuyID = uint32(temp>>224); } function _setBooked(uint stockAmount, uint moneyAmount, uint32 firstBuyID) internal { require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "OneSwap: OVERFLOW"); _bookedStockAndMoneyAndFirstBuyID = (uint(firstBuyID)<<224)|(moneyAmount<<112)|stockAmount; } // safely transfer ERC20 tokens function _safeTransfer(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "OneSwap: TRANSFER_FAILED"); } // when orderbook transfer tokens to takers and makers, WETH is automatically changed into ETH, // if this is the last stop of a multi-stop swap path function _transferToken(address token, address to, uint amount, bool isLastPath) internal { if (token == _immuWETH && isLastPath) { IWETH(_immuWETH).withdraw(amount); _safeTransferETH(to, amount); } else { _safeTransfer(token, to, amount); } } function _safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value : value}(new bytes(0)); require(success, "OneSwap: ETH_TRANSFER_FAILED"); } // Give feeTo some liquidity tokens if K got increased since last liquidity-changing function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IOneSwapFactory(_immuFactory).feeTo(); feeOn = feeTo != address(0); uint kLast = _kLast; // gas savings to use cached kLast if (feeOn) { if (kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(_OS); uint denominator = rootK.mul(_LS).add(rootKLast.mul(_OS)); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (kLast != 0) { _kLast = 0; } } // mint new liquidity tokens to 'to' function mint(address to) external override lock returns (uint liquidity) { (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); (uint112 bookedStock, uint112 bookedMoney, ) = getBooked(); uint stockBalance = IERC20(_immuStockToken).balanceOf(address(this)); uint moneyBalance = IERC20(_immuMoneyToken).balanceOf(address(this)); require(stockBalance >= uint(bookedStock) + uint(reserveStock) && moneyBalance >= uint(bookedMoney) + uint(reserveMoney), "OneSwap: INVALID_BALANCE"); stockBalance -= uint(bookedStock); moneyBalance -= uint(bookedMoney); uint stockAmount = stockBalance - uint(reserveStock); uint moneyAmount = moneyBalance - uint(reserveMoney); bool feeOn = _mintFee(reserveStock, reserveMoney); uint _totalSupply = totalSupply; // gas savings by caching totalSupply in memory, // must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(stockAmount.mul(moneyAmount)).sub(_MINIMUM_LIQUIDITY); _mint(address(0), _MINIMUM_LIQUIDITY); // permanently lock the first _MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(stockAmount.mul(_totalSupply) / uint(reserveStock), moneyAmount.mul(_totalSupply) / uint(reserveMoney)); } require(liquidity > 0, "OneSwap: INSUFFICIENT_MINTED"); _mint(to, liquidity); _setReserves(stockBalance, moneyBalance, firstSellID); if (feeOn) _kLast = stockBalance.mul(moneyBalance); emit Mint(msg.sender, (moneyAmount<<112)|stockAmount, to); } // burn liquidity tokens and send stock&money to 'to' function burn(address to) external override lock returns (uint stockAmount, uint moneyAmount) { (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint stockBalance = IERC20(_immuStockToken).balanceOf(address(this)).sub(bookedStock); uint moneyBalance = IERC20(_immuMoneyToken).balanceOf(address(this)).sub(bookedMoney); require(stockBalance >= uint(reserveStock) && moneyBalance >= uint(reserveMoney), "OneSwap: INVALID_BALANCE"); uint liquidity = balanceOf[address(this)]; // we're sure liquidity < totalSupply bool feeOn = _mintFee(reserveStock, reserveMoney); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee stockAmount = liquidity.mul(stockBalance) / _totalSupply; moneyAmount = liquidity.mul(moneyBalance) / _totalSupply; require(stockAmount > 0 && moneyAmount > 0, "OneSwap: INSUFFICIENT_BURNED"); //_burn(address(this), liquidity); balanceOf[address(this)] = 0; totalSupply = totalSupply.sub(liquidity); emit Transfer(address(this), address(0), liquidity); _safeTransfer(_immuStockToken, to, stockAmount); _safeTransfer(_immuMoneyToken, to, moneyAmount); stockBalance = stockBalance - stockAmount; moneyBalance = moneyBalance - moneyAmount; _setReserves(stockBalance, moneyBalance, firstSellID); if (feeOn) _kLast = stockBalance.mul(moneyBalance); emit Burn(msg.sender, (moneyAmount<<112)|stockAmount, to); } // take the extra money&stock in this pair to 'to' function skim(address to) external override lock { address _stock = _immuStockToken; address _money = _immuMoneyToken; (uint112 reserveStock, uint112 reserveMoney, ) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint balanceStock = IERC20(_stock).balanceOf(address(this)); uint balanceMoney = IERC20(_money).balanceOf(address(this)); require(balanceStock >= uint(bookedStock) + uint(reserveStock) && balanceMoney >= uint(bookedMoney) + uint(reserveMoney), "OneSwap: INVALID_BALANCE"); _safeTransfer(_stock, to, balanceStock-reserveStock-bookedStock); _safeTransfer(_money, to, balanceMoney-reserveMoney-bookedMoney); } // sync-up reserve stock&money in pool according to real balance function sync() external override lock { (, , uint32 firstSellID) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint balanceStock = IERC20(_immuStockToken).balanceOf(address(this)); uint balanceMoney = IERC20(_immuMoneyToken).balanceOf(address(this)); require(balanceStock >= bookedStock && balanceMoney >= bookedMoney, "OneSwap: INVALID_BALANCE"); _setReserves(balanceStock-bookedStock, balanceMoney-bookedMoney, firstSellID); } constructor(address weth, address stockToken, address moneyToken, bool isOnlySwap) public { _immuFactory = msg.sender; _immuWETH = weth; _immuStockToken = stockToken; _immuMoneyToken = moneyToken; _immuIsOnlySwap = isOnlySwap; } } contract OneSwapPair is OneSwapPool, IOneSwapPair { // the orderbooks. Gas is saved when using array to store them instead of mapping uint[1<<22] private _sellOrders; uint[1<<22] private _buyOrders; uint32 private constant _MAX_ID = (1<<22)-1; // the maximum value of an order ID uint64 internal immutable _immuStockUnit; uint64 internal immutable _immuPriceMul; uint64 internal immutable _immuPriceDiv; constructor(address weth, address stockToken, address moneyToken, bool isOnlySwap, uint64 stockUnit, uint64 priceMul, uint64 priceDiv) public OneSwapPool(weth, stockToken, moneyToken, isOnlySwap) { _immuStockUnit = stockUnit; _immuPriceMul = priceMul; _immuPriceDiv = priceDiv; } function _expandPrice(uint32 price32) private view returns (RatPrice memory price) { price = DecFloat32.expandPrice(price32); price.numerator *= _immuPriceMul; price.denominator *= _immuPriceDiv; } function symbol() external view override returns (string memory) { string memory s = IERC20(_immuStockToken).symbol(); string memory m = IERC20(_immuMoneyToken).symbol(); return string(abi.encodePacked(s, "/", m, "-Share")); //to concat strings } // when emitting events, solidity's ABI pads each entry to uint256, which is so wasteful // we compress the entries into one uint256 to save gas function _emitNewLimitOrder( uint64 addressLow, /*255~193*/ uint64 totalStockAmount, /*192~128*/ uint64 remainedStockAmount, /*127~64*/ uint32 price, /*63~32*/ uint32 orderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(addressLow); data = (data<<64) | uint(totalStockAmount); data = (data<<64) | uint(remainedStockAmount); data = (data<<32) | uint(price); data = (data<<32) | uint(orderID<<8); if(isBuy) { data = data | 1; } emit NewLimitOrder(data); } function _emitNewMarketOrder( uint136 addressLow, /*255~120*/ uint112 amount, /*119~8*/ bool isBuy /*7~0*/) private { uint data = uint(addressLow); data = (data<<112) | uint(amount); data = data<<8; if(isBuy) { data = data | 1; } emit NewMarketOrder(data); } function _emitOrderChanged( uint64 makerLastAmount, /*159~96*/ uint64 makerDealAmount, /*95~32*/ uint32 makerOrderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(makerLastAmount); data = (data<<64) | uint(makerDealAmount); data = (data<<32) | uint(makerOrderID<<8); if(isBuy) { data = data | 1; } emit OrderChanged(data); } function _emitDealWithPool( uint112 inAmount, /*131~120*/ uint112 outAmount,/*119~8*/ bool isBuy/*7~0*/) private { uint data = uint(inAmount); data = (data<<112) | uint(outAmount); data = data<<8; if(isBuy) { data = data | 1; } emit DealWithPool(data); } function _emitRemoveOrder( uint64 remainStockAmount, /*95~32*/ uint32 orderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(remainStockAmount); data = (data<<32) | uint(orderID<<8); if(isBuy) { data = data | 1; } emit RemoveOrder(data); } // compress an order into a 256b integer function _order2uint(Order memory order) internal pure returns (uint) { uint n = uint(order.sender); n = (n<<32) | order.price; n = (n<<42) | order.amount; n = (n<<22) | order.nextID; return n; } // extract an order from a 256b integer function _uint2order(uint n) internal pure returns (Order memory) { Order memory order; order.nextID = uint32(n & ((1<<22)-1)); n = n >> 22; order.amount = uint64(n & ((1<<42)-1)); n = n >> 42; order.price = uint32(n & ((1<<32)-1)); n = n >> 32; order.sender = address(n); return order; } // returns true if this order exists function _hasOrder(bool isBuy, uint32 id) internal view returns (bool) { if(isBuy) { return _buyOrders[id] != 0; } else { return _sellOrders[id] != 0; } } // load an order from storage, converting its compressed form into an Order struct function _getOrder(bool isBuy, uint32 id) internal view returns (Order memory order, bool findIt) { if(isBuy) { order = _uint2order(_buyOrders[id]); return (order, order.price != 0); } else { order = _uint2order(_sellOrders[id]); return (order, order.price != 0); } } // save an order to storage, converting it into compressed form function _setOrder(bool isBuy, uint32 id, Order memory order) internal { if(isBuy) { _buyOrders[id] = _order2uint(order); } else { _sellOrders[id] = _order2uint(order); } } // delete an order from storage function _deleteOrder(bool isBuy, uint32 id) internal { if(isBuy) { delete _buyOrders[id]; } else { delete _sellOrders[id]; } } function _getFirstOrderID(Context memory ctx, bool isBuy) internal pure returns (uint32) { if(isBuy) { return ctx.firstBuyID; } return ctx.firstSellID; } function _setFirstOrderID(Context memory ctx, bool isBuy, uint32 id) internal pure { if(isBuy) { ctx.firstBuyID = id; } else { ctx.firstSellID = id; } } function removeOrder(bool isBuy, uint32 id, uint72 prevKey) external override lock { Context memory ctx; (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); if(!isBuy) { (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); } Order memory order = _removeOrderFromBook(ctx, isBuy, id, prevKey); // this is the removed order require(msg.sender == order.sender, "OneSwap: NOT_OWNER"); uint stockAmount = uint(order.amount)/*42bits*/ * uint(_immuStockUnit)/*64bits*/; if(isBuy) { RatPrice memory price = _expandPrice(order.price); uint moneyAmount = stockAmount * price.numerator/*54+64bits*/ / price.denominator; ctx.bookedMoney -= moneyAmount; _transferToken(_immuMoneyToken, order.sender, moneyAmount, true); } else { ctx.bookedStock -= stockAmount; _transferToken(_immuStockToken, order.sender, stockAmount, true); } _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); } // remove an order from orderbook and return it function _removeOrderFromBook(Context memory ctx, bool isBuy, uint32 id, uint72 prevKey) internal returns (Order memory) { (Order memory order, bool ok) = _getOrder(isBuy, id); require(ok, "OneSwap: NO_SUCH_ORDER"); if(prevKey == 0) { uint32 firstID = _getFirstOrderID(ctx, isBuy); require(id == firstID, "OneSwap: NOT_FIRST"); _setFirstOrderID(ctx, isBuy, order.nextID); if(!isBuy) { _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); } } else { (uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey); require(findIt, "OneSwap: INVALID_POSITION"); while(prevOrder.nextID != id) { currID = prevOrder.nextID; require(currID != 0, "OneSwap: REACH_END"); (prevOrder, ) = _getOrder(isBuy, currID); } prevOrder.nextID = order.nextID; _setOrder(isBuy, currID, prevOrder); } _emitRemoveOrder(order.amount, id, isBuy); _deleteOrder(isBuy, id); return order; } // insert an order at the head of single-linked list // this function does not check price, use it carefully function _insertOrderAtHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private { order.nextID = _getFirstOrderID(ctx, isBuy); _setOrder(isBuy, id, order); _setFirstOrderID(ctx, isBuy, id); } // prevKey contains 3 orders. try to get the first existing order function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns ( uint32 currID, Order memory prevOrder, bool findIt) { currID = uint32(prevKey&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>24)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>48)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); } } } // Given a valid start position, find a proper position to insert order // prevKey contains three suggested order IDs, each takes 24 bits. // We try them one by one to find a valid start position // can not use this function to insert at head! if prevKey is all zero, it will return false function _insertOrderFromGivenPos(bool isBuy, Order memory order, uint32 id, uint72 prevKey) private returns (bool inserted) { (uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey); if(!findIt) { return false; } return _insertOrder(isBuy, order, prevOrder, id, currID); } // Starting from the head of orderbook, find a proper position to insert order function _insertOrderFromHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private returns (bool inserted) { uint32 firstID = _getFirstOrderID(ctx, isBuy); bool canBeFirst = (firstID == 0); Order memory firstOrder; if(!canBeFirst) { (firstOrder, ) = _getOrder(isBuy, firstID); canBeFirst = (isBuy && (firstOrder.price < order.price)) || (!isBuy && (firstOrder.price > order.price)); } if(canBeFirst) { order.nextID = firstID; _setOrder(isBuy, id, order); _setFirstOrderID(ctx, isBuy, id); return true; } return _insertOrder(isBuy, order, firstOrder, id, firstID); } // starting from 'prevOrder', whose id is 'currID', find a proper position to insert order function _insertOrder(bool isBuy, Order memory order, Order memory prevOrder, uint32 id, uint32 currID) private returns (bool inserted) { while(currID != 0) { bool canFollow = (isBuy && (order.price <= prevOrder.price)) || (!isBuy && (order.price >= prevOrder.price)); if(!canFollow) {break;} Order memory nextOrder; if(prevOrder.nextID != 0) { (nextOrder, ) = _getOrder(isBuy, prevOrder.nextID); bool canPrecede = (isBuy && (nextOrder.price < order.price)) || (!isBuy && (nextOrder.price > order.price)); canFollow = canFollow && canPrecede; } if(canFollow) { order.nextID = prevOrder.nextID; _setOrder(isBuy, id, order); prevOrder.nextID = id; _setOrder(isBuy, currID, prevOrder); return true; } currID = prevOrder.nextID; prevOrder = nextOrder; } return false; } // to query the first sell price, the first buy price and the price of pool function getPrices() external override view returns ( uint firstSellPriceNumerator, uint firstSellPriceDenominator, uint firstBuyPriceNumerator, uint firstBuyPriceDenominator, uint poolPriceNumerator, uint poolPriceDenominator) { (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); poolPriceNumerator = uint(reserveMoney); poolPriceDenominator = uint(reserveStock); firstSellPriceNumerator = 0; firstSellPriceDenominator = 0; firstBuyPriceNumerator = 0; firstBuyPriceDenominator = 0; if(firstSellID!=0) { uint order = _sellOrders[firstSellID]; RatPrice memory price = _expandPrice(uint32(order>>64)); firstSellPriceNumerator = price.numerator; firstSellPriceDenominator = price.denominator; } uint32 id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224); if(id!=0) { uint order = _buyOrders[id]; RatPrice memory price = _expandPrice(uint32(order>>64)); firstBuyPriceNumerator = price.numerator; firstBuyPriceDenominator = price.denominator; } } // Get the orderbook's content, starting from id, to get no more than maxCount orders function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external override view returns (uint[] memory) { if(id == 0) { if(isBuy) { id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224); } else { id = uint32(_reserveStockAndMoneyAndFirstSellID>>224); } } uint[1<<22] storage orderbook; if(isBuy) { orderbook = _buyOrders; } else { orderbook = _sellOrders; } //record block height at the first entry uint order = (block.number<<24) | id; uint addrOrig; // start of returned data uint addrLen; // the slice's length is written at this address uint addrStart; // the address of the first entry of returned slice uint addrEnd; // ending address to write the next order uint count = 0; // the slice's length assembly { addrOrig := mload(0x40) // There is a “free memory pointer” at address 0x40 in memory mstore(addrOrig, 32) //the meaningful data start after offset 32 } addrLen = addrOrig + 32; addrStart = addrLen + 32; addrEnd = addrStart; while(count < maxCount) { assembly { mstore(addrEnd, order) //write the order } addrEnd += 32; count++; if(id == 0) {break;} order = orderbook[id]; require(order!=0, "OneSwap: INCONSISTENT_BOOK"); id = uint32(order&_MAX_ID); } assembly { mstore(addrLen, count) // record the returned slice's length let byteCount := sub(addrEnd, addrOrig) return(addrOrig, byteCount) } } // Get an unused id to be used with new order function _getUnusedOrderID(bool isBuy, uint32 id) internal view returns (uint32) { if(id == 0) { // 0 is reserved id = 1; } for(uint32 i = 0; i < 100 && id <= _MAX_ID; i++) { //try 100 times if(!_hasOrder(isBuy, id)) { return id; } id++; } require(false, "OneSwap: CANNOT_FIND_VALID_ID"); return 0; } function calcStockAndMoney(uint64 amount, uint32 price32) external view override returns (uint stockAmount, uint moneyAmount) { (stockAmount, moneyAmount, ) = _calcStockAndMoney(amount, price32); } function _calcStockAndMoney(uint64 amount, uint32 price32) private view returns (uint stockAmount, uint moneyAmount, RatPrice memory price) { price = _expandPrice(price32); stockAmount = uint(amount)/*42bits*/ * uint(_immuStockUnit)/*64bits*/; moneyAmount = stockAmount * price.numerator/*54+64bits*/ /price.denominator; } function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable override lock { require(_immuIsOnlySwap == false, "OneSwap: LIMIT_ORDER_NOT_SUPPORTED"); Context memory ctx; ctx.hasDealtInOrderBook = false; ctx.isLimitOrder = true; ctx.isLastSwap = true; ctx.order.sender = sender; ctx.order.amount = amount; ctx.order.price = price32; ctx.newOrderID = _getUnusedOrderID(isBuy, id); RatPrice memory price; {// to prevent "CompilerError: Stack too deep, try removing local variables." require((amount >> 42) == 0, "OneSwap: INVALID_AMOUNT"); uint32 m = price32 & DecFloat32.MantissaMask; require(DecFloat32.MinMantissa <= m && m <= DecFloat32.MaxMantissa, "OneSwap: INVALID_PRICE"); uint stockAmount; uint moneyAmount; (stockAmount, moneyAmount, price) = _calcStockAndMoney(amount, price32); if(isBuy) { ctx.remainAmount = moneyAmount; } else { ctx.remainAmount = stockAmount; } } require(ctx.remainAmount < uint(1<<112), "OneSwap: OVERFLOW"); (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); _checkRemainAmount(ctx, isBuy); if(prevKey != 0) { // try to insert it bool inserted = _insertOrderFromGivenPos(isBuy, ctx.order, ctx.newOrderID, prevKey); if(inserted) { // if inserted successfully, record the booked tokens _emitNewLimitOrder(uint64(ctx.order.sender), amount, amount, price32, ctx.newOrderID, isBuy); if(isBuy) { ctx.bookedMoney += ctx.remainAmount; } else { ctx.bookedStock += ctx.remainAmount; } _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); if(ctx.reserveChanged) { _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); } return; } // if insertion failed, we try to match this order and make it deal } _addOrder(ctx, isBuy, price); } function addMarketOrder(address inputToken, address sender, uint112 inAmount, bool isLastSwap) external payable override lock returns (uint) { require(inputToken == _immuMoneyToken || inputToken == _immuStockToken, "OneSwap: INVALID_TOKEN"); bool isBuy = inputToken == _immuMoneyToken; Context memory ctx; ctx.hasDealtInOrderBook = false; ctx.isLimitOrder = false; ctx.isLastSwap = isLastSwap; ctx.remainAmount = inAmount; (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); _checkRemainAmount(ctx, isBuy); ctx.order.sender = sender; if(isBuy) { ctx.order.price = DecFloat32.MaxPrice; } else { ctx.order.price = DecFloat32.MinPrice; } RatPrice memory price = _expandPrice(ctx.order.price); _emitNewMarketOrder(uint136(ctx.order.sender), inAmount, isBuy); return _addOrder(ctx, isBuy, price); } // Check router contract did send me enough tokens. // If Router sent to much tokens, take them as reserve money&stock function _checkRemainAmount(Context memory ctx, bool isBuy) private { if(msg.value != 0) { IWETH(_immuWETH).deposit{value: msg.value}(); } ctx.reserveChanged = false; uint diff; if(isBuy) { uint balance = IERC20(_immuMoneyToken).balanceOf(address(this)); require(balance >= ctx.bookedMoney + ctx.reserveMoney, "OneSwap: MONEY_MISMATCH"); diff = balance - ctx.bookedMoney - ctx.reserveMoney; if(ctx.remainAmount < diff) { ctx.reserveMoney += (diff - ctx.remainAmount); ctx.reserveChanged = true; } } else { uint balance = IERC20(_immuStockToken).balanceOf(address(this)); require(balance >= ctx.bookedStock + ctx.reserveStock, "OneSwap: STOCK_MISMATCH"); diff = balance - ctx.bookedStock - ctx.reserveStock; if(ctx.remainAmount < diff) { ctx.reserveStock += (diff - ctx.remainAmount); ctx.reserveChanged = true; } } require(ctx.remainAmount <= diff, "OneSwap: DEPOSIT_NOT_ENOUGH"); } // internal helper function to add new limit order & market order // returns the amount of tokens which were sent to the taker (from AMM pool and booked tokens) function _addOrder(Context memory ctx, bool isBuy, RatPrice memory price) private returns (uint) { (ctx.dealMoneyInBook, ctx.dealStockInBook) = (0, 0); ctx.firstID = _getFirstOrderID(ctx, !isBuy); uint32 currID = ctx.firstID; ctx.amountIntoPool = 0; while(currID != 0) { // while not reaching the end of single-linked (Order memory orderInBook, ) = _getOrder(!isBuy, currID); bool canDealInOrderBook = (isBuy && (orderInBook.price <= ctx.order.price)) || (!isBuy && (orderInBook.price >= ctx.order.price)); if(!canDealInOrderBook) {break;} // no proper price in orderbook, stop here // Deal in liquid pool RatPrice memory priceInBook = _expandPrice(orderInBook.price); bool allDeal = _tryDealInPool(ctx, isBuy, priceInBook); if(allDeal) {break;} // Deal in orderbook _dealInOrderBook(ctx, isBuy, currID, orderInBook, priceInBook); // if the order in book did NOT fully deal, then this new order DID fully deal, so stop here if(orderInBook.amount != 0) { _setOrder(!isBuy, currID, orderInBook); break; } // if the order in book DID fully deal, then delete this order from storage and move to the next _deleteOrder(!isBuy, currID); currID = orderInBook.nextID; } // Deal in liquid pool if(ctx.isLimitOrder) { // use current order's price to deal with pool _tryDealInPool(ctx, isBuy, price); } else { // the AMM pool can deal with orders with any amount ctx.amountIntoPool += ctx.remainAmount; // both of them are less than 112 bits ctx.remainAmount = 0; } if(ctx.firstID != currID) { //some orders DID fully deal, so the head of single-linked list change _setFirstOrderID(ctx, !isBuy, currID); } uint amountToTaker = _dealWithPoolAndCollectFee(ctx, isBuy); if(ctx.isLimitOrder) { // If a limit order did NOT fully deal, we add it into orderbook _insertOrderToBook(ctx, isBuy, price); } // Please note a market order always fully deals if(isBuy) { ctx.bookedStock -= ctx.dealStockInBook; //If this subtraction overflows, _setBooked will fail } else { ctx.bookedMoney -= ctx.dealMoneyInBook; //If this subtraction overflows, _setBooked will fail } // write the cached values to storage _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); return amountToTaker; } // Given reserveMoney and reserveStock in AMM pool, calculate how much tokens will go into the pool if the // final price is 'price' function _intopoolAmountTillPrice(bool isBuy, uint reserveMoney, uint reserveStock, RatPrice memory price) private pure returns (uint result) { // sqrt(Pold/Pnew) = sqrt((2**32)*M_old*PnewDenominator / (S_old*PnewNumerator)) / (2**16) // sell, stock-into-pool, Pold > Pnew uint numerator = reserveMoney/*112bits*/ * price.denominator/*76+64bits*/; uint denominator = reserveStock/*112bits*/ * price.numerator/*54+64bits*/; if(isBuy) { // buy, money-into-pool, Pold < Pnew // sqrt(Pnew/Pold) = sqrt((2**32)*S_old*PnewNumerator / (M_old*PnewDenominator)) / (2**16) (numerator, denominator) = (denominator, numerator); } numerator = numerator.mul(1<<32); uint quotient = numerator / denominator; uint root = Math.sqrt(quotient); //root is at most 110bits uint diff = 0; if(root <= (1<<16)) { return 0; } else { diff = root - (1<<16); //at most 110bits } if(isBuy) { result = reserveMoney * diff; } else { result = reserveStock * diff; } result /= (1<<16); return result; } // Current order tries to deal against the AMM pool. Returns whether current order fully deals. function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private view returns (bool) { uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price); require(currTokenCanTrade < uint(1<<112), "OneSwap: CURR_TOKEN_TOO_LARGE"); // all the below variables are less t han 112 bits if(!isBuy) { currTokenCanTrade /= _immuStockUnit; //to round currTokenCanTrade *= _immuStockUnit; } if(currTokenCanTrade > ctx.amountIntoPool) { uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool; bool allDeal = diffTokenCanTrade >= ctx.remainAmount; if(allDeal) { diffTokenCanTrade = ctx.remainAmount; } ctx.amountIntoPool += diffTokenCanTrade; ctx.remainAmount -= diffTokenCanTrade; return allDeal; } return false; } // Current order tries to deal against the orders in book function _dealInOrderBook(Context memory ctx, bool isBuy, uint32 currID, Order memory orderInBook, RatPrice memory priceInBook) internal { ctx.hasDealtInOrderBook = true; uint stockAmount; if(isBuy) { uint a = ctx.remainAmount/*112bits*/ * priceInBook.denominator/*76+64bits*/; uint b = priceInBook.numerator/*54+64bits*/ * _immuStockUnit/*64bits*/; stockAmount = a/b; } else { stockAmount = ctx.remainAmount/_immuStockUnit; } if(uint(orderInBook.amount) < stockAmount) { stockAmount = uint(orderInBook.amount); } require(stockAmount < (1<<42), "OneSwap: STOCK_TOO_LARGE"); uint stockTrans = stockAmount/*42bits*/ * _immuStockUnit/*64bits*/; uint moneyTrans = stockTrans * priceInBook.numerator/*54+64bits*/ / priceInBook.denominator/*76+64bits*/; _emitOrderChanged(orderInBook.amount, uint64(stockAmount), currID, isBuy); orderInBook.amount -= uint64(stockAmount); if(isBuy) { //subtraction cannot overflow: moneyTrans and stockTrans are calculated from remainAmount ctx.remainAmount -= moneyTrans; } else { ctx.remainAmount -= stockTrans; } // following accumulations can not overflow, because stockTrans(moneyTrans) at most 106bits(160bits) // we know for sure that dealStockInBook and dealMoneyInBook are less than 192 bits ctx.dealStockInBook += stockTrans; ctx.dealMoneyInBook += moneyTrans; if(isBuy) { _transferToken(_immuMoneyToken, orderInBook.sender, moneyTrans, true); } else { _transferToken(_immuStockToken, orderInBook.sender, stockTrans, true); } } // make real deal with the pool and then collect fee, which will be added to AMM pool function _dealWithPoolAndCollectFee(Context memory ctx, bool isBuy) internal returns (uint) { (uint outpoolTokenReserve, uint inpoolTokenReserve, uint otherToTaker) = ( ctx.reserveMoney, ctx.reserveStock, ctx.dealMoneyInBook); if(isBuy) { (outpoolTokenReserve, inpoolTokenReserve, otherToTaker) = ( ctx.reserveStock, ctx.reserveMoney, ctx.dealStockInBook); } // all these 4 varialbes are less than 112 bits // outAmount is sure to less than outpoolTokenReserve (which is ctx.reserveStock or ctx.reserveMoney) uint outAmount = (outpoolTokenReserve*ctx.amountIntoPool)/(inpoolTokenReserve+ctx.amountIntoPool); if(ctx.amountIntoPool > 0) { _emitDealWithPool(uint112(ctx.amountIntoPool), uint112(outAmount), isBuy); } uint32 feeBPS = IOneSwapFactory(_immuFactory).feeBPS(); // the token amount that should go to the taker, // for buy-order, it's stock amount; for sell-order, it's money amount uint amountToTaker = outAmount + otherToTaker; require(amountToTaker < uint(1<<112), "OneSwap: AMOUNT_TOO_LARGE"); //SWC-Integer Overflow and Underflow: L1002 uint fee = amountToTaker * feeBPS / 10000; amountToTaker -= fee; if(isBuy) { ctx.reserveMoney = ctx.reserveMoney + ctx.amountIntoPool; ctx.reserveStock = ctx.reserveStock - outAmount + fee; } else { ctx.reserveMoney = ctx.reserveMoney - outAmount + fee; ctx.reserveStock = ctx.reserveStock + ctx.amountIntoPool; } address token = _immuMoneyToken; if(isBuy) { token = _immuStockToken; } _transferToken(token, ctx.order.sender, amountToTaker, ctx.isLastSwap); return amountToTaker; } // Insert a not-fully-deal limit order into orderbook function _insertOrderToBook(Context memory ctx, bool isBuy, RatPrice memory price) internal { (uint smallAmount, uint moneyAmount, uint stockAmount) = (0, 0, 0); if(isBuy) { uint tempAmount1 = ctx.remainAmount /*112bits*/ * price.denominator /*76+64bits*/; uint temp = _immuStockUnit * price.numerator/*54+64bits*/; stockAmount = tempAmount1 / temp; uint tempAmount2 = stockAmount * temp; // Now tempAmount1 >= tempAmount2 moneyAmount = (tempAmount2+price.denominator-1)/price.denominator; // round up if(ctx.remainAmount > moneyAmount) { // smallAmount is the gap where remainAmount can not buy an integer of stocks smallAmount = ctx.remainAmount - moneyAmount; } else { moneyAmount = ctx.remainAmount; } //Now ctx.remainAmount >= moneyAmount } else { // for sell orders, remainAmount were always decreased by integral multiple of _immuStockUnit // and we know for sure that ctx.remainAmount % _immuStockUnit == 0 stockAmount = ctx.remainAmount / _immuStockUnit; } ctx.reserveMoney += smallAmount; // If this addition overflows, _setReserves will fail _emitNewLimitOrder(uint64(ctx.order.sender), ctx.order.amount, uint64(stockAmount), ctx.order.price, ctx.newOrderID, isBuy); if(stockAmount != 0) { ctx.order.amount = uint64(stockAmount); if(ctx.hasDealtInOrderBook) { // if current order has ever dealt, it has the best price and can be inserted at head _insertOrderAtHead(ctx, isBuy, ctx.order, ctx.newOrderID); } else { // if current order has NEVER dealt, we must find a proper position for it. // we may scan a lot of entries in the single-linked list and run out of gas _insertOrderFromHead(ctx, isBuy, ctx.order, ctx.newOrderID); } } // Any overflow/underflow in following calculation will be caught by _setBooked if(isBuy) { ctx.bookedMoney += moneyAmount; } else { ctx.bookedStock += ctx.remainAmount; } } receive() external payable { assert(msg.sender == _immuWETH); // only accept ETH via fallback from the WETH contract } } // this contract is only used for test contract OneSwapFactoryTEST { address public feeTo; address public feeToSetter; address public weth; mapping(address => mapping(address => address)) public pairs; address[] public allPairs; event PairCreated(address indexed stock, address indexed money, address pair, uint); function createPair(address stock, address money) external { require(stock != money, "OneSwap: IDENTICAL_ADDRESSES"); require(stock != address(0) && money != address(0), "OneSwap: ZERO_ADDRESS"); require(pairs[stock][money] == address(0), "OneSwap: PAIR_EXISTS"); // single check is sufficient uint8 dec = IERC20(stock).decimals(); require(25 >= dec && dec >= 6, "OneSwap: DECIMALS_NOT_SUPPORTED"); dec -= 6; bytes32 salt = keccak256(abi.encodePacked(stock, money)); OneSwapPair oneswap = new OneSwapPair{salt: salt}(weth, stock, money, false, 1/*uint64(uint(10)**uint(dec))*/, 1, 1); address pair = address(oneswap); pairs[stock][money] = pair; allPairs.push(pair); emit PairCreated(stock, money, pair, allPairs.length); } function allPairsLength() external view returns (uint) { return allPairs.length; } function feeBPS() external pure returns (uint32) { return 30; } } // SPDX-License-Identifier: GPL pragma solidity ^0.6.6; import "./interfaces/IOneSwapToken.sol"; import "./interfaces/IOneSwapFactory.sol"; import "./interfaces/IOneSwapRouter.sol"; import "./interfaces/IOneSwapBuyback.sol"; contract OneSwapBuyback is IOneSwapBuyback { uint256 private constant _MAX_UINT256 = uint256(-1); address public immutable override weth; address public immutable override ones; address public immutable override router; address public immutable override factory; mapping (address => bool) private _mainTokens; address[] private _mainTokenArr; constructor(address _weth, address _ones, address _router, address _factory) public { weth = _weth; ones = _ones; router = _router; factory = _factory; // add WETH & ONES to main token list _mainTokens[_ones] = true; _mainTokenArr.push(_ones); _mainTokens[_weth] = true; _mainTokenArr.push(_weth); } // add token into main token list function addMainToken(address token) external override { require(msg.sender == IOneSwapToken(ones).owner(), "OneSwapBuyback: NOT_ONES_OWNER"); if (!_mainTokens[token]) { _mainTokens[token] = true; _mainTokenArr.push(token); } } // remove token from main token list //SWC-Code With No Effects: L44-L59 function removeMainToken(address token) external override { require(msg.sender == IOneSwapToken(ones).owner(), "OneSwapBuyback: NOT_ONES_OWNER"); require(token != ones, "OneSwapBuyback: REMOVE_ONES_FROM_MAIN"); require(token != weth, "OneSwapBuyback: REMOVE_WETH_FROM_MAIN"); if (_mainTokens[token]) { _mainTokens[token] = false; uint256 lastIdx = _mainTokenArr.length - 1; for (uint256 i = 0; i < lastIdx; i++) { if (_mainTokenArr[i] == token) { _mainTokenArr[i] = _mainTokenArr[lastIdx]; break; } } _mainTokenArr.pop(); } } // check if token is in main token list function isMainToken(address token) external view override returns (bool) { return _mainTokens[token]; } // query main token list function mainTokens() external view override returns (address[] memory list) { list = _mainTokenArr; } // remove Buyback's liquidity from all pairs // swap got minor tokens for main tokens if possible function removeLiquidity(address[] calldata pairs) external override { for (uint256 i = 0; i < pairs.length; i++) { _removeLiquidity(pairs[i]); } } function _removeLiquidity(address pair) private { (address a, address b) = IOneSwapFactory(factory).getTokensFromPair(pair); require(a != address(0) && b != address(0), "OneSwapBuyback: INVALID_PAIR"); uint256 amt = IERC20(pair).balanceOf(address(this)); require(amt > 0, "OneSwapBuyback: NO_LIQUIDITY"); IERC20(pair).approve(router, amt); IOneSwapRouter(router).removeLiquidity( pair, amt, 0, 0, address(this), _MAX_UINT256); // minor -> main bool aIsMain = _mainTokens[a]; bool bIsMain = _mainTokens[b]; if ((aIsMain && !bIsMain) || (!aIsMain && bIsMain)) { _swapForMainToken(pair); } } // swap minor tokens for main tokens function swapForMainToken(address[] calldata pairs) external override { for (uint256 i = 0; i < pairs.length; i++) { _swapForMainToken(pairs[i]); } } function _swapForMainToken(address pair) private { (address a, address b) = IOneSwapFactory(factory).getTokensFromPair(pair); require(a != address(0) && b != address(0), "OneSwapBuyback: INVALID_PAIR"); address mainToken; address minorToken; if (_mainTokens[a]) { require(!_mainTokens[b], "OneSwapBuyback: SWAP_TWO_MAIN_TOKENS"); (mainToken, minorToken) = (a, b); } else { require(_mainTokens[b], "OneSwapBuyback: SWAP_TWO_MINOR_TOKENS"); (mainToken, minorToken) = (b, a); } uint256 minorTokenAmt = IERC20(minorToken).balanceOf(address(this)); require(minorTokenAmt > 0, "OneSwapBuyback: NO_MINOR_TOKENS"); address[] memory path = new address[](1); path[0] = pair; // minor -> main IERC20(minorToken).approve(router, minorTokenAmt); IOneSwapRouter(router).swapToken( minorToken, minorTokenAmt, 0, path, address(this), _MAX_UINT256); } // swap main tokens for ones, then burn all ones function swapForOnesAndBurn(address[] calldata pairs) external override { for (uint256 i = 0; i < pairs.length; i++) { _swapForOnesAndBurn(pairs[i]); } // burn all ones uint256 allOnes = IERC20(ones).balanceOf(address(this)); IOneSwapToken(ones).burn(allOnes); emit BurnOnes(allOnes); } function _swapForOnesAndBurn(address pair) private { (address a, address b) = IOneSwapFactory(factory).getTokensFromPair(pair); require(a != address(0) && b != address(0), "OneSwapBuyback: INVALID_PAIR"); require(a == ones || b == ones, "OneSwapBuyback: ONES_NOT_IN_PAIR"); address token = (a == ones) ? b : a; require(_mainTokens[token], "OneSwapBuyback: MAIN_TOKEN_NOT_IN_PAIR"); uint256 tokenAmt = IERC20(token).balanceOf(address(this)); require(tokenAmt > 0, "OneSwapBuyback: NO_MAIN_TOKENS"); address[] memory path = new address[](1); path[0] = pair; // token -> ones IERC20(token).approve(router, tokenAmt); IOneSwapRouter(router).swapToken( token, tokenAmt, 0, path, address(this), _MAX_UINT256); } }
Public SMART CONTRACT AUDIT REPORT for NODEEX HOLDINGS LIMITED Prepared By: Shuxiao Wang Hangzhou, China September 6, 2020 1/47 PeckShield Audit Report #: 2020-38Public Document Properties Client NODEEX HOLDINGS LIMITED Title Smart Contract Audit Report Target OneSwap Version 1.0 Author Xuxian Jiang Auditors Huaguo Shi, Jeff Liu, Xuxian Jiang Reviewed by Jeff Liu Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 September 6, 2020 Xuxian Jiang Final Release 1.0-rc1 September 5, 2020 Xuxian Jiang Release Candidate #1 0.4 September 4, 2020 Xuxian Jiang Additional Findings #3 0.3 September 1, 2020 Xuxian Jiang Additional Findings #2 0.2 August 29, 2020 Xuxian Jiang Additional Findings #1 0.1 August 27, 2020 Xuxian Jiang Initial Draft 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/47 PeckShield Audit Report #: 2020-38Public Contents 1 Introduction 5 1.1 About OneSwap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3 Detailed Results 13 3.1 Better Handling of Ownership Transfers . . . . . . . . . . . . . . . . . . . . . . . . 13 3.2 Front-Running of Proposal Tallies . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.3 Overlapped Time Windows Between Vote and Tally . . . . . . . . . . . . . . . . . . 16 3.4 Removal of Initial Nop Iterations in removeMainToken() . . . . . . . . . . . . . . . . 18 3.5 Incompatibility with Deflationary Tokens . . . . . . . . . . . . . . . . . . . . . . . . 20 3.6 Tightened Sanity Checks in limitOrderWithETH() . . . . . . . . . . . . . . . . . . . 22 3.7 Non-Payable removeLiquidityETH() . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 3.8 Cached/Randomized ID For Unused OrderID Lookup . . . . . . . . . . . . . . . . . 25 3.9 Gas-Efficient New Pair Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 3.10 Burnability of Assets Owned By Blacklisted Addresses . . . . . . . . . . . . . . . . . 28 3.11 Accommodation of approve() Idiosyncrasies . . . . . . . . . . . . . . . . . . . . . . 30 3.12 Improved Handling of Corner Cases in SupervisedSend . . . . . . . . . . . . . . . . . 31 3.13 Consistent Adherence of Checks-Effects-Interactions . . . . . . . . . . . . . . . . . . 33 3.14 Improved Precision Calculation in Trading Fee Calculation . . . . . . . . . . . . . . . 34 3.15 Less Friction For Improved Buybacks and Order Matching . . . . . . . . . . . . . . . 36 3.16 Other Suggestions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 4 Conclusion 39 3/47 PeckShield Audit Report #: 2020-38Public 5 Appendix 40 5.1 Basic Coding Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5.1.1 Constructor Mismatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5.1.2 Ownership Takeover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5.1.3 Redundant Fallback Function . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5.1.4 Overflows & Underflows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5.1.5 Reentrancy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 5.1.6 Money-Giving Bug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 5.1.7 Blackhole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 5.1.8 Unauthorized Self-Destruct . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 5.1.9 Revert DoS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 5.1.10 Unchecked External Call. . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 5.1.11 Gasless Send. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 5.1.12 SendInstead Of Transfer . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 5.1.13 Costly Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 5.1.14 (Unsafe) Use Of Untrusted Libraries . . . . . . . . . . . . . . . . . . . . . . 42 5.1.15 (Unsafe) Use Of Predictable Variables . . . . . . . . . . . . . . . . . . . . . 43 5.1.16 Transaction Ordering Dependence . . . . . . . . . . . . . . . . . . . . . . . 43 5.1.17 Deprecated Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 5.2 Semantic Consistency Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 5.3 Additional Recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 5.3.1 Avoid Use of Variadic Byte Array . . . . . . . . . . . . . . . . . . . . . . . . 43 5.3.2 Make Visibility Level Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . 44 5.3.3 Make Type Inference Explicit . . . . . . . . . . . . . . . . . . . . . . . . . . 44 5.3.4 Adhere To Function Declaration Strictly . . . . . . . . . . . . . . . . . . . . 44 References 45 4/47 PeckShield Audit Report #: 2020-38Public 1 | Introduction Given the opportunity to review the OneSwap design document and related smart contract source code, we in the report outline our systematic approach to evaluate potential security issues in the smartcontractimplementation,exposepossiblesemanticinconsistenciesbetweensmartcontractcode and design document, and provide additional suggestions or recommendations for improvement. Our results show that the given branch of OneSwap 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 OneSwap OneSwap is a fully decentralized exchange protocol on smart contract that uniquely supports both traditional order book (either market or limit orders) as well as automated market making (AMM). With permission-free token listing, users are able to establish liquidity pools without permission, and make markets through automated algorithms. It also has the plan to support liquidity mining and trade-driven mining simultaneously, providing both platform tokens and transaction fees as revenues. OneSwap pushes forward the current AMM-based DEX frontline and presents a valuable contribution to current DeFi ecosystem. The basic information of OneSwap is as follows: Table 1.1: Basic Information of OneSwap ItemDescription IssuerNODEEX HOLDINGS LIMITED Website https://www.oneswap.net/ TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report September 6, 2020 In the following, we show the Git repository of reviewed files and the commit hash value used in 5/47 PeckShield Audit Report #: 2020-38Public this audit: •https://github.com/oneswap/oneswap _contract_ethereum (4194ac1) 1.2 About PeckShield PeckShield Inc. [20] 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; •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 6/47 PeckShield Audit Report #: 2020-38Public 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/47 PeckShield Audit Report #: 2020-38Public 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 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-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. 8/47 PeckShield Audit Report #: 2020-38Public 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/47 PeckShield Audit Report #: 2020-38Public 2 | Findings 2.1 Summary HereisasummaryofourfindingsafteranalyzingtheOneSwapimplementation. Duringthefirstphase of our audit, we studied the smart contract source code and ran our in-house static code analyzer through the codebase. We also measured the gas consumption of key operations with comparison with the popular UniswapV2 . The purpose here is to not only statically identify known coding bugs, and then manually verify (reject or confirm) issues reported by our tool, but also understand the performance in a realistic setting. Figure 2.1: Gas Consumption Comparison Between OneSwapand UniswapV2 The performance comparison shows that OneSwapoutperforms UniswapV2 in almost all aspects despite the additional support of limit orders in a DEX setting. In particular, the adoption of a proxy-based approach (Section 3.9) greatly reduces the gas cost for the creation of a new pair. Also, a variety of optimization efforts, including the clever use of immutable members, the packed design of orders and other data structures, as well as the efficient communication between proxy and logic, eventually pay off even with the burden of integrated limit order support in OneSwap. Among 10/47 PeckShield Audit Report #: 2020-38Public all audited DeFi projects, OneSwapis exceptional and really stands out in their extreme quest and dedication to maximize gas optimization. Severity # of Findings Critical 0 High 1 Medium 3 Low 9 Informational 2 Total 15 Beside the performance measurement, we further manually review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. So far, we have 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, 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. 11/47 PeckShield Audit Report #: 2020-38Public 2.2 Key Findings Overall, these smart contracts are well-designed and engineered, though the implementation can be improvedbyresolvingtheidentifiedissues(showninTable2.1), including 1high-severityvulnerability, 3medium-severityvulnerabilities, 9low-severityvulnerabilities, and 2informationalrecommendations. Table 2.1: Key OneSwap Audit Findings ID Severity Title Category Status PVE-001 Low BetterHandling ofOwnership Transfers Business Logics Fixed PVE-002 High Front-Running ofProposal Tallies Time and State Fixed PVE-003 Low Overlapped TimeWindows Between Vote andTallyTime and State Fixed PVE-004 Informational Removal ofInitialNopIterations in removeMainToken()Coding Practices Fixed PVE-005 Medium Incompatibility withDeflationary Tokens Business Logics Partially Fixed PVE-006 Low Tightened Sanity Checks in limitOrderWithETH()Security Features Fixed PVE-007 Medium Non-Payable removeLiquidityETH() Coding Practices Fixed PVE-008 Low Cached/Randomized IDForUnusedOrderID LookupCoding Practices Fixed PVE-009 Medium Gas-Efficient NewPairDeployment Coding Practices Fixed PVE-010 Informational Burnability ofAssetsOwnedByBlacklisted AddressesBusiness Logics Fixed PVE-011 Low Accommodation ofapprove() Idiosyncrasies Business Logics Fixed PVE-012 Low Improved Handling ofCornerCasesin SupervisedSendBusiness Logics Fixed PVE-013 Low Consistent Adherence of Checks-Effects-InteractionsTime and State Fixed PVE-014 Low Improved Precision Calculation inTrading FeeCalculationCoding Practice Fixed PVE-015 Low LessFriction ForImproved Buybacks and OrderMatchingCoding Practice Fixed Please refer to Section 3 for details. 12/47 PeckShield Audit Report #: 2020-38Public 3 | Detailed Results 3.1 Better Handling of Ownership Transfers •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Medium•Target: OneSwapBlackList •Category: Business Logics [12] •CWE subcategory: CWE-841 [8] Description The changeOwner() function in the OneSwapBlackList contract allows the current owner of the contract to transfer her privilege to another address. However, in the ownership transfer implementation, the newOwner is directly stored into the storage, _owner, after only validating that the newOwner is a non-zero address (line 45). 26 function changeOwner ( address newOwner ) public o v e r r i d e onlyOwner { 27 _setOwner ( newOwner ) ; 28 } 30 function a d d B l a c k L i s t s ( address [ ] c a l l d a t a _ e v i l U s e r ) public o v e r r i d e onlyOwner { 31 for (uint i = 0 ; i < _ e v i l U s e r . length ; i ++) { 32 _ i s B l a c k L i s t e d [ _ e v i l U s e r [ i ] ] = true ; 33 } 34 emit AddedBlackLists ( _ e v i l U s e r ) ; 35 } 37 function r e m o v e B l a c k L i s t s ( address [ ] c a l l d a t a _clearedUser ) public o v e r r i d e onlyOwner { 38 for (uint i = 0 ; i < _clearedUser . length ; i ++) { 39 delete _ i s B l a c k L i s t e d [ _clearedUser [ i ] ] ; 40 } 41 emit RemovedBlackLists ( _clearedUser ) ; 42 } 44 function _setOwner ( address newOwner ) i n t e r n a l { 45 i f( newOwner != address (0) ) { 13/47 PeckShield Audit Report #: 2020-38Public 46 _owner = newOwner ; 47 emit OwnerChanged ( newOwner ) ; 48 } 49 } Listing 3.1: OneSwapBlackList.sol This is reasonable under the assumption that the newOwnerparameter 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 OneSwap 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 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. Recommendation As suggested, the ownership transition can be better managed with a two- step approach, such as, using these two functions: changeOwner() and acceptOwner() . Specifically, the changeOwner() function keeps the new address in the storage, _newOwner , instead of modifying the _ownerdirectly. The acceptOwner() function checks whether _newOwner ismsg.sender to ensure that _newOwner signs the transaction and verifies herself as the new owner. Only after the successful verification, _newOwner would effectively become the _owner. 69 function changeOwner ( address newOwner ) i n t e r n a l { 70 require ( newOwner != address (0) , " Owner should not be 0 address " ) ; 71 require ( newOwner != _owner , " The current and new owner cannot be the same " ) ; 72 require ( newOwner != _newOwner , " Cannot set the candidate owner to the same address " ) ; 73 _newOwner = newOwner ; 74 } 76 function acceptOwner ( ) public { 77 require (msg.sender == _newOwner , " msg . sender and _newOwner must be the same " ) ; 78 _owner = _newOwner ; 79 emit O w n e r s h i p T r a n s f e r r e d ( _owner , _newOwner) ; 80 } Listing 3.2: OneSwapBlackList.sol ( revised ) Status The issue has been fixed by this commit: 49b5c8d0392e828b735445980e364d5ddc1c8542. 14/47 PeckShield Audit Report #: 2020-38Public 3.2 Front-Running of Proposal Tallies •ID: PVE-002 •Severity: High •Likelihood: Medium •Impact: High•Target: OneSwapGov •Category: Time and State [10] •CWE subcategory: CWE-362 [4] Description OneSwap defines a standard work-flow to submit, vote, and execute proposals that enact on the system-wideoperations. Therearefourtypesofproposals,i.e., _PROPOSAL_TYPE_FUNDS ,_PROPOSAL_TYPE_PARAM ,_PROPOSAL_TYPE_UPGRADE , and _PROPOSAL_TYPE_TEXT . The _PROPOSAL_TYPE_FUNDS proposal allows for the allocation of certain onesassets to fund a particular project (or effort); the _PROPOSAL_TYPE_PARAM pro- posal enables dynamic configuration of system-wide protocol fee in BPS; the _PROPOSAL_TYPE_UPGRADE proposal allows for upgrade of the OneSwapDEX engine; the last type, i.e., _PROPOSAL_TYPE_TEXT , is currently a placeholder. The proposal falls in three different phases: submit,vote, and tally. The tallyphase will immediately execute the proposal if passed. Our analysis shows that the tally()function counts the user votes and is responsible for execute passed proposals. We notice the criteria of determining whether a proposal is passed is based on the balance sum of users who voted yes. And the balance is measured at the very moment when tally() occurs. 141 // Count the votes , if the result is " Pass ", transfer coins to the beneficiary 142 function t a l l y ( uint64 proposalID , uint64 maxEntry ) external o v e r r i d e { 143 P ro p o sa l memory p r o p o s a l = p r o p o s a l s [ p r o p o s a l I D ] ; 144 require ( p r o p o s a l . d e a d l i n e != 0 , " OneSwapGov : NO_PROPOSAL " ) ; 145 // solhint - disable -next - line not -rely -on - time 146 require (uint ( p r o p o s a l . d e a d l i n e ) <= block .timestamp ," OneSwapGov : DEADLINE_NOT_REACHED " ) ; 147 require ( maxEntry == _MAX_UINT64 ( maxEntry > 0 && msg.sender == IOneSwapToken ( ones ) . owner ( ) ) , 148 " OneSwapGov : INVALID_MAX_ENTRY " ) ; 150 address c u r r V o t e r = l a s t V o t e r [ p r o p o s a l I D ] ; 151 require ( c u r r V o t e r != address (0) , " OneSwapGov : NO_LAST_VOTER " ) ; 152 uint yesCoinsSum = _yesCoins [ p r o p o s a l I D ] ; 153 uint yesCoinsOld = yesCoinsSum ; 154 uint noCoinsSum = _noCoins [ p r o p o s a l I D ] ; 155 uint noCoinsOld = noCoinsSum ; 157 for (uint64 i =0; i < maxEntry && c u r r V o t e r != address (0) ; i ++) { 158 Vote memory v = v o t e s [ p r o p o s a l I D ] [ c u r r V o t e r ] ; 159 i f( v . o p i n i o n == _YES) { 160 yesCoinsSum += IERC20 ( ones ) . balanceOf ( c u r r V o t e r ) ; 15/47 PeckShield Audit Report #: 2020-38Public 161 } 162 i f( v . o p i n i o n == _NO) { 163 noCoinsSum += IERC20 ( ones ) . balanceOf ( c u r r V o t e r ) ; 164 } 165 delete v o t e s [ p r o p o s a l I D ] [ c u r r V o t e r ] ; 166 c u r r V o t e r = v . prevVoter ; 167 } 169 . . . 170 } Listing 3.3: OneSwapGov.sol As a result, if a malicious actor chooses to front-run the tally()transaction, with enough voting assets, the actor can largely control the tally()results. And flashloans can readily meet the need of enough voting assets for this front-running attack. The fundamental reason while such attack is possible is due to the way how voting weights are calculated. Without locking up any asset to be committed for the votes, the proposal-based governance system carry less weight in the final results. Moreover, by only counting the voting weights when the tally()operation occurs and the tally()operation may not finish within a single transaction, it unnecessarily provides room for manipulation. Recommendation Develop an effective counter-measure against the manipulation of tally() results. StatusTheissuehasbeenconfirmedandfixedbyproposinganewgovernanceimplementationin this commit: 49b5c8d0392e828b735445980e364d5ddc1c8542. The new governance requires asset lockups to better serve the governance purposes. 3.3 Overlapped Time Windows Between Vote and Tally •ID: PVE-003 •Severity: Low •Likelihood: Medium •Impact: Low•Target: OneSwapGov •Category: Time and State [10] •CWE subcategory: CWE-362 [4] Description As described in Section 3.2, OneSwap defines a standard work-flow to submit, vote, and execute pro- posalsthatenactonthesystem-wideoperations. Aproposalfallsinthreedifferentstates, i.e., submit, vote, and tally. After a proposal is submitted, users can vote it within a pre-defined _VOTE_PERIOD . 16/47 PeckShield Audit Report #: 2020-38Public This _VOTE_PERIOD is hard-coded constant of 3days. After this voting period, the voted proposal can then be tallied to decide whether the proposal should be next executed or not. Our analysis shows that the logic to enforce the voting period introduces a corner case that needs to be better handled. Specifically, as shown in the following code snippet, the proposal, once submitted, can be voted before the deadline, i.e., deadline = uint32(block.timestamp + _VOTE_PERIOD ). More precisely, any vote will be accepted if the following condition is satisfied: require(uint( proposal.deadline)>= block.timestamp) (line 108). 100 // Have never voted before , vote for the first time 101 function vote ( uint64 id , uint8 o p i n i o n ) external o v e r r i d e { 102 uint balance = IERC20 ( ones ) . balanceOf ( msg.sender ) ; 103 require (balance > 0 , " OneSwapGov : NO_ONES " ) ; 105 P ro p o sa l memory p r o p o s a l = p r o p o s a l s [ i d ] ; 106 require ( p r o p o s a l . d e a d l i n e != 0 , " OneSwapGov : NO_PROPOSAL " ) ; 107 // solhint - disable -next - line not -rely -on - time 108 require (uint ( p r o p o s a l . d e a d l i n e ) >= block .timestamp ," OneSwapGov : DEADLINE_REACHED " ) ; 110 require (_YES <=o p i n i o n && opinion <= _NO, " OneSwapGov : INVALID_OPINION " ) ; 111 Vote memory v = v o t e s [ i d ] [ msg.sender ] ; 112 require ( v . o p i n i o n == 0 , " OneSwapGov : ALREADY_VOTED " ) ; 114 v . prevVoter = l a s t V o t e r [ i d ] ; 115 v . o p i n i o n = o p i n i o n ; 116 v o t e s [ i d ] [ msg.sender ] = v ; 118 l a s t V o t e r [ i d ] = msg.sender ; 120 emit NewVote ( id , msg.sender , o p i n i o n ) ; 121 } Listing 3.4: OneSwapGov.sol For the tally()operation, it can be performed when the following timing is met, i.e., require(uint (proposal.deadline)<= block.timestamp) . Apparently, there is an overlap when require(uint(proposal .deadline)= block.timestamp) . If there is an ongoing voting transaction and the tally transaction included in the same block, whether the voting is counted based on the transaction ordering within this particular block. If the voting transaction is arranged earlier within the block, it will be counted. Otherwise, it will not! This certainly brings confusions and should be avoided. Recommendation Ensure there is no overlap between the time windows for voting and tallying. We can either ensure vote()can only occur when require(uint(proposal.deadline)> block.timestamp )(so tally()can occur when require(uint(proposal.deadline)<= block.timestamp) ) or tally()can only happen when require(uint(proposal.deadline)< block.timestamp) (so vote()can occur when require(uint(proposal.deadline)>= block.timestamp) ), but not both. 17/47 PeckShield Audit Report #: 2020-38Public 100 // Have never voted before , vote for the first time 101 function vote ( uint64 id , uint8 o p i n i o n ) external o v e r r i d e { 102 uint balance = IERC20 ( ones ) . balanceOf ( msg.sender ) ; 103 require (balance > 0 , " OneSwapGov : NO_ONES " ) ; 105 P ro p o sa l memory p r o p o s a l = p r o p o s a l s [ i d ] ; 106 require ( p r o p o s a l . d e a d l i n e != 0 , " OneSwapGov : NO_PROPOSAL " ) ; 107 // solhint - disable -next - line not -rely -on - time 108 require (uint ( p r o p o s a l . d e a d l i n e ) > block .timestamp ," OneSwapGov : DEADLINE_REACHED ") ; 110 require (_YES <=o p i n i o n && opinion <= _NO, " OneSwapGov : INVALID_OPINION " ) ; 111 Vote memory v = v o t e s [ i d ] [ msg.sender ] ; 112 require ( v . o p i n i o n == 0 , " OneSwapGov : ALREADY_VOTED " ) ; 114 v . prevVoter = l a s t V o t e r [ i d ] ; 115 v . o p i n i o n = o p i n i o n ; 116 v o t e s [ i d ] [ msg.sender ] = v ; 118 l a s t V o t e r [ i d ] = msg.sender ; 120 emit NewVote ( id , msg.sender , o p i n i o n ) ; 121 } Listing 3.5: OneSwapGov.sol (revised) Status The issue has been confirmed and fixed by proposing a new governance implementation in this commit: 49b5c8d0392e828b735445980e364d5ddc1c8542. The new governance implementation takes care of the above time overlaps between vote and tally. 3.4 Removal of Initial Nop Iterations in removeMainToken() •ID: PVE-004 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: OneSwapBuyback •Category: Coding Practices [11] •CWE subcategory: CWE-1041 [2] Description OneSwap has an interesting buy-back mechanism in place that can be used to purchase (and burn) the protocol tokens. It allows for flexible and dynamic configuration of so-called main tokens so that when the provided liquidity needs to withdraw, it only retains these _mainTokens (likely with greater liquidity/trading volume or more stable price). 18/47 PeckShield Audit Report #: 2020-38Public When the OneSwap protocol is deployed, the contract’s constructor will automatically place both onesand WETHasmain tokens . These two will always be considered as main tokens and cannot be removed. 42 // remove token from main token list 43 function removeMainToken ( address token ) external o v e r r i d e { 44 require (msg.sender == IOneSwapToken ( ones ) . owner ( ) , " OneSwapBuyback : NOT_ONES_OWNER " ) ; 45 require ( token != ones , " OneSwapBuyback : REMOVE_ONES_FROM_MAIN " ) ; 46 require ( token != weth , " OneSwapBuyback : REMOVE_WETH_FROM_MAIN " ) ; 47 i f( _mainTokens [ token ] ) { 48 _mainTokens [ token ] = f a l s e ; 49 uint256 l a s t I d x = _mainTokenArr . length *1 ; 50 for (uint256 i = 0 ; i < l a s t I d x ; i ++) { 51 i f( _mainTokenArr [ i ] == token ) { 52 _mainTokenArr [ i ] = _mainTokenArr [ l a s t I d x ] ; 53 break ; 54 } 55 } 56 _mainTokenArr . pop ( ) ; 57 } 58 } Listing 3.6: OneSwapBuyback.sol Therefore, the removeMainToken() routine (that is tasked to dynamically remove a given main token) can be slightly optimized to skip the checking of these two coins. And these two coins always occupy the first two slots in the internal _mainTokens array. Recommendation Optimize the removeMainToken() logic as the first two are pre-occupied and cannot be removed as shown below (line 50). 42 // remove token from main token list 43 function removeMainToken ( address token ) external o v e r r i d e { 44 require (msg.sender == IOneSwapToken ( ones ) . owner ( ) , " OneSwapBuyback : NOT_ONES_OWNER " ) ; 45 require ( token != ones , " OneSwapBuyback : REMOVE_ONES_FROM_MAIN " ) ; 46 require ( token != weth , " OneSwapBuyback : REMOVE_WETH_FROM_MAIN " ) ; 47 i f( _mainTokens [ token ] ) { 48 _mainTokens [ token ] = f a l s e ; 49 uint256 l a s t I d x = _mainTokenArr . length *1 ; 50 for (uint256 i = 2 ; i < l a s t I d x ; i ++) { 51 i f( _mainTokenArr [ i ] == token ) { 52 _mainTokenArr [ i ] = _mainTokenArr [ l a s t I d x ] ; 53 break ; 54 } 55 } 56 _mainTokenArr . pop ( ) ; 57 } 58 } Listing 3.7: OneSwapBuyback.sol 19/47 PeckShield Audit Report #: 2020-38Public Status The issue has been fixed by this commit: 49b5c8d0392e828b735445980e364d5ddc1c8542. 3.5 Incompatibility with Deflationary Tokens •ID: PVE-005 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: OneSwapRouter •Category: Business Logics [12] •CWE subcategory: CWE-841 [8] Description In OneSwap, the OneSwapRouter contract is designed to be the main entry for interaction with trading users. In particular, one entry routine, i.e., swapToken() , accepts asset transfer-in and swaps it for another. Naturally, the contract implements a number of low-level helper routines to transfer assets into or out of OneSwap. These asset-transferring routines work as expected with standard ERC20 tokens: namely the vault’s internal asset balances are always consistent with actual token balances maintained in individual ERC20 token contract. 132 function _swap( address input , uint amountIn , address [ ]memory path , address _to ) i n t e r n a l v i r t u a l returns (uint [ ]memory amounts ) { 133 amounts = new uint [ ] ( path . length + 1) ; 134 amounts [ 0 ] = amountIn ; 136 for (uint i = 0 ; i < path . length ; i ++) { 137 (address to , bool isLastSwap ) = i < path . length *1 ? ( path [ i +1] , f a l s e ) : ( _to , true ) ; 138 amounts [ i + 1 ] = IOneSwapPair ( path [ i ] ) . addMarketOrder ( input , to , uint112 ( amounts [ i ] ) , isLastSwap ) ; 139 i f( ! isLastSwap ) { 140 (address stock , address money )= _getTokensFromPair ( path [ i ] ) ; 141 i n p u t = ( s t o c k != i n p u t ) ? s t o c k : money ; 142 } 143 } 144 } 146 function swapToken ( address token , uint amountIn , uint amountOutMin , address [ ] c a l l d a t a path , 147 address to , uint d e a d l i n e ) external o v e r r i d e e n s u r e ( d e a d l i n e ) returns (uint [ ] memory amounts ) { 149 require ( path . length >= 1 , " OneSwapRouter : INVALID_PATH " ) ; 150 // ensure pair exist 151 _getTokensFromPair ( path [ 0 ] ) ; 152 _safeTransferFrom ( token , msg.sender , path [ 0 ] , amountIn ) ; 153 amounts = _swap( token , amountIn , path , to ) ; 20/47 PeckShield Audit Report #: 2020-38Public 154 require ( amounts [ path . length ] >= amountOutMin , " OneSwapRouter : INSUFFICIENT_OUTPUT_AMOUNT " ) ; 155 } Listing 3.8: OneSwapRouter.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 transfer or 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 swapToken() , 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 OneSwap and affects protocol-wide operation and maintenance. A similar issue can also be found in SupervisedSend . One possible 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 transferortransferFrom will always result in full transfer, we need to ensure the increased or decreased amount in the pool before and after the transferortransferFrom 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. Another mitigation is to regulate the set of ERC20 tokens that are permitted into OneSwap for indexing. However, as a trustless intermediary, OneSwap may not be in the position to effectively regulate the entire process. Meanwhile, there exist certain assets that may exhibit control switches that can be dynamically exercised to convert into deflationary. We need to point out that this issue can be traced back to the Periphery codebase of UniswapV2 . Recommendation To accommodate the support of possible deflationary tokens, it is better to check the balance before and after the transferFrom() call to ensure the book-keeping amount is accurate. This support may bring additional gas cost. Status The issue has been confirmed and accordingly fixed by measuring the balances right before the low-level asset transfer and right after the transfer. The difference is used to calculate the actually transferred asset amount. 21/47 PeckShield Audit Report #: 2020-38Public 3.6 Tightened Sanity Checks in limitOrderWithETH() •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Medium•Target: OneSwapRouter •Category: Security Features [9] •CWE subcategory: CWE-287 [3] Description As mentioned in Section 3.5, the OneSwapRouter contract is designed to be the main entry for in- teraction with trading users. Another specific entry routine, i.e., limitOrderWithETH() , allows for submitting a limit order involved with ETHtrading. It conveniently wraps the deposited ETHs into WETHs in order to take advantage of the uniform, standardized trading interface of OneSwapPair . 183 function limitOrderWithETH ( bool isBuy , address p a i r , uint prevKey , uint p r i c e , uint32 id , 184 uint stockAmount , uint d e a d l i n e ) external payable o v e r r i d e e n s u r e ( d e a d l i n e ) { 185 (address stock , address money ) = _getTokensFromPair ( p a i r ) ; 186 require ( s t o c k == weth money == weth , " OneSwapRouter : PAIR_MISMATCH " ) ; 187 uint e t h L e f t ; 188 { 189 (uint _stockAmount , uint _moneyAmount) = IOneSwapPair ( p a i r ) . calcStockAndMoney ( uint64 ( stockAmount ) , uint32 ( p r i c e ) ) ; 190 i f( isBuy ) { 191 require (msg.value >= _moneyAmount , " OneSwapRouter : INSUFFICIENT_INPUT_AMOUNT " ) ; 192 e t h L e f t = msg.value *_moneyAmount ; 193 }e l s e { 194 require (msg.value >= _stockAmount , " OneSwapRouter : INSUFFICIENT_INPUT_AMOUNT " ) ; 195 e t h L e f t = msg.value *_stockAmount ; 196 } 197 } 198 199 IWETH( weth ) . d e p o s i t { value :msg.value *e t h L e f t }() ; 200 a ss e rt (IWETH( weth ) . t r a n s f e r ( p a i r , msg.value *e t h L e f t ) ) ; 201 IOneSwapPair ( p a i r ) . addLimitOrder ( isBuy , msg.sender ,uint64 ( stockAmount ) , uint32 ( p r i c e ) , id , uint72 ( prevKey ) ) ; 202 i f( e t h L e f t > 0) { _safeTransferETH ( msg.sender , e t h L e f t ) ; } 203 } Listing 3.9: OneSwapRouter.sol To elaborate the logic, we show above the code snippet of limitOrderWithETH() . The specific ETHwrapping requires that either stockormoneyneeds to be the supported WETH:require(stock == weth || money == weth, "OneSwapRouter: PAIR_MISMATCH") (line 186). Apparently, this is necessary to prevent accidental deposits. 22/47 PeckShield Audit Report #: 2020-38Public However, the condition can be further strengthened by requiring the pairing of isBuy. When stock = WETH, the submitted limited order has to be a SELLorder, i.e., isBuy = false ; When money = WETH , the submitted limited order has to be a BUYorder, i.e., isBuy = true . The tightened sanity checks are very helpful to prevent accidental deposits of ETHs when stock = WETH and isBuy = true . Otherwise, the accidentally deposited assets will likely be sync()’ed into the pool reserve or skim()’ed by others. Recommendation Tighten the above-mentioned sanity checks on limitOrderWithETH() . 183 function limitOrderWithETH ( bool isBuy , address p a i r , uint prevKey , uint p r i c e , uint32 id , 184 uint stockAmount , uint d e a d l i n e ) external payable o v e r r i d e e n s u r e ( d e a d l i n e ) { 185 (address stock , address money ) = _getTokensFromPair ( p a i r ) ; 186 require ( ( s t o c k == weth && ! isBuy ) ( money == weth && isBuy ) , " OneSwapRouter : PAIR_MISMATCH " ) ; 187 uint e t h L e f t ; 188 { 189 (uint _stockAmount , uint _moneyAmount) = IOneSwapPair ( p a i r ) . calcStockAndMoney ( uint64 ( stockAmount ) , uint32 ( p r i c e ) ) ; 190 i f( isBuy ) { 191 require (msg.value >= _moneyAmount , " OneSwapRouter : INSUFFICIENT_INPUT_AMOUNT " ) ; 192 e t h L e f t = msg.value *_moneyAmount ; 193 }e l s e { 194 require (msg.value >= _stockAmount , " OneSwapRouter : INSUFFICIENT_INPUT_AMOUNT " ) ; 195 e t h L e f t = msg.value *_stockAmount ; 196 } 197 } 198 199 IWETH( weth ) . d e p o s i t { value :msg.value *e t h L e f t }() ; 200 a ss e rt (IWETH( weth ) . t r a n s f e r ( p a i r , msg.value *e t h L e f t ) ) ; 201 IOneSwapPair ( p a i r ) . addLimitOrder ( isBuy , msg.sender ,uint64 ( stockAmount ) , uint32 ( p r i c e ) , id , uint72 ( prevKey ) ) ; 202 i f( e t h L e f t > 0) { _safeTransferETH ( msg.sender , e t h L e f t ) ; } 203 } Listing 3.10: OneSwapRouter.sol Status The issue has been confirmed and fixed by providing a native ETHsupport in OneSwap. In other words, it does not need the front-end wrapper of WETHin order to support ETH-related trading pairs. Note that the UniswapV2 implementation still needs the WETHwrapper. 23/47 PeckShield Audit Report #: 2020-38Public 3.7 Non-Payable removeLiquidityETH() •ID: PVE-007 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: OneSwapRouter •Category: Coding Practices [11] •CWE subcategory: CWE-1041 [2] Description Within the OneSwapRouter contract, there is another entry routine, i.e., removeLiquidityETH() . This routine allows the pool’s liquidity providers to remove liquidity from the pool. By transparently unwrapping WETHs into ETH,removeLiquidityETH() greatly facilitates user experience for native ETHs. It is important to note that this routine is only supposed to accept the pool’s liquidity tokens, not others including ETHs. Therefore, the current definition of function removeLiquidityETH(address pair, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline)external override payablemay wrongfully allow to take users’ accidental ETHdeposit. To prevent that from happening, it is suggested to remove the keyword payablefrom the definition. 113 function removeLiquidityETH ( address p a i r , uint l i q u i d i t y , uint amountTokenMin , uint amountETHMin , 114 address to , uint d e a d l i n e ) external o v e r r i d e e n s u r e ( d e a d l i n e ) payable returns ( uint amountToken , uint amountETH) { 115 116 address token ; 117 (address stock , address money ) = _getTokensFromPair ( p a i r ) ; 118 i f( s t o c k == weth ) { 119 token = money ; 120 (amountETH , amountToken ) = _removeLiquidity ( p a i r , l i q u i d i t y , amountETHMin , amountTokenMin , address (t h i s ) ) ; 121 }e l s e i f ( money == weth ) { 122 token = s t o c k ; 123 ( amountToken , amountETH) = _removeLiquidity ( p a i r , l i q u i d i t y , amountTokenMin , amountETHMin , address (t h i s ) ) ; 124 }e l s e { 125 require (false ," OneSwapRouter : PAIR_MISMATCH " ) ; 126 } 127 IWETH( weth ) . withdraw (amountETH) ; 128 _safeTransferETH ( to , amountETH) ; 129 _ s a f e T r a n s f e r ( token , to , amountToken ) ; 130 } Listing 3.11: OneSwapRouter.sol Recommendation Remove the payablekeyword from the removeLiquidityETH() definition. 24/47 PeckShield Audit Report #: 2020-38Public Status The issue has been confirmed and fixed by providing a native ETHsupport in OneSwap. As mentioned in Section 3.6, it does not need the front-end wrapper of WETHforETH-related trading pairs. By contrast, the UniswapV2 deployment still needs the WETHwrapper. 3.8 Cached/Randomized ID For Unused OrderID Lookup •ID: PVE-008 •Severity: Low •Likelihood: Low •Impact: Low•Target: OneSwapPair •Category: Coding Practices [11] •CWE subcategory: CWE-1041 [2] Description OneSwap has a built-in order-matching engine that maintains two singly-linked lists for pending buy and sellorders. Each order has a unique ID assigned. To ensure the order uniqueness, the routine _getUnusedOrderID() is responsible for ensuring the assigned (new) order always bears an unused order ID. (Note the uniqueness only needs to be maintained with buyorders or sellorders, not both.) We notice that when the routine is tasked to find an unused order ID (by a given ID input of 0), it always starts from 1to search for unused ID. Such ID assignment may not be optimal as it always starts from the same number. A better alternative may be to start from the last unused ID or even randomize the ID from the msg.sender ortx.origin . By doing so, it is likely to improve the hit rate of finding an unused ID. 704 // Get an unused id to be used with new order 705 function _getUnusedOrderID ( bool isBuy , uint32 i d ) i n t e r n a l view returns (uint32 ) { 706 i f( i d == 0) { // 0 is reserved 707 i d = 1 ; 708 } 709 for(uint32 i = 0 ; i < 100 && i d <= _MAX_ID; i ++) { // try 100 times 710 i f( ! _hasOrder ( isBuy , i d ) ) { 711 return i d ; 712 } 713 i d ++; 714 } 715 require (false ," OneSwap : CANNOT_FIND_VALID_ID " ) ; 716 return 0 ; 717 } Listing 3.12: OneSwapRouter.sol Recommendation For a new unused ID assignment, start the ID search from the last unused ID or a randomized ID. 25/47 PeckShield Audit Report #: 2020-38Public Status The issue has been fixed by randomizing the starting ID for assignment. It basically implements a pseudo-random number generator: id = uint32(uint(blockhash(block.number-1))^uint (tx.origin))& _MAX_ID . Note that this pseudo-random number generator may not be sufficiently secure, but it suffices for the purpose of order ID assignment. 3.9 Gas-Efficient New Pair Deployment •ID: PVE-009 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: OneSwapFactory •Category: Coding Practices [11] •CWE subcategory: CWE-1041 [2] Description OneSwap acts as a trustless intermediary between liquidity providers and trading users. The liquidity providers depositcertain amount of stockand moneyassets into the OneSwap pool and in return get the tokenized pool share of current reserves. Later on, the liquidity providers can withdraw their own share by returning the pool tokens back to the pool. With assets in the pool, users can submit swap orlimitorders and the trading price is determined according to the current order book and/or AMM price curve. When the pool does not exist, the first liquidity provider’s addLiquidity() operation will trigger the creation of the pool (via the createPair() function). As the name indicates, createPair() per- forms necessary sanity checks and then instantiates the pool contract creation (line 60):OneSwapPair oneswap = new OneSwapPair(weth, stock, money, isOnlySwap, uint64(uint(10)**dec), priceMul, priceDiv ). 60 function c r e a t e P a i r ( address stock , address money , bool isOnlySwap ) external o v e r r i d e returns (address p a i r ) { 61 require ( s t o c k != money , " OneSwapFactory : IDENTICAL_ADDRESSES " ) ; 62 require ( s t o c k != address (0) && money != address (0) , " OneSwapFactory : ZERO_ADDRESS " ) ; 63 uint moneyDec = uint ( IERC20 ( money ) . d e c i m a l s ( ) ) ; 64 uint stockDec = uint ( IERC20 ( s t o c k ) . d e c i m a l s ( ) ) ; 65 require (23 >= stockDec && stockDec >= 0 , " OneSwapFactory : STOCK_DECIMALS_NOT_SUPPORTED " ) ; 66 uint dec = 0 ; 67 i f( stockDec >= 4) { 68 dec = stockDec *4 ;// now 19 >= dec && dec >= 0 69 } 70 // 10**19 = 10000000000000000000 71 // 1 <<64 = 18446744073709551616 72 uint64 priceMul = 1 ; 26/47 PeckShield Audit Report #: 2020-38Public 73 uint64 p r i c e D i v = 1 ; 74 bool d i f f e r e n c e T o o L a r g e = f a l s e ; 75 i f( moneyDec > stockDec ) { 76 i f( moneyDec > stockDec + 19) { 77 d i f f e r e n c e T o o L a r g e = true ; 78 }e l s e { 79 priceMul = uint64 (uint (10) ∗∗( moneyDec *stockDec ) ) ; 80 } 81 } 82 i f( stockDec > moneyDec ) { 83 i f( stockDec > moneyDec + 19) { 84 d i f f e r e n c e T o o L a r g e = true ; 85 }e l s e { 86 p r i c e D i v = uint64 (uint (10) ∗∗( stockDec *moneyDec ) ) ; 87 } 88 } 89 require ( ! d i f f e r e n c e T o o L a r g e , " OneSwapFactory : DECIMALS_DIFF_TOO_LARGE " ) ; 90 bytes32 s a l t = keccak256 ( a b i . encodePacked ( stock , money , isOnlySwap ) ) ; 91 require ( _tokensToPair [ s a l t ] == address (0) , " OneSwapFactory : PAIR_EXISTS " ) ; 92 OneSwapPair oneswap = new OneSwapPair{ s a l t : s a l t }( weth , stock , money , isOnlySwap ,uint64 (uint (10) ∗∗dec ) , priceMul , p r i c e D i v ) ; 93 94 p a i r = address ( oneswap ) ; 95 a l l P a i r s . push ( p a i r ) ; 96 _tokensToPair [ s a l t ] = p a i r ; 97 _pairWithToken [ p a i r ] = TokensInPair ( stock , money ) ; 98 emit P a i r C r e a t e d ( p a i r , stock , money , isOnlySwap ) ; 99 } Listing 3.13: OneSwapFactory.sol The pair contract is a complicated one and its instantiation inevitably consumes significant amount of gas. Such gas-consuming pool contract deployment would discourage liquidity providers’ engagement. An alternative would be to explore a proxy-based approach by implementing the pool contract as a logic one. By doing so, we only need to deploy a minimal proxy for each pair, hence lowering the entry barrier for liquidity providers, especially for the creation of trading pools. Recall that in order to prevent the first liquidity provider from monopolizing the liquidity pool, the provider has been penalized by forcibly burning the very first _MINIMUM_LIQUIDITY = 10 ** 3 pool shares. It is just not justifiable to further penalize early liquidity providers who introduce the trading pools into the OneSwap ecosystem! Recommendation Explore the proxy-based approach of deploying pool contracts to lower the barrier for early participation. Status The issue has been confirmed. The team has seriously taken the suggested approach by implementing a proxy-based architecture in this commit: d76898b603aed60a776fc0ac529b199e1a6c8c9e. The benefit in reduced gas consumption is evident. In the following, we show the comparison of key 27/47 PeckShield Audit Report #: 2020-38Public Table 3.1: Gas Consumption Comparison Between OneSwapAnd UniswapV2 Operation OneSwap UniswapV2 Note createPair() 419;493 2;174;541a90~reduction from >5Mgas to current <500K addLiquidity() 116;409 123;702add new liquidity into the pool removeLiquidity() 97;837 175;966remove liquidity from the pool swap() 121;790 117;503swap one token to another against the pool operations between OneSwapAnd UniswapV2 . 3.10 Burnability of Assets Owned By Blacklisted Addresses •ID: PVE-010 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: OneSwapToken •Category: Business Logics [12] •CWE subcategory: CWE-754 [7] Description OneSwapToken defines the protocol token used in OneSwap. It supports the capability of blacklist- ing certain accounts. Note the OneSwapToken s owned by a blacklisted address are prevented from transferring to another account. 102 function _ t r a n s f e r ( address sender ,address r e c i p i e n t , uint256 amount ) i n t e r n a l v i r t u a l { 103 require (sender !=address (0) , " OneSwapToken : TRANSFER_FROM_THE_ZERO_ADDRESS " ) ; 104 require ( r e c i p i e n t != address (0) , " OneSwapToken : TRANSFER_TO_THE_ZERO_ADDRESS " ) ; 106 _beforeTokenTransfer ( sender , r e c i p i e n t , amount ) ; 108 _balances [ sender ] = _balances [ sender ] . sub ( amount , " OneSwapToken : TRANSFER_AMOUNT_EXCEEDS_BALANCE " ) ; 109 _balances [ r e c i p i e n t ] = _balances [ r e c i p i e n t ] . add ( amount ) ; 110 emit Transfer (sender , r e c i p i e n t , amount ) ; 111 } 113 function _burn ( address account , uint256 amount ) i n t e r n a l v i r t u a l { 114 require ( account != address (0) , " OneSwapToken : BURN_FROM_THE_ZERO_ADDRESS " ) ; 116 _balances [ account ] = _balances [ account ] . sub ( amount , " OneSwapToken : BURN_AMOUNT_EXCEEDS_BALANCE " ) ; 117 _totalSupply = _totalSupply . sub ( amount ) ; 118 emit Transfer ( account , address (0) , amount ) ; 119 } 28/47 PeckShield Audit Report #: 2020-38Public 121 function _approve ( address owner , address spender , uint256 amount ) i n t e r n a l v i r t u a l { 122 require ( owner != address (0) , " OneSwapToken : APPROVE_FROM_THE_ZERO_ADDRESS " ) ; 123 require ( spender != address (0) , " OneSwapToken : APPROVE_TO_THE_ZERO_ADDRESS " ) ; 125 _allowances [ owner ] [ spender ] = amount ; 126 emit Approval ( owner , spender , amount ) ; 127 } 129 function _beforeTokenTransfer ( address from , address to , uint256 )i n t e r n a l v i r t u a l view { 130 require ( ! i s B l a c k L i s t e d ( from ) , " OneSwapToken : FROM_IS_BLACKLISTED_BY_TOKEN_OWNER " ) ; 131 require ( ! i s B l a c k L i s t e d ( to ) , " OneSwapToken : TO_IS_BLACKLISTED_BY_TOKEN_OWNER " ) ; 132 } Listing 3.14: OneSwapToken.sol The blocking logic is implemented by invoking a call to _beforeTokenTransfer() that in essence answers whether any of the involved parties is blacklisted. If yes, the transfer is simply reverted. Meanwhile, we notice that a blacklisted account can still burn the owned assets. Ethically, we believe it is more appropriate to freeze the blacklisted account, including the burn()attempt by the blacklisted account. Recommendation Add the support of preventing a blacklisted account from burning owned tokens. And also block a blacklisted account from spending if there is still pending allowance. 113 function _burn ( address account , uint256 amount ) i n t e r n a l v i r t u a l { 114 require ( account != address (0) , " OneSwapToken : BURN_FROM_THE_ZERO_ADDRESS " ) ; 115 require ( ! i s B l a c k L i s t e d ( account ) , " OneSwapToken : BURN_FROM_THE_BLACKLISTED_ADDRESS " ) ; 117 _balances [ account ] = _balances [ account ] . sub ( amount , " OneSwapToken : BURN_AMOUNT_EXCEEDS_BALANCE " ) ; 118 _totalSupply = _totalSupply . sub ( amount ) ; 119 emit Transfer ( account , address (0) , amount ) ; 120 } Listing 3.15: OneSwapToken.sol Status The issue has been fixed by this commit: 49b5c8d0392e828b735445980e364d5ddc1c8542. 29/47 PeckShield Audit Report #: 2020-38Public 3.11 Accommodation of approve() Idiosyncrasies •ID: PVE-011 •Severity: Low •Likelihood: medium •Impact: Low•Target: OneSwapBuyback •Category: Business Logics [12] •CWE subcategory: N/A Description ThoughthereisastandardizedERC-20specification, manytokencontractsmaynotstrictlyfollowthe specification or have additional functionalities beyond the specification. In this section, we examine the approve() routine and 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.16: USDT Token Contract Because of that, a normal call to approve() with a currently non-zero allowance may fail. An example is shown below. It is in the OneSwapBuyback contract that is designed to swap certain tokens to the protocol token. To accommodate the specific idiosyncrasy, there is a need to approve() twice: the first one reduces the allowance to 0; and the second one sets the new allowance. 30/47 PeckShield Audit Report #: 2020-38Public 137 function _swapForOnesAndBurn ( address p a i r ) private { 138 (address a ,address b ) = IOneSwapFactory ( f a c t o r y ) . getTokensFromPair ( p a i r ) ; 139 require ( a != address (0) && b != address (0) , " OneSwapBuyback : INVALID_PAIR " ) ; 140 require ( a == ones b == ones , " OneSwapBuyback : ONES_NOT_IN_PAIR " ) ; 142 address token = ( a == ones ) ? b : a ; 143 require ( _mainTokens [ token ] , " OneSwapBuyback : MAIN_TOKEN_NOT_IN_PAIR " ) ; 144 uint256 tokenAmt = IERC20 ( token ) . balanceOf ( address (t h i s ) ) ; 145 require ( tokenAmt > 0 , " OneSwapBuyback : NO_MAIN_TOKENS " ) ; 147 address [ ]memory path = new address [ ] ( 1 ) ; 148 path [ 0 ] = p a i r ; 150 // token -> ones 151 IERC20 ( token ) . approve ( r o u t e r , tokenAmt ) ; 152 IOneSwapRouter ( r o u t e r ) . swapToken ( 153 token , tokenAmt , 0 , path , address (t h i s ) , _MAX_UINT256) ; 154 } Listing 3.17: OneSwapBuyback.sol Recommendation Accommodate the above-mentioned idiosyncrasy of approve() . Status The issue has been fixed by this commit: 49b5c8d0392e828b735445980e364d5ddc1c8542. 3.12 Improved Handling of Corner Cases in SupervisedSend •ID: PVE-012 •Severity: Low •Likelihood: Low •Impact: Low•Target: SupervisedSend •Category: Business Logics [12] •CWE subcategory: N/A Description OneSwap provides a number of unique features and SupervisedSend is one of them. SupervisedSend allows for effective lock-up of assets and the locked assets can be released after the lock-up expires. The SupervisedSend contract has exposed a number of functions, including supervisedSend() and supervisedUnlockSend() . The first function properly locks up the assets with a specified expiry time and the second one allows for unlocking the assets after the lockup is expired. The lockup time is facilitated with two modifiers, i.e., beforeUnlockTime and afterUnlockTime . We show these two modifiers below. 20 modifier afterUnlockTime ( uint32 unlockTime ) { 21 require (uint ( unlockTime ) ∗3600 < block .timestamp ," SupervisedSend : NOT_ARRIVING_UNLOCKTIME_YET " ) ; 31/47 PeckShield Audit Report #: 2020-38Public 22 _; 23 } 24 25 modifier beforeUnlockTime ( uint32 unlockTime ) { 26 require (uint ( unlockTime ) ∗3600 > block .timestamp ," SupervisedSend : ALREADY_UNLOCKED " ) ; 27 _; 28 } Listing 3.18: SupervisedSend.sol Apparently, the beforeUnlockTime modifier ensures the assets are currently locked ( require(uint( unlockTime)* 3600 < block.timestamp – line 21) and the afterUnlockTime modifier guarantees that the lockup period is over ( require(uint(unlockTime)* 3600 > block.timestamp – line 26). It is interesting to note an un-handled corner case when uint(unlockTime)* 3600 == block.timestamp . Another corner issue is also identified in the _tryDealInPool() routine of the OneSwapPair contract (line 1018). Recommendation Address the missed corner cases without any omission. Status The issue has been fixed by including the =case in the afterUnlockTime modifier. The corner casein _tryDealInPool() was fixedby thiscommit: 4194ac1a55934cd573bd93987111eaa8f70676fe. 20 modifier afterUnlockTime ( uint32 unlockTime ) { 21 require (uint ( unlockTime ) ∗3600 <= block .timestamp ," SupervisedSend : NOT_ARRIVING_UNLOCKTIME_YET " ) ; 22 _; 23 } 24 25 modifier beforeUnlockTime ( uint32 unlockTime ) { 26 require (uint ( unlockTime ) ∗3600 > block .timestamp ," SupervisedSend : ALREADY_UNLOCKED " ) ; 27 _; 28 } Listing 3.19: SupervisedSend.sol ( revised ) 32/47 PeckShield Audit Report #: 2020-38Public 3.13 Consistent Adherence of Checks-Effects-Interactions •ID: PVE-013 •Severity: Low •Likelihood: Low •Impact: Low•Target: SupervisedSend •Category: Time and State [13] •CWE subcategory: CWE-663 [6] 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 invoking functions that should only be executed once. This attack was part of several most prominent hacks in Ethereum history, including the DAO[23] exploit, and the recent Uniswap/Lendf.Me hack [21]. We notice there are several occasions the checks-effects-interactions principle is violated. Using the SupervisedSend as an example, the supervisedSend() function (see the code snippet below) is provided to externally call a token contract to transfer assets for lock-up. However, the invocation of an external contract requires extra care in avoiding the above re-entrancy . Apparently, the interaction with the external contract (line 36) starts before effecting the update on the internal state (line 37), hence violating the principle. In this particular case, if the external contract has some hidden logic that may be capable of launching re-entrancy via the very same supervisedSend() function. Meanwhile, we should emphasize that the onestokens implement rather standard ERC20 interfaces and its token contract is not vulnerable or exploitable for re-entrancy . 30 function s u p e r v i s e d S e n d ( address to , address s u p e r v i s o r , uint112 reward , uint112 amount , address token , uint32 unlockTime , uint256 s e r i a l N u m b e r ) public o v e r r i d e { 31 bytes32 key = _getSupervisedSendKey ( msg.sender , to , s u p e r v i s o r , token , unlockTime ) ; 32 s u p e r v i s e d S e n d I n f o memory i n f o = s u p e r v i s e d S e n d I n f o s [ key ] [ s e r i a l N u m b e r ] ; 33 require ( amount > reward , " SupervisedSend : TOO_MUCH_REWARDS " ) ; 34 // prevent duplicated send 35 require ( i n f o . amount == 0 && i n f o . reward == 0 , " SupervisedSend : INFO_ALREADY_EXISTS " ) ; 36 _safeTransferToMe ( token , msg.sender ,uint ( amount ) . add ( uint ( reward ) ) ) ; 37 s u p e r v i s e d S e n d I n f o s [ key ] [ s e r i a l N u m b e r ]= s u p e r v i s e d S e n d I n f o ( amount , reward ) ; 38 emit SupervisedSend ( msg.sender , to , s u p e r v i s o r , token , amount , reward , unlockTime ) ; 39 } Listing 3.20: SupervisedSend.sol 33/47 PeckShield Audit Report #: 2020-38Public Recommendation Apply necessary reentrancy prevention by following the checks-effects- interactions best practice. 30 function s u p e r v i s e d S e n d ( address to , address s u p e r v i s o r , uint112 reward , uint112 amount , address token , uint32 unlockTime , uint256 s e r i a l N u m b e r ) public o v e r r i d e { 31 bytes32 key = _getSupervisedSendKey ( msg.sender , to , s u p e r v i s o r , token , unlockTime ) ; 32 s u p e r v i s e d S e n d I n f o memory i n f o = s u p e r v i s e d S e n d I n f o s [ key ] [ s e r i a l N u m b e r ] ; 33 require ( amount > reward , " SupervisedSend : TOO_MUCH_REWARDS " ) ; 34 // prevent duplicated send 35 require ( i n f o . amount == 0 && i n f o . reward == 0 , " SupervisedSend : INFO_ALREADY_EXISTS " ) ; 36 s u p e r v i s e d S e n d I n f o s [ key ] [ s e r i a l N u m b e r ]= s u p e r v i s e d S e n d I n f o ( amount , reward ) ; 37 _safeTransferToMe ( token , msg.sender ,uint ( amount ) . add ( uint ( reward ) ) ) ; 38 emit SupervisedSend ( msg.sender , to , s u p e r v i s o r , token , amount , reward , unlockTime ) ; 39 } Listing 3.21: SupervisedSend.sol ( revised ) Status This issue has been fixed by following the checks-effects-interactions best practice. 3.14 Improved Precision Calculation in Trading Fee Calculation •ID: PVE-014 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: OneSwapPair •Category: Coding Practices [11] •CWE subcategory: CWE-627 [5] Description SafeMath is a 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 default division behavior, i.e., the floordivision. Conceptually, the floordivisionisanormaldivisionoperationexceptitreturnsthelargestpossible integer that is either less than or equal to the normal division result. In SafeMath,floor(x) or simply divtakes as input an integer number xand gives as output the greatest integer less than or equal to x, denoted floor(x) =âxã. Its counterpart is the ceilingdivision that maps xto the least integer greater than or equal to x, denoted as ceil(x)=äxå. In essence, the ceilingdivision is rounding up the result of the division, instead of rounding down in the floordivision. 34/47 PeckShield Audit Report #: 2020-38Public During the analysis of an internal function, i.e, _dealWithPoolAndCollectFee() , that makes a deal with the pool and then collects necessary fee, we notice the fee calculation results in (small) precision loss. For elaboration, we show the related code snippet below. 1066 // make real deal with the pool and then collect fee , which will be added to AMM pool 1067 function _dealWithPoolAndCollectFee ( Context memory ctx , bool isBuy ) i n t e r n a l returns (uint ) { 1068 (uint outpoolTokenReserve , uint inpoolTokenReserve , uint otherToTaker ) = ( 1069 c tx . reserveMoney , c t x . r e s e r v e S t o c k , ct x . dealMoneyInBook ) ; 1070 i f( isBuy ) { 1071 ( outpoolTokenReserve , inpoolTokenReserve , otherToTaker ) = ( 1072 c tx . r e s e r v e S t o c k , c t x . reserveMoney , ct x . dealStockInBook ) ; 1073 } 1075 // all these 4 varialbes are less than 112 bits 1076 // outAmount is sure to less than outpoolTokenReserve ( which is ctx . reserveStock or ctx . reserveMoney ) 1077 uint outAmount = ( outpoolTokenReserve ∗c tx . amountIntoPool ) /( inpoolTokenReserve+ c tx . amountIntoPool ) ; 1078 i f( c tx . amountIntoPool > 0) { 1079 _emitDealWithPool ( uint112 ( c tx . amountIntoPool ) , uint112 ( outAmount ) , isBuy ) ; 1080 } 1081 uint32 feeBPS = IOneSwapFactory ( c t x . f a c t o r y ) . feeBPS ( ) ; 1082 // the token amount that should go to the taker , 1083 // for buy -order , it ’s stock amount ; for sell -order , it ’s money amount 1084 uint amountToTaker = outAmount + otherToTaker ; 1085 require ( amountToTaker < uint (1<<112) , " OneSwap : AMOUNT_TOO_LARGE " ) ; 1086 uint f e e = amountToTaker ∗feeBPS / 10000; 1087 amountToTaker *= f e e ; 1089 i f( isBuy ) { 1090 c tx . reserveMoney = c t x . reserveMoney + c tx . amountIntoPool ; 1091 c tx . r e s e r v e S t o c k = ct x . r e s e r v e S t o c k *outAmount + f e e ; 1092 }e l s e { 1093 c tx . reserveMoney = c t x . reserveMoney *outAmount + f e e ; 1094 c tx . r e s e r v e S t o c k = ct x . r e s e r v e S t o c k + c t x . amountIntoPool ; 1095 } 1097 address token = c tx . moneyToken ; 1098 i f( isBuy ) { 1099 token = c tx . stockToken ; 1100 } 1101 _ s a f e T r a n s f e r ( token , c t x . o r d e r . sender , amountToTaker , ct x . ones ) ; 1102 return amountToTaker ; 1103 } Listing 3.22: OneSwapPair() The fee calculation is performed via fee = amountToTaker * feeBPS / 10000 (line 1086). Appar- ently, it is a standard floor()operation that rounds down the calculation result. Note that in an AMM-based DEX scenario where a user trades in one token for another, if there is a rounding issue, 35/47 PeckShield Audit Report #: 2020-38Public it is always preferable to calculate the trading amount in a way towards the liquidity pool to protect the liquidity providers’ interest. Therefore, depending on specific cases, the calculation may often needs to replace the normal floordivision with ceilingdivision. In other words, the fee calculation is better revised as fee = (amountToTaker * feeBPS + 9999)/ 10000 , aceilingdivision. Recommendation Revise the logic accordingly to round-up the fee calculation. Status The issue has been confirmed and fixed by taking the suggested round-up approach for the fee calculation. 3.15 Less Friction For Improved Buybacks and Order Matching •ID: PVE-015 •Severity: Low •Likelihood: Low •Impact: Low•Target: OneSwapBuyback, OneSwapPair •Category: Coding Practices [11] •CWE subcategory: N/A Description OneSwap has a number of components that not only depend on each other, but also interact with external DeFi protocols. Because of that, it is often necessary to introduce as little friction as possible to avoid sudden disruption of an ongoing transaction. Note that the disruption can be caused by imposed requirements on the related execution paths. Certainly, essential requirements need to be satisfied while others need to gauge specific application situations or logics to avoid unnecessary or sudden revert. In the following, we show a specific case in the OneSwapBuyback contract. The specific function is_removeLiquidity() . As the name indicates, it allows previously provided liquidity to be removed from the pool. For convenience, it further supports batch-processing: given a list of pairs (and their associated liquidity pools), it iterates each one and removes the provided liquidity. However, it also requires require(amt > 0, "OneSwapBuyback: NO_LIQUIDITY") (line 81). This requirement will unnecessarily revert the ongoing transaction even if we can simply skip it during the batch processing. 69 // remove Buyback ’s liquidity from all pairs 70 // swap got minor tokens for main tokens if possible 71 function r e m o v e L i q u i d i t y ( address [ ] c a l l d a t a p a i r s ) external o v e r r i d e { 72 for (uint256 i = 0 ; i < p a i r s . length ; i ++) { 73 _removeLiquidity ( p a i r s [ i ] ) ; 74 } 75 } 76 function _removeLiquidity ( address p a i r ) private { 77 (address a ,address b ) = IOneSwapFactory ( f a c t o r y ) . getTokensFromPair ( p a i r ) ; 36/47 PeckShield Audit Report #: 2020-38Public 78 require ( a != address (0) b != address (0) , " OneSwapBuyback : INVALID_PAIR " ) ; 80 uint256 amt = IERC20 ( p a i r ) . balanceOf ( address (t h i s ) ) ; 81 require ( amt > 0 , " OneSwapBuyback : NO_LIQUIDITY " ) ; 83 IERC20 ( p a i r ) . approve ( r o u t e r , 0) ; 84 IERC20 ( p a i r ) . approve ( r o u t e r , amt ) ; 85 IOneSwapRouter ( r o u t e r ) . r e m o v e L i q u i d i t y ( 86 p a i r , amt , 0 , 0 , address (t h i s ) , _MAX_UINT256) ; 88 // minor -> main 89 bool aIsMain = _mainTokens [ a ] ; 90 bool bIsMain = _mainTokens [ b ] ; 91 i f( ( aIsMain && ! bIsMain ) ( ! aIsMain && bIsMain ) ) { 92 _swapForMainToken ( p a i r ) ; 93 } 94 } Listing 3.23: OneSwapBuyback.sol Anothersimilarissuecanalsobefoundinthe _intopoolAmountTillPrice() routineinthe OneSwapPair contract. Recommendation Introduce as little friction as possible by revising the _removeLiquidity() routine accordingly. 69 // remove Buyback ’s liquidity from all pairs 70 // swap got minor tokens for main tokens if possible 71 function r e m o v e L i q u i d i t y ( address [ ] c a l l d a t a p a i r s ) external o v e r r i d e { 72 for (uint256 i = 0 ; i < p a i r s . length ; i ++) { 73 _removeLiquidity ( p a i r s [ i ] ) ; 74 } 75 } 76 function _removeLiquidity ( address p a i r ) private { 77 (address a ,address b ) = IOneSwapFactory ( f a c t o r y ) . getTokensFromPair ( p a i r ) ; 78 require ( a != address (0) b != address (0) , " OneSwapBuyback : INVALID_PAIR " ) ; 80 uint256 amt = IERC20 ( p a i r ) . balanceOf ( address (t h i s ) ) ; 81 i f( amt == 0) { return } ; 83 IERC20 ( p a i r ) . approve ( r o u t e r , 0) ; 84 IERC20 ( p a i r ) . approve ( r o u t e r , amt ) ; 85 IOneSwapRouter ( r o u t e r ) . r e m o v e L i q u i d i t y ( 86 p a i r , amt , 0 , 0 , address (t h i s ) , _MAX_UINT256) ; 88 // minor -> main 89 bool aIsMain = _mainTokens [ a ] ; 90 bool bIsMain = _mainTokens [ b ] ; 91 i f( ( aIsMain && ! bIsMain ) ( ! aIsMain && bIsMain ) ) { 92 _swapForMainToken ( p a i r ) ; 93 } 37/47 PeckShield Audit Report #: 2020-38Public 94 } Listing 3.24: OneSwapBuyback.sol Status The issue has been fixed by replacing non-essential require() with corresponding if conditions. 3.16 Other Suggestions OneSwap merges the DEX support of traditional order book and automated market making. While it greatly pushes forward the DEX frontline, it also naturally inherits from well-known front-running or back-running issues plagued with current DEXs. For example, a large trade may be sandwiched by preceding addition into liquidity pool (via mint()) and tailgating removal of the same amount of liquidity (via burn()). Such sandwiching unfortunately causes a loss to other liquidity providers. Also, a large burn of the protocol token (via the built-in buybackmechanism) could be similarly sandwiched by preceding buys for increased token values. Similarly, a market order could be intentionally traded for a higher price if a malicious actor intentionally increases it by trading an earlier competing order. However, we need to acknowledge that these are largely inherent to current blockchain infrastructure and there is still a need to continue the search efforts for an effective defense. Next, becausetheSoliditylanguageisstillmaturinganditiscommonfornewcompilerversionsto include changes that might bring unexpected compatibility or inter-version consistencies, 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.6.6; instead of pragma solidity >=0.6.6 or ^0.6.6; . Moreover, we strongly suggest not to use experimental Solidity features or third-party unaudited libraries. If necessary, refactor current code base to only use stable features or trusted libraries. 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. 38/47 PeckShield Audit Report #: 2020-38Public 4 | Conclusion In this audit, we thoroughly analyzed the OneSwap design and implementation. The system presents a unique offering in current DEX ecosystem with the support of both traditional order book and AMMs. We are truly impressed by the design and implementation, especially the dedication to maximized gas optimization. The current code base is well 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. 39/47 PeckShield Audit Report #: 2020-38Public 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 [16, 17, 18, 19, 22]. •Result: Not found •Severity: Critical 40/47 PeckShield Audit Report #: 2020-38Public 5.1.5 Reentrancy •Description: Reentrancy [24] 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 41/47 PeckShield Audit Report #: 2020-38Public 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 42/47 PeckShield Audit Report #: 2020-38Public 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 43/47 PeckShield Audit Report #: 2020-38Public 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 44/47 PeckShield Audit Report #: 2020-38Public References [1] axic. Enforcing ABI length checks for return data from calls can be breaking. https://github. com/ethereum/solidity/issues/4116. [2] MITRE. CWE-1041: Use of Redundant Code. https://cwe.mitre.org/data/definitions/1041. 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-627: Dynamic Variable Evaluation. https://cwe.mitre.org/data/definitions/627. html. [6] MITRE. CWE-663: Use of a Non-reentrant Function in a Concurrent Context. https://cwe. mitre.org/data/definitions/663.html. [7] MITRE. CWE-754: Improper Check for Unusual or Exceptional Conditions. https://cwe.mitre. org/data/definitions/754.html. [8] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [9] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. 45/47 PeckShield Audit Report #: 2020-38Public [10] MITRE. CWE CATEGORY: 7PK - Time and State. https://cwe.mitre.org/data/definitions/ 361.html. [11] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [12] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [13] MITRE. CWE CATEGORY: Concurrency. https://cwe.mitre.org/data/definitions/557.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. ALERT: New batchOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018- 10299). https://www.peckshield.com/2018/04/22/batchOverflow/. [17] PeckShield. New burnOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 11239). https://www.peckshield.com/2018/05/18/burnOverflow/. [18] PeckShield. New multiOverflow Bug Identified in Multiple ERC20 Smart Contracts (CVE-2018- 10706). https://www.peckshield.com/2018/05/10/multiOverflow/. [19] PeckShield. New proxyOverflow Bug in Multiple ERC20 Smart Contracts (CVE-2018-10376). https://www.peckshield.com/2018/04/25/proxyOverflow/. [20] PeckShield. PeckShield Inc. https://www.peckshield.com. [21] PeckShield. Uniswap/Lendf.Me Hacks: Root Cause and Loss Analysis. https://medium.com/ @peckshield/uniswap-lendf-me-hacks-root-cause-and-loss-analysis-50f3263dcc09. [22] PeckShield. Your Tokens Are Mine: A Suspicious Scam Token in A Top Exchange. https: //www.peckshield.com/2018/04/28/transferFlaw/. 46/47 PeckShield Audit Report #: 2020-38Public [23] David Siegel. Understanding The DAO Attack. https://www.coindesk.com/ understanding-dao-hack-journalists. [24] Solidity. Warnings of Expressions and Control Structures. http://solidity.readthedocs.io/en/ develop/control-structures.html. 47/47 PeckShield Audit Report #: 2020-38
Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Better Handling of Ownership Transfers (Lines 590-611) - Front-Running of Proposal Tallies (Lines 612-619) - Overlapped Time Windows Between Vote and Tally (Lines 620-624) - Removal of Initial Nop Iterations in removeMainToken() (Lines 625-631) - Incompatibility with Deflationary Tokens (Lines 632-637) - Tightened Sanity Checks in limitOrderWithETH() (Lines 638-644) - Non-Payable removeLiquidityETH() (Lines 645-650) - Cached/Randomized ID For Unused OrderID Lookup (Lines 651-655) 2.b Fix (one line with code reference) - Better Handling of Ownership Transfers (Lines 590-611): Add a check to ensure that the transfer is only Issues Count of Minor/Moderate/Major/Critical: - Minor: 8 - Moderate: 4 - Major: 0 - Critical: 0 Minor Issues: - Constructor Mismatch: The constructor of the OneSwap contract does not match the design document (Line 590). - Fix: The constructor should be updated to match the design document (Line 590). - Ownership Takeover: The ownership of the OneSwap contract can be taken over by an attacker (Line 591). - Fix: The ownership of the OneSwap contract should be protected from attackers (Line 591). - Redundant Fallback Function: The fallback function of the OneSwap contract is redundant (Line 592). - Fix: The fallback function should be removed (Line 592). - Overflows & Underflows: The OneSwap contract is vulnerable to overflows and underflows (Line 593). - Fix: The OneSwap contract should be protected from overflows and underflows (Line 593). - Reentrancy: The OneSwap contract is vulnerable to reentrancy attacks (Line 594). - Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked return values in the function transferFrom (line 890) 2.b Fix (one line with code reference) - Check return values in the function transferFrom (line 890) Moderate: 0 Major: 0 Critical: 0 Observations - No major or critical issues were found in the OneSwap smart contract. - All minor issues were fixed. Conclusion - The OneSwap smart contract is secure and ready for deployment.
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./TokenVesting.sol"; contract VestingController is Ownable { using SafeERC20 for IERC20; uint256 constant countMintDay = 2; // count day afer create contract when can mint locked token event Vesting(address VestingContract, address Beneficiary); modifier vestTime() { require(_timestampCreated + (1 days) * countMintDay >= block.timestamp, "mint time was finished"); _; } IERC20 blid; /** * @return The start timestamp day when create contract */ function timestampCreated() public view returns (uint256) { return _timestampCreated; } uint256 _timestampCreated; /** * @notice Constuctor save time create and owner this contract */ constructor() { _timestampCreated = block.timestamp; transferOwnership(msg.sender); } /** * @notice Set token for vesting */ function addBLID(address token) external vestTime onlyOwner { blid = IERC20(token); } /** * @notice Deploy TokenVesting with this parameters, and transfer amount blid to TokenVesting */ function vest( address account, uint256 amount, uint256 startTimestamp, uint256 duration, uint256 durationCount ) external vestTime onlyOwner { require(blid.balanceOf(address(this)) > amount, "VestingController: vest amount exceeds balance"); TokenVesting vesting = new TokenVesting( address(blid), account, startTimestamp, duration, durationCount ); blid.safeTransfer(address(vesting), amount); emit Vesting(address(vesting), account); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract TokenVesting { using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); IERC20 public _token; address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _durationCount; uint256 private _startTimestamp; uint256 private _duration; uint256 private _endTimestamp; uint256 private _released; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary. By then all * of the balance will have vested. * @param tokenValue Address of vesting token * @param beneficiaryValue Address of beneficiary * @param startTimestampValue Timstamp when start vesting * @param durationValue Duration one period of vesit * @param durationCountValue Count duration one period of vesit */ constructor( address tokenValue, address beneficiaryValue, uint256 startTimestampValue, uint256 durationValue, uint256 durationCountValue ) { require(beneficiaryValue != address(0), "TokenVesting: beneficiary is the zero address"); _token = IERC20(tokenValue); _beneficiary = beneficiaryValue; _duration = durationValue; _durationCount = durationCountValue; _startTimestamp = startTimestampValue; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the end time of the token vesting. */ function end() public view returns (uint256) { return _startTimestamp + _duration * _durationCount; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _startTimestamp; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return the amount of the token released. */ function released() public view returns (uint256) { return _released; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { uint256 unreleased = releasableAmount(); require(unreleased > 0, "TokenVesting: no tokens are due"); _released = _released + (unreleased); _token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(_token), unreleased); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns (uint256) { return _vestedAmount() - (_released); } /** * @dev Calculates the amount that has already vested. */ function _vestedAmount() private view returns (uint256) { uint256 currentBalance = _token.balanceOf(address(this)); uint256 totalBalance = currentBalance + (_released); if (block.timestamp < _startTimestamp) { return 0; } else if (block.timestamp >= _startTimestamp + _duration * _durationCount) { return totalBalance; } else { return (totalBalance * ((block.timestamp - _startTimestamp) / (_duration))) / _durationCount; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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); } contract Bolide is Context, IBEP20, Ownable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint256 timestampCreated; uint256 private immutable _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor(uint256 cap_) { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; _name = "Bolide"; _symbol = "BLID"; timestampCreated = block.timestamp; } function mint(address account, uint256 amount) external onlyOwner { require(timestampCreated + 1 days > block.timestamp, "Mint time was finished"); _mint(account, amount); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 pure override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256 balance) { return _balances[account]; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view 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 override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _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 { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } /** * @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 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 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 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(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 { require(_totalSupply + amount <= _cap, "ERC20Capped: cap exceeded"); require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(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 { require(account != address(0), "ERC20: burn from the zero address"); 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); } /** * @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 { 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); } }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 11 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the security assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: strategies/low_risk/contracts/libs/Aggregator.sol strategies/low_risk /contracts/libs/ERC20ForTestStorage.sol strategies/low_risk/contracts/libs/Migrations.sol strategies/low_risk/contracts/Logic.sol strategies/low_risk/contracts/Storage.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided functional requirements and technical requirements. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 7 out of 10. Code duplications. Not following solidity code style guidelines. Gas over -usage. Architecture quality The architecture quality score is 8 out of 10. Logic is split into modules. Contracts are self -descriptive. No thinking about gas efficiency. Room for improvements in code structuring. Security score As a result of the audit, security engineers found no issues . The security score is 10 out of 10. All found issues are displayed in the “Issues overview” section. Summary According to the assessment, the Cus tomer's smart contract has the following score: 9.5 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High No high severity issues were found. Medium 1. Test failed One of the two tests is failing. That could be either an issue in the test or an error in the contract logic implementation. Scope: strategies Recommendation : Ensure that the tests are successful and cover all the code branches. Status: 6 of 73 tests are failing (Revised Commit: 9378f79) Low 1. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 2. Excessive state access It is not recommended to read the state at each code line. It would be much more gas effective to read the state value into the local memory variable and use it for reading. Contract : StorageV0.sol Recommendation : Read the state variable to a local memory instead of multiple reading . Status: Fixed (Revised Commit: 9ca0cf0) 3. Not emitting events StorageV0 and Logic are not emitting events on state changes. There should be events to allow the community to track the current state off-chain. Contract: StorageV0.sol, Logic.sol Functions: setBLID, addToken, setLogic, setStorage, setAdmin www.hacken.io Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9ca0cf0) 4. Implicit variables visibility State variables that do not have specified visibility are declared internal implicitly. That could not be obvious. Contract: StorageV0.sol Variables : earnBLID, countEarns, countTokens, tokens, tokenBalance, oracles, tokensAdd, deposits, tokenDeposited, to kenTime, reserveBLID, logicContract, BLID Recommendation : Always declare visibility explicitly. Status: Fixed (Revised Commit: 9378f79) 5. Reading state variable’s `length` in the loop Reading `length` attribute in the loop may cost excess gas fees. Contract: Logic.sol Function : returnToken Recommendation : Save `length` attribute value into a local memory variable. Status: Fixed (Revised Commit: 9378f79) 6. Reading state variable in the loop Reading `countTokens` state variable in the loop would cost excess gas fees. Contract: StorageV0.sol Function : addEarn, _upBalance, _upBalanceByItarate, balanceEarnBLID, balanceOf, getTotalDeposit Recommendation : Save `countTokens` value into a local memor y variable. Status: Fixed (Revised Commit: 9ca0cf0) 7. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: Logic.sol, StorageV0.sol Functions : Logic.getReservesCount, Logic.getReserve, StorageV0.initialize, StorageV0._upBalance, StorageV0._upBalanceByItarate, StorageV0.balanceOf, StorageV0.getBLIDReserve, StorageV0.getTotalDeposit, StorageV0.getTokenBalance, StorageV0.getTokenDeposit, StorageV0._isUsedToken, StorageV0. getCountEarns www.hacken.io Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9ca0cf0) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no statements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements. While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hac ks. Thus, the audit can not guarantee the explicit security of the audited smart contracts.
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external call (strategies/low_risk/contracts/Logic.sol:L51) - Unchecked math (strategies/low_risk/contracts/Logic.sol:L51) - Unsafe type inference (strategies/low_risk/contracts/Logic.sol:L51) - Implicit visibility level (strategies/low_risk/contracts/Logic.sol:L51) 2.b Fix (one line with code reference) - Check external call (strategies/low_risk/contracts/Logic.sol:L51) - Check math (strategies/low_risk/contracts/Logic.sol:L51) - Use safe type inference (strategies/low_risk/contracts/Logic.sol:L51) - Use explicit visibility level (strategies/low_risk/contract Issues Count of Minor/Moderate/Major/Critical - Critical: 0 - High: 0 - Moderate: 1 - Minor: 3 Minor Issues 2.a Test failed (Scope: strategies, Revised Commit: 9378f79) 2.b Ensure that the tests are successful and cover all the code branches. Moderate 3.a Floating solidity version (Contracts: all, Revised Commit: 9378f79) 3.b Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Major 4.a Excessive state access (Contract: StorageV0.sol, Revised Commit: 9ca0cf0) 4.b Read the state variable to a local memory instead of multiple reading. Critical No critical severity issues were found. Observations - Logic is split into modules. - Contracts are self-descriptive. - No thinking about gas efficiency. - Room for improvements in code structuring. Conclusion According to the assessment, the Customer's smart contract has the following score: 9.5. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./TokenVesting.sol"; contract VestingController is Ownable { using SafeERC20 for IERC20; uint256 constant countMintDay = 2; // count day afer create contract when can mint locked token event Vesting(address VestingContract, address Beneficiary); modifier vestTime() { require(_timestampCreated + (1 days) * countMintDay >= block.timestamp, "mint time was finished"); _; } IERC20 blid; /** * @return The start timestamp day when create contract */ function timestampCreated() public view returns (uint256) { return _timestampCreated; } uint256 _timestampCreated; /** * @notice Constuctor save time create and owner this contract */ constructor() { _timestampCreated = block.timestamp; transferOwnership(msg.sender); } /** * @notice Set token for vesting */ function addBLID(address token) external vestTime onlyOwner { blid = IERC20(token); } /** * @notice Deploy TokenVesting with this parameters, and transfer amount blid to TokenVesting */ function vest( address account, uint256 amount, uint256 startTimestamp, uint256 duration, uint256 durationCount ) external vestTime onlyOwner { require(blid.balanceOf(address(this)) > amount, "VestingController: vest amount exceeds balance"); TokenVesting vesting = new TokenVesting( address(blid), account, startTimestamp, duration, durationCount ); blid.safeTransfer(address(vesting), amount); emit Vesting(address(vesting), account); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract TokenVesting { using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); IERC20 public _token; address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _durationCount; uint256 private _startTimestamp; uint256 private _duration; uint256 private _endTimestamp; uint256 private _released; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary. By then all * of the balance will have vested. * @param tokenValue Address of vesting token * @param beneficiaryValue Address of beneficiary * @param startTimestampValue Timstamp when start vesting * @param durationValue Duration one period of vesit * @param durationCountValue Count duration one period of vesit */ constructor( address tokenValue, address beneficiaryValue, uint256 startTimestampValue, uint256 durationValue, uint256 durationCountValue ) { require(beneficiaryValue != address(0), "TokenVesting: beneficiary is the zero address"); _token = IERC20(tokenValue); _beneficiary = beneficiaryValue; _duration = durationValue; _durationCount = durationCountValue; _startTimestamp = startTimestampValue; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the end time of the token vesting. */ function end() public view returns (uint256) { return _startTimestamp + _duration * _durationCount; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _startTimestamp; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return the amount of the token released. */ function released() public view returns (uint256) { return _released; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { uint256 unreleased = releasableAmount(); require(unreleased > 0, "TokenVesting: no tokens are due"); _released = _released + (unreleased); _token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(_token), unreleased); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns (uint256) { return _vestedAmount() - (_released); } /** * @dev Calculates the amount that has already vested. */ function _vestedAmount() private view returns (uint256) { uint256 currentBalance = _token.balanceOf(address(this)); uint256 totalBalance = currentBalance + (_released); if (block.timestamp < _startTimestamp) { return 0; } else if (block.timestamp >= _startTimestamp + _duration * _durationCount) { return totalBalance; } else { return (totalBalance * ((block.timestamp - _startTimestamp) / (_duration))) / _durationCount; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @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); } contract Bolide is Context, IBEP20, Ownable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint256 timestampCreated; uint256 private immutable _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor(uint256 cap_) { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; _name = "Bolide"; _symbol = "BLID"; timestampCreated = block.timestamp; } function mint(address account, uint256 amount) external onlyOwner { require(timestampCreated + 1 days > block.timestamp, "Mint time was finished"); _mint(account, amount); } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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 pure override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256 balance) { return _balances[account]; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view 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 override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _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 { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } /** * @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 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 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 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(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 { require(_totalSupply + amount <= _cap, "ERC20Capped: cap exceeded"); require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(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 { require(account != address(0), "ERC20: burn from the zero address"); 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); } /** * @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 { 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); } }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 10 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the securit y assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: farming/contracts/libs/PancakeVoteProxy.sol farming/contracts/libs/Migrations.sol farming/contracts/MasterChef.sol farming/contracts/Timelock.sol farming/contracts/libs/Mo ckBEP20.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided some functional requirements and no technical requirements. The contracts are forks of well -known ones. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 9 out of 10. No NatSpecs. Architecture quality The architecture quality score is 10 out of 10. Security score As a result of the audit, security engineers found 1 low severity issue. The security score is 10 out of 10. All found issues are displayed in the “Issues overview” sectio n. Summary According to the assessment, the Customer's smart contract has the following score: 9.9 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High 1. Possible rewards lost or receiving more Changing allocPoint in the MasterBlid.set method while _withUpdate flag is set to false may lead to rewards lost or receiving rewards more than deserved. Contract: MasterChef.sol Function: set Recommendation : Call updatePool(_pid) in the case if _withUpdate flag is false and you do not want to update all pools. Status: Fixed. (Revised Commit: 9ca0cf0) Medium 1. Privileged ownership The owner of the MasterBlid contract has permission to `updateMultiplier`, add new pools, change pool’s allocation points, and set a migrator contract (which will move all LPs from the pool to itself) without community consensus. Contract: MasterChef.sol Recommendation : Consider using one of the following methodologies: - Transfer ownership to a Time -lock contract with reasonable latency (i.e. 24h) so the community may react to changes; - Transfer ownership to a multi -signature wallet to prevent a single point of failure; - Transfer ownership to DAO so the community could decide whether the privileged operations should be executed by voting. Status: Fixed; Moved ownership to a Timelock (Revised Commit: 9ca0cf0) Low 1. Excess writing operation When _allocPoint is not changed for the pool, there is still an assignment for a new value, which consumes gas doing nothing. Contract: MasterChef.sol Function: set Recommendation :Move “poolInfo[_pid].allocPoint = _allocPoint” assignment inside the if block. www.hacken.io Status: Fixed (Revised Commit: 9378f79) 2. Missing Emit Events Functions that change critical values should emit events for better off-chain tracking. Contract: MasterChef.sol Function: setMigrator, updateMultiplier, setBlidPerBlock Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9378f79) 3. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 4. Balance upda ted after transfer It is recommended to update the balance state before doing any token transfer. Contract : MasterChef.sol Functions : emergencyWithdraw, migrate Recommendation : Update the balance and do transfer after that . Status: Reported (Revised Commit: 9378f79) 5. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: MasterChef.sol Functions : updateMultiplier, add, set, setBlidPerBlock, setM igrator, setExpenseAddress, migrate, deposit, withdraw, enterStaking, leaveStaking Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9378f79) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no sta tements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements . While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hacks. Thus, the audit can not guarantee the explicit security o f the audited smart contracts.
Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Unchecked external call (strategies/low_risk/contracts/Logic.sol:L51) - Unchecked math (strategies/low_risk/contracts/Logic.sol:L51) - Unsafe type inference (strategies/low_risk/contracts/Logic.sol:L51) - Implicit visibility level (strategies/low_risk/contracts/Logic.sol:L51) 2.b Fix (one line with code reference) - Check external call (strategies/low_risk/contracts/Logic.sol:L51) - Check math (strategies/low_risk/contracts/Logic.sol:L51) - Use safe type inference (strategies/low_risk/contracts/Logic.sol:L51) - Use explicit visibility level (strategies/low_risk/contract Issues Count of Minor/Moderate/Major/Critical - Critical: 0 - High: 0 - Moderate: 1 - Minor: 3 Minor Issues 2.a Test failed (Scope: strategies, Revised Commit: 9378f79) 2.b Ensure that the tests are successful and cover all the code branches. Moderate 3.a Floating solidity version (Contracts: all, Revised Commit: 9378f79) 3.b Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Major 4.a Excessive state access (Contract: StorageV0.sol, Revised Commit: 9ca0cf0) 4.b Read the state variable to a local memory instead of multiple reading. Critical No critical severity issues were found. Observations - Logic is split into modules. - Contracts are self-descriptive. - No thinking about gas efficiency. - Room for improvements in code structuring. Conclusion According to the assessment, the Customer's smart contract has the following score: 9.5. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
// SPDX-License-Identifier: MIT pragma solidity "0.8.13"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; interface LogicContract { function returnToken(uint256 amount, address token) external; } interface AggregatorV3Interface { function decimals() external view returns (uint8); function latestAnswer() external view returns (int256 answer); } contract StorageV2 is Initializable, OwnableUpgradeable, PausableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; //struct struct DepositStruct { mapping(address => uint256) amount; mapping(address => int256) tokenTime; uint256 iterate; uint256 balanceBLID; mapping(address => uint256) depositIterate; } struct EarnBLID { uint256 allBLID; uint256 timestamp; uint256 usd; uint256 tdt; mapping(address => uint256) rates; } /*** events ***/ event Deposit(address depositor, address token, uint256 amount); event Withdraw(address depositor, address token, uint256 amount); event UpdateTokenBalance(uint256 balance, address token); event TakeToken(address token, uint256 amount); event ReturnToken(address token, uint256 amount); event AddEarn(uint256 amount); event UpdateBLIDBalance(uint256 balance); event InterestFee(address depositor, uint256 amount); event SetBLID(address blid); event AddToken(address token, address oracle); event SetLogic(address logic); function initialize(address _logicContract) external initializer { OwnableUpgradeable.__Ownable_init(); PausableUpgradeable.__Pausable_init(); logicContract = _logicContract; } // SWC-State Variable Default Visibility: L63 - L76 mapping(uint256 => EarnBLID) private earnBLID; uint256 private countEarns; uint256 private countTokens; mapping(uint256 => address) private tokens; mapping(address => uint256) private tokenBalance; mapping(address => address) private oracles; mapping(address => bool) private tokensAdd; mapping(address => DepositStruct) private deposits; mapping(address => uint256) private tokenDeposited; mapping(address => int256) private tokenTime; uint256 private reserveBLID; address private logicContract; address private BLID; mapping(address => mapping(uint256 => uint256)) public accumulatedRewardsPerShare; /*** modifiers ***/ modifier isUsedToken(address _token) { require(tokensAdd[_token], "E1"); _; } modifier isLogicContract(address account) { require(logicContract == account, "E2"); _; } /*** User function ***/ /** * @notice Deposit amount of token to Strategy and receiving earned tokens. * @param amount amount of token * @param token address of token */ function deposit(uint256 amount, address token) external isUsedToken(token) whenNotPaused { require(amount > 0, "E3"); uint8 decimals = AggregatorV3Interface(token).decimals(); DepositStruct storage depositor = deposits[msg.sender]; IERC20Upgradeable(token).safeTransferFrom(msg.sender, address(this), amount); uint256 amountExp18 = amount * 10**(18 - decimals); if (depositor.tokenTime[address(0)] == 0) { depositor.iterate = countEarns; depositor.depositIterate[token] = countEarns; depositor.tokenTime[address(0)] = 1; depositor.tokenTime[token] += int256(block.timestamp * (amountExp18)); } else { interestFee(); if (depositor.depositIterate[token] == countEarns) { depositor.tokenTime[token] += int256(block.timestamp * (amountExp18)); } else { depositor.tokenTime[token] = int256( depositor.amount[token] * earnBLID[countEarns - 1].timestamp + block.timestamp * (amountExp18) ); depositor.depositIterate[token] = countEarns; } } depositor.amount[token] += amountExp18; tokenTime[token] += int256(block.timestamp * (amountExp18)); tokenBalance[token] += amountExp18; tokenDeposited[token] += amountExp18; emit UpdateTokenBalance(tokenBalance[token], token); emit Deposit(msg.sender, token, amountExp18); } /** * @notice Withdraw amount of token from Strategy and receiving earned tokens. * @param amount Amount of token * @param token Address of token */ function withdraw(uint256 amount, address token) external isUsedToken(token) whenNotPaused { uint8 decimals = AggregatorV3Interface(token).decimals(); uint256 countEarns_ = countEarns; uint256 amountExp18 = amount * 10**(18 - decimals); DepositStruct storage depositor = deposits[msg.sender]; require(depositor.amount[token] >= amountExp18 && amount > 0, "E4"); if (amountExp18 > tokenBalance[token]) { LogicContract(logicContract).returnToken(amount, token); interestFee(); IERC20Upgradeable(token).safeTransferFrom(logicContract, msg.sender, amount); tokenDeposited[token] -= amountExp18; tokenTime[token] -= int256(block.timestamp * (amountExp18)); } else { interestFee(); IERC20Upgradeable(token).safeTransfer(msg.sender, amount); tokenTime[token] -= int256(block.timestamp * (amountExp18)); tokenBalance[token] -= amountExp18; tokenDeposited[token] -= amountExp18; } if (depositor.depositIterate[token] == countEarns_) { depositor.tokenTime[token] -= int256(block.timestamp * (amountExp18)); } else { depositor.tokenTime[token] = int256(depositor.amount[token] * earnBLID[countEarns_ - 1].timestamp) - int256(block.timestamp * (amountExp18)); depositor.depositIterate[token] = countEarns_; } depositor.amount[token] -= amountExp18; emit UpdateTokenBalance(tokenBalance[token], token); emit Withdraw(msg.sender, token, amountExp18); } /** * @notice Claim BLID to msg.sender */ function interestFee() public { uint256 balanceUser = balanceEarnBLID(msg.sender); require(reserveBLID >= balanceUser, "E5"); IERC20Upgradeable(BLID).safeTransfer(msg.sender, balanceUser); DepositStruct storage depositor = deposits[msg.sender]; depositor.balanceBLID = balanceUser; depositor.iterate = countEarns; //unchecked is used because a check was made in require unchecked { depositor.balanceBLID = 0; reserveBLID -= balanceUser; } emit UpdateBLIDBalance(reserveBLID); emit InterestFee(msg.sender, balanceUser); } /*** Owner functions ***/ /** * @notice Set blid in contract * @param _blid address of BLID */ function setBLID(address _blid) external onlyOwner { BLID = _blid; emit SetBLID(_blid); } /** * @notice Triggers stopped state. */ function pause() external onlyOwner { _pause(); } /** * @notice Returns to normal state. */ function unpause() external onlyOwner { _unpause(); } /** * @notice Update AccumulatedRewardsPerShare for token, using once after update contract * @param token Address of token */ function updateAccumulatedRewardsPerShare(address token) external onlyOwner { require(accumulatedRewardsPerShare[token][0] == 0, "E7"); uint256 countEarns_ = countEarns; for (uint256 i = 0; i < countEarns_; i++) { updateAccumulatedRewardsPerShareById(token, i); } } /** * @notice Add token and token's oracle * @param _token Address of Token * @param _oracles Address of token's oracle(https://docs.chain.link/docs/binance-smart-chain-addresses/ */ function addToken(address _token, address _oracles) external onlyOwner { require(_token != address(0) && _oracles != address(0)); require(!tokensAdd[_token], "E6"); oracles[_token] = _oracles; tokens[countTokens++] = _token; tokensAdd[_token] = true; emit AddToken(_token, _oracles); } /** * @notice Set logic in contract(only for upgradebale contract,use only whith DAO) * @param _logic Address of Logic Contract */ function setLogic(address _logic) external onlyOwner { logicContract = _logic; emit SetLogic(_logic); } /*** LogicContract function ***/ /** * @notice Transfer amount of token from Storage to Logic Contract. * @param amount Amount of token * @param token Address of token */ function takeToken(uint256 amount, address token) external isLogicContract(msg.sender) isUsedToken(token) { uint8 decimals = AggregatorV3Interface(token).decimals(); uint256 amountExp18 = amount * 10**(18 - decimals); IERC20Upgradeable(token).safeTransfer(msg.sender, amount); tokenBalance[token] = tokenBalance[token] - amountExp18; emit UpdateTokenBalance(tokenBalance[token], token); emit TakeToken(token, amountExp18); } /** * @notice Transfer amount of token from Storage to Logic Contract. * @param amount Amount of token * @param token Address of token */ function returnToken(uint256 amount, address token) external isLogicContract(msg.sender) isUsedToken(token) { uint8 decimals = AggregatorV3Interface(token).decimals(); uint256 amountExp18 = amount * 10**(18 - decimals); IERC20Upgradeable(token).safeTransferFrom(logicContract, address(this), amount); tokenBalance[token] = tokenBalance[token] + amountExp18; emit UpdateTokenBalance(tokenBalance[token], token); emit ReturnToken(token, amountExp18); } /** * @notice Take amount BLID from Logic contract and distributes earned BLID * @param amount Amount of distributes earned BLID */ function addEarn(uint256 amount) external isLogicContract(msg.sender) { IERC20Upgradeable(BLID).safeTransferFrom(msg.sender, address(this), amount); reserveBLID += amount; int256 _dollarTime = 0; uint256 countTokens_ = countTokens; uint256 countEarns_ = countEarns; EarnBLID storage thisEarnBLID = earnBLID[countEarns_]; for (uint256 i = 0; i < countTokens_; i++) { address token = tokens[i]; AggregatorV3Interface oracle = AggregatorV3Interface(oracles[token]); thisEarnBLID.rates[token] = (uint256(oracle.latestAnswer()) * 10**(18 - oracle.decimals())); // count all deposited token in usd thisEarnBLID.usd += tokenDeposited[token] * thisEarnBLID.rates[token]; // convert token time to dollar time _dollarTime += tokenTime[token] * int256(thisEarnBLID.rates[token]); } require(_dollarTime != 0); thisEarnBLID.allBLID = amount; thisEarnBLID.timestamp = block.timestamp; thisEarnBLID.tdt = uint256( (int256(((block.timestamp) * thisEarnBLID.usd)) - _dollarTime) / (1 ether) ); // count delta of current token time and all user token time for (uint256 i = 0; i < countTokens_; i++) { address token = tokens[i]; tokenTime[token] = int256(tokenDeposited[token] * block.timestamp); // count curent token time updateAccumulatedRewardsPerShareById(token, countEarns_); } thisEarnBLID.usd /= (1 ether); countEarns++; emit AddEarn(amount); emit UpdateBLIDBalance(reserveBLID); } /*** External function ***/ /** * @notice Counts the number of accrued СSR * @param account Address of Depositor */ function _upBalance(address account) external { deposits[account].balanceBLID = balanceEarnBLID(account); deposits[account].iterate = countEarns; } /*** Public View function ***/ /** * @notice Return earned blid * @param account Address of Depositor */ function balanceEarnBLID(address account) public view returns (uint256) { DepositStruct storage depositor = deposits[account]; if (depositor.tokenTime[address(0)] == 0 || countEarns == 0) { return 0; } if (countEarns == depositor.iterate) return depositor.balanceBLID; uint256 countTokens_ = countTokens; uint256 sum = 0; uint256 depositorIterate = depositor.iterate; for (uint256 j = 0; j < countTokens_; j++) { address token = tokens[j]; //if iterate when user deposited if (depositorIterate == depositor.depositIterate[token]) { sum += getEarnedInOneDepositedIterate(depositorIterate, token, account); sum += getEarnedInOneNotDepositedIterate(depositorIterate, token, account); } else { sum += getEarnedInOneNotDepositedIterate(depositorIterate - 1, token, account); } } return sum + depositor.balanceBLID; } /*** External View function ***/ /** * @notice Return usd balance of account * @param account Address of Depositor */ function balanceOf(address account) external view returns (uint256) { uint256 countTokens_ = countTokens; uint256 sum = 0; for (uint256 j = 0; j < countTokens_; j++) { address token = tokens[j]; AggregatorV3Interface oracle = AggregatorV3Interface(oracles[token]); sum += ((deposits[account].amount[token] * uint256(oracle.latestAnswer()) * 10**(18 - oracle.decimals())) / (1 ether)); } return sum; } /** * @notice Return sums of all distribution BLID. */ function getBLIDReserve() external view returns (uint256) { return reserveBLID; } /** * @notice Return deposited usd */ function getTotalDeposit() external view returns (uint256) { uint256 countTokens_ = countTokens; uint256 sum = 0; for (uint256 j = 0; j < countTokens_; j++) { address token = tokens[j]; AggregatorV3Interface oracle = AggregatorV3Interface(oracles[token]); sum += (tokenDeposited[token] * uint256(oracle.latestAnswer()) * 10**(18 - oracle.decimals())) / (1 ether); } return sum; } /** * @notice Returns the balance of token on this contract */ function getTokenBalance(address token) external view returns (uint256) { return tokenBalance[token]; } /** * @notice Return deposited token from account */ function getTokenDeposit(address account, address token) external view returns (uint256) { return deposits[account].amount[token]; } /** * @notice Return true if _token is in token list * @param _token Address of Token */ function _isUsedToken(address _token) external view returns (bool) { return tokensAdd[_token]; } /** * @notice Return count distribution BLID token. */ function getCountEarns() external view returns (uint256) { return countEarns; } /** * @notice Return data on distribution BLID token. * First return value is amount of distribution BLID token. * Second return value is a timestamp when distribution BLID token completed. * Third return value is an amount of dollar depositedhen distribution BLID token completed. */ function getEarnsByID(uint256 id) external view returns ( uint256, uint256, uint256 ) { return (earnBLID[id].allBLID, earnBLID[id].timestamp, earnBLID[id].usd); } /** * @notice Return amount of all deposited token * @param token Address of Token */ function getTokenDeposited(address token) external view returns (uint256) { return tokenDeposited[token]; } /*** Prvate Function ***/ /** * @notice Count accumulatedRewardsPerShare * @param token Address of Token * @param id of accumulatedRewardsPerShare */ function updateAccumulatedRewardsPerShareById(address token, uint256 id) private { EarnBLID storage thisEarnBLID = earnBLID[id]; //unchecked is used because if id = 0 then accumulatedRewardsPerShare[token][id-1] equal zero unchecked { accumulatedRewardsPerShare[token][id] = accumulatedRewardsPerShare[token][id - 1] + ((thisEarnBLID.allBLID * (thisEarnBLID.timestamp - earnBLID[id - 1].timestamp) * thisEarnBLID.rates[token]) / thisEarnBLID.tdt); } } /** * @notice Count user rewards in one iterate, when he deposited * @param token Address of Token * @param depositIterate iterate when deposit happened * @param account Address of Depositor */ function getEarnedInOneDepositedIterate( uint256 depositIterate, address token, address account ) private view returns (uint256) { EarnBLID storage thisEarnBLID = earnBLID[depositIterate]; DepositStruct storage thisDepositor = deposits[account]; return (// all distibution BLID multiply to thisEarnBLID.allBLID * // delta of user dollar time and user dollar time if user deposited in at the beginning distibution uint256( int256(thisDepositor.amount[token] * thisEarnBLID.rates[token] * thisEarnBLID.timestamp) - thisDepositor.tokenTime[token] * int256(thisEarnBLID.rates[token]) )) / //div to delta of all users dollar time and all users dollar time if all users deposited in at the beginning distibution thisEarnBLID.tdt / (1 ether); } /*** Prvate View Function ***/ /** * @notice Count user rewards in one iterate, when he was not deposit * @param token Address of Token * @param depositIterate iterate when deposit happened * @param account Address of Depositor */ function getEarnedInOneNotDepositedIterate( uint256 depositIterate, address token, address account ) private view returns (uint256) { return ((accumulatedRewardsPerShare[token][countEarns - 1] - accumulatedRewardsPerShare[token][depositIterate]) * deposits[account].amount[token]) / (1 ether); } } // SPDX-License-Identifier: MIT pragma solidity "0.8.13"; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IStorage { function takeToken(uint256 amount, address token) external; function returnToken(uint256 amount, address token) external; function addEarn(uint256 amount) external; } interface IDistribution { function enterMarkets(address[] calldata vTokens) external returns (uint256[] memory); function markets(address vTokenAddress) external view returns ( bool, uint256, bool ); function claimVenus(address holder) external; function claimVenus(address holder, address[] memory vTokens) external; } interface IMasterChef { function poolInfo(uint256 _pid) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accCakePerShare ); function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function enterStaking(uint256 _amount) external; function leaveStaking(uint256 _amount) external; function emergencyWithdraw(uint256 _pid) external; function userInfo(uint256 _pid, address account) external view returns (uint256, uint256); } interface IVToken { function mint(uint256 mintAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint() external payable; function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function repayBorrow() external payable; } interface IPancakePair { function token0() external view returns (address); function token1() external view returns (address); } interface IPancakeRouter01 { function WETH() external pure returns (address); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } contract Logic is Ownable { using SafeERC20 for IERC20; struct ReserveLiquidity { address tokenA; address tokenB; address vTokenA; address vTokenB; address swap; address swapMaster; address lpToken; uint256 poolID; address[][] path; } address private _storage; address private blid; address private admin; address private venusController; address private pancake; address private apeswap; address private pancakeMaster; address private apeswapMaster; address private expenseAddress; address private vBNB; mapping(address => bool) private usedVTokens; mapping(address => address) private VTokens; ReserveLiquidity[] reserves; event SetAdmin(address admin); event SetBLID(address _blid); event SetStorage(address _storage); constructor( address _expenseAddress, address _venusController, address pancakeRouter, address apeswapRouter, address pancakeMaster_, address apeswapMaster_ ) { expenseAddress = _expenseAddress; venusController = _venusController; apeswap = apeswapRouter; pancake = pancakeRouter; pancakeMaster = pancakeMaster_; apeswapMaster = apeswapMaster_; } fallback() external payable {} receive() external payable {} modifier onlyOwnerAndAdmin() { require(msg.sender == owner() || msg.sender == admin, "E1"); _; } modifier onlyStorage() { require(msg.sender == _storage, "E1"); _; } modifier isUsedVToken(address vToken) { require(usedVTokens[vToken], "E2"); _; } modifier isUsedSwap(address swap) { require(swap == apeswap || swap == pancake, "E3"); _; } modifier isUsedMaster(address swap) { require(swap == pancakeMaster || apeswapMaster == swap, "E4"); _; } /** * @notice Add VToken in Contract and approve token for storage, venus, * pancakeswap/apeswap router, and pancakeswap/apeswap master(Main Staking contract) * @param token Address of Token for deposited * @param vToken Address of VToken */ function addVTokens(address token, address vToken) external onlyOwner { bool _isUsedVToken; (_isUsedVToken, , ) = IDistribution(venusController).markets(vToken); require(_isUsedVToken, "E5"); if ((token) != address(0)) { IERC20(token).approve(vToken, type(uint256).max); IERC20(token).approve(apeswap, type(uint256).max); IERC20(token).approve(pancake, type(uint256).max); IERC20(token).approve(_storage, type(uint256).max); IERC20(token).approve(pancakeMaster, type(uint256).max); IERC20(token).approve(apeswapMaster, type(uint256).max); VTokens[token] = vToken; } else { vBNB = vToken; } usedVTokens[vToken] = true; } /** * @notice Set blid in contract and approve blid for storage, venus, pancakeswap/apeswap * router, and pancakeswap/apeswap master(Main Staking contract), you can call the * function once * @param blid_ Adrees of BLID */ function setBLID(address blid_) external onlyOwner { require(blid == address(0), "E6"); blid = blid_; IERC20(blid).safeApprove(apeswap, type(uint256).max); IERC20(blid).safeApprove(pancake, type(uint256).max); IERC20(blid).safeApprove(pancakeMaster, type(uint256).max); IERC20(blid).safeApprove(apeswapMaster, type(uint256).max); IERC20(blid).safeApprove(_storage, type(uint256).max); emit SetBLID(blid_); } /** * @notice Set storage, you can call the function once * @param storage_ Addres of Storage Contract */ function setStorage(address storage_) external onlyOwner { require(_storage == address(0), "E7"); _storage = storage_; emit SetStorage(storage_); } /** * @notice Approve token for storage, venus, pancakeswap/apeswap router, * and pancakeswap/apeswap master(Main Staking contract) * @param token Address of Token that is approved */ function approveTokenForSwap(address token) external onlyOwner { (IERC20(token).approve(apeswap, type(uint256).max)); (IERC20(token).approve(pancake, type(uint256).max)); (IERC20(token).approve(pancakeMaster, type(uint256).max)); (IERC20(token).approve(apeswapMaster, type(uint256).max)); } /** * @notice Frees up tokens for the user, but Storage doesn't transfer token for the user, * only Storage can this function, after calling this function Storage transfer * from Logic to user token. * @param amount Amount of token * @param token Address of token */ function returnToken(uint256 amount, address token) external payable onlyStorage { uint256 takeFromVenus = 0; uint256 length = reserves.length; //check logic balance if (IERC20(token).balanceOf(address(this)) >= amount) { return; } //loop by reserves lp token for (uint256 i = 0; i < length; i++) { address[] memory path = findPath(i, token); // get path for router ReserveLiquidity memory reserve = reserves[i]; uint256 lpAmount = getPriceFromTokenToLp( reserve.lpToken, amount - takeFromVenus, token, reserve.swap, path ); //get amount of lp token that need for reedem liqudity //get how many deposited to farming (uint256 depositedLp, ) = IMasterChef(reserve.swapMaster).userInfo(reserve.poolID, address(this)); if (depositedLp == 0) continue; // if deposited LP tokens don't enough for repay borrow and for reedem token then only repay // borow and continue loop, else repay borow, reedem token and break loop if (lpAmount >= depositedLp) { takeFromVenus += getPriceFromLpToToken( reserve.lpToken, depositedLp, token, reserve.swap, path ); withdrawAndRepay(reserve, depositedLp); } else { withdrawAndRepay(reserve, lpAmount); // get supplied token and break loop IVToken(VTokens[token]).redeemUnderlying(amount); return; } } //try get supplied token IVToken(VTokens[token]).redeemUnderlying(amount); //if get money if (IERC20(token).balanceOf(address(this)) >= amount) { return; } revert("no money"); } /** * @notice Set admin * @param newAdmin Addres of new admin */ function setAdmin(address newAdmin) external onlyOwner { admin = newAdmin; emit SetAdmin(newAdmin); } /** * @notice Transfer amount of token from Storage to Logic contract token - address of the token * @param amount Amount of token * @param token Address of token */ function takeTokenFromStorage(uint256 amount, address token) external onlyOwnerAndAdmin { IStorage(_storage).takeToken(amount, token); } /** * @notice Transfer amount of token from Logic to Storage contract token - address of token * @param amount Amount of token * @param token Address of token */ function returnTokenToStorage(uint256 amount, address token) external onlyOwnerAndAdmin { IStorage(_storage).returnToken(amount, token); } /** * @notice Distribution amount of blid to depositors. * @param amount Amount of BLID */ function addEarnToStorage(uint256 amount) external onlyOwnerAndAdmin { IERC20(blid).safeTransfer(expenseAddress, (amount * 3) / 100); IStorage(_storage).addEarn((amount * 97) / 100); } /** * @notice Enter into a list of markets(address of VTokens) - it is not an * error to enter the same market more than once. * @param vTokens The addresses of the vToken markets to enter. * @return For each market, returns an error code indicating whether or not it was entered. * Each is 0 on success, otherwise an Error code */ function enterMarkets(address[] calldata vTokens) external onlyOwnerAndAdmin returns (uint256[] memory) { return IDistribution(venusController).enterMarkets(vTokens); } /** * @notice Every Venus user accrues XVS for each block * they are supplying to or borrowing from the protocol. * @param vTokens The addresses of the vToken markets to enter. */ function claimVenus(address[] calldata vTokens) external onlyOwnerAndAdmin { IDistribution(venusController).claimVenus(address(this), vTokens); } /** * @notice Stake token and mint VToken * @param vToken: that mint Vtokens to this contract * @param mintAmount: The amount of the asset to be supplied, in units of the underlying asset. * @return 0 on success, otherwise an Error code */ function mint(address vToken, uint256 mintAmount) external isUsedVToken(vToken) onlyOwnerAndAdmin returns (uint256) { if (vToken == vBNB) { IVToken(vToken).mint{ value: mintAmount }(); } return IVToken(vToken).mint(mintAmount); } /** * @notice The borrow function transfers an asset from the protocol to the user and creates a * borrow balance which begins accumulating interest based on the Borrow Rate for the asset. * The amount borrowed must be less than the user's Account Liquidity and the market's * available liquidity. * @param vToken: that mint Vtokens to this contract * @param borrowAmount: The amount of underlying to be borrow. * @return 0 on success, otherwise an Error code */ function borrow(address vToken, uint256 borrowAmount) external payable isUsedVToken(vToken) onlyOwnerAndAdmin returns (uint256) { return IVToken(vToken).borrow(borrowAmount); } /** * @notice The repay function transfers an asset into the protocol, reducing the user's borrow balance. * @param vToken: that mint Vtokens to this contract * @param repayAmount: The amount of the underlying borrowed asset to be repaid. * A value of -1 (i.e. 2256 - 1) can be used to repay the full amount. * @return 0 on success, otherwise an Error code */ function repayBorrow(address vToken, uint256 repayAmount) external isUsedVToken(vToken) onlyOwnerAndAdmin returns (uint256) { if (vToken == vBNB) { IVToken(vToken).repayBorrow{ value: repayAmount }(); return 0; } return IVToken(vToken).repayBorrow(repayAmount); } /** * @notice The redeem underlying function converts vTokens into a specified quantity of the * underlying asset, and returns them to the user. * The amount of vTokens redeemed is equal to the quantity of underlying tokens received, * divided by the current Exchange Rate. * The amount redeemed must be less than the user's Account Liquidity and the market's * available liquidity. * @param vToken: that mint Vtokens to this contract * @param redeemAmount: The amount of underlying to be redeemed. * @return 0 on success, otherwise an Error code */ function redeemUnderlying(address vToken, uint256 redeemAmount) external isUsedVToken(vToken) onlyOwnerAndAdmin returns (uint256) { return IVToken(vToken).redeemUnderlying(redeemAmount); } /** * @notice Adds liquidity to a BEP20⇄BEP20 pool. * @param swap Address of swap router * @param tokenA The contract address of one token from your liquidity pair. * @param tokenB The contract address of the other token from your liquidity pair. * @param amountADesired The amount of tokenA you'd like to provide as liquidity. * @param amountBDesired The amount of tokenA you'd like to provide as liquidity. * @param amountAMin The minimum amount of tokenA to provide (slippage impact). * @param amountBMin The minimum amount of tokenB to provide (slippage impact). * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function addLiquidity( address swap, address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) external isUsedSwap(swap) onlyOwnerAndAdmin returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { (amountADesired, amountBDesired, amountAMin) = IPancakeRouter01(swap).addLiquidity( tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, address(this), deadline ); return (amountADesired, amountBDesired, amountAMin); } /** * @notice Removes liquidity from a BEP20⇄BEP20 pool. * @param swap Address of swap router * @param tokenA The contract address of one token from your liquidity pair. * @param tokenB The contract address of the other token from your liquidity pair. * @param liquidity The amount of LP Tokens to remove. * @param amountAMin he minimum amount of tokenA to provide (slippage impact). * @param amountBMin The minimum amount of tokenB to provide (slippage impact). * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function removeLiquidity( address swap, address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, uint256 deadline ) external onlyOwnerAndAdmin isUsedSwap(swap) returns (uint256 amountA, uint256 amountB) { (amountAMin, amountBMin) = IPancakeRouter01(swap).removeLiquidity( tokenA, tokenB, liquidity, amountAMin, amountBMin, address(this), deadline ); return (amountAMin, amountBMin); } /** * @notice Receive an as many output tokens as possible for an exact amount of input tokens. * @param swap Address of swap router * @param amountIn TPayable amount of input tokens. * @param amountOutMin The minimum amount tokens to receive. * @param path (address[]) An array of token addresses. path.length must be >= 2. * Pools for each consecutive pair of addresses must exist and have liquidity. * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function swapExactTokensForTokens( address swap, uint256 amountIn, uint256 amountOutMin, address[] calldata path, uint256 deadline ) external isUsedSwap(swap) onlyOwnerAndAdmin returns (uint256[] memory amounts) { return IPancakeRouter01(swap).swapExactTokensForTokens( amountIn, amountOutMin, path, address(this), deadline ); } /** * @notice Receive an exact amount of output tokens for as few input tokens as possible. * @param swap Address of swap router * @param amountOut Payable amount of input tokens. * @param amountInMax The minimum amount tokens to input. * @param path (address[]) An array of token addresses. path.length must be >= 2. * Pools for each consecutive pair of addresses must exist and have liquidity. * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function swapTokensForExactTokens( address swap, uint256 amountOut, uint256 amountInMax, address[] calldata path, uint256 deadline ) external onlyOwnerAndAdmin isUsedSwap(swap) returns (uint256[] memory amounts) { return IPancakeRouter01(swap).swapTokensForExactTokens( amountOut, amountInMax, path, address(this), deadline ); } /** * @notice Adds liquidity to a BEP20⇄WBNB pool. * @param swap Address of swap router * @param token The contract address of one token from your liquidity pair. * @param amountTokenDesired The amount of the token you'd like to provide as liquidity. * @param amountETHDesired The minimum amount of the token to provide (slippage impact). * @param amountTokenMin The minimum amount of token to provide (slippage impact). * @param amountETHMin The minimum amount of BNB to provide (slippage impact). * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function addLiquidityETH( address swap, address token, uint256 amountTokenDesired, uint256 amountETHDesired, uint256 amountTokenMin, uint256 amountETHMin, uint256 deadline ) external isUsedSwap(swap) onlyOwnerAndAdmin returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { (amountETHDesired, amountTokenMin, amountETHMin) = IPancakeRouter01(swap).addLiquidityETH{ value: amountETHDesired }(token, amountTokenDesired, amountTokenMin, amountETHMin, address(this), deadline); return (amountETHDesired, amountTokenMin, amountETHMin); } /** * @notice Removes liquidity from a BEP20⇄WBNB pool. * @param swap Address of swap router * @param token The contract address of one token from your liquidity pair. * @param liquidity The amount of LP Tokens to remove. * @param amountTokenMin The minimum amount of the token to remove (slippage impact). * @param amountETHMin The minimum amount of BNB to remove (slippage impact). * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function removeLiquidityETH( address swap, address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, uint256 deadline ) external payable isUsedSwap(swap) onlyOwnerAndAdmin returns (uint256 amountToken, uint256 amountETH) { (deadline, amountETHMin) = IPancakeRouter01(swap).removeLiquidityETH( token, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); return (deadline, amountETHMin); } /** * @notice Receive as many output tokens as possible for an exact amount of BNB. * @param swap Address of swap router * @param amountETH Payable BNB amount. * @param amountOutMin The minimum amount tokens to input. * @param path (address[]) An array of token addresses. path.length must be >= 2. * Pools for each consecutive pair of addresses must exist and have liquidity. * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function swapExactETHForTokens( address swap, uint256 amountETH, uint256 amountOutMin, address[] calldata path, uint256 deadline ) external isUsedSwap(swap) onlyOwnerAndAdmin returns (uint256[] memory amounts) { return IPancakeRouter01(swap).swapExactETHForTokens{ value: amountETH }( amountOutMin, path, address(this), deadline ); } /** * @notice Receive an exact amount of output tokens for as few input tokens as possible. * @param swap Address of swap router * @param amountOut Payable BNB amount. * @param amountInMax The minimum amount tokens to input. * @param path (address[]) An array of token addresses. path.length must be >= 2. * Pools for each consecutive pair of addresses must exist and have liquidity. * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function swapTokensForExactETH( address swap, uint256 amountOut, uint256 amountInMax, address[] calldata path, uint256 deadline ) external payable isUsedSwap(swap) onlyOwnerAndAdmin returns (uint256[] memory amounts) { return IPancakeRouter01(swap).swapTokensForExactETH( amountOut, amountInMax, path, address(this), deadline ); } /** * @notice Receive as much BNB as possible for an exact amount of input tokens. * @param swap Address of swap router * @param amountIn Payable amount of input tokens. * @param amountOutMin The maximum amount tokens to input. * @param path (address[]) An array of token addresses. path.length must be >= 2. * Pools for each consecutive pair of addresses must exist and have liquidity. * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function swapExactTokensForETH( address swap, uint256 amountIn, uint256 amountOutMin, address[] calldata path, uint256 deadline ) external payable isUsedSwap(swap) onlyOwnerAndAdmin returns (uint256[] memory amounts) { return IPancakeRouter01(swap).swapExactTokensForETH( amountIn, amountOutMin, path, address(this), deadline ); } /** * @notice Receive an exact amount of output tokens for as little BNB as possible. * @param swap Address of swap router * @param amountOut The amount tokens to receive. * @param amountETH Payable BNB amount. * @param path (address[]) An array of token addresses. path.length must be >= 2. * Pools for each consecutive pair of addresses must exist and have liquidity. * @param deadline Unix timestamp deadline by which the transaction must confirm. */ function swapETHForExactTokens( address swap, uint256 amountETH, uint256 amountOut, address[] calldata path, uint256 deadline ) external isUsedSwap(swap) onlyOwnerAndAdmin returns (uint256[] memory amounts) { return IPancakeRouter01(swap).swapETHForExactTokens{ value: amountETH }( amountOut, path, address(this), deadline ); } /** * @notice Deposit LP tokens to Master * @param swapMaster Address of swap master(Main staking contract) * @param _pid pool id * @param _amount amount of lp token */ function deposit( address swapMaster, uint256 _pid, uint256 _amount ) external isUsedMaster(swapMaster) onlyOwnerAndAdmin { IMasterChef(swapMaster).deposit(_pid, _amount); } /** * @notice Withdraw LP tokens from Master * @param swapMaster Address of swap master(Main staking contract) * @param _pid pool id * @param _amount amount of lp token */ function withdraw( address swapMaster, uint256 _pid, uint256 _amount ) external isUsedMaster(swapMaster) onlyOwnerAndAdmin { IMasterChef(swapMaster).withdraw(_pid, _amount); } /** * @notice Stake BANANA/Cake tokens to STAKING. * @param swapMaster Address of swap master(Main staking contract) * @param _amount amount of lp token */ function enterStaking(address swapMaster, uint256 _amount) external isUsedMaster(swapMaster) onlyOwnerAndAdmin { IMasterChef(swapMaster).enterStaking(_amount); } /** * @notice Withdraw BANANA/Cake tokens from STAKING. * @param swapMaster Address of swap master(Main staking contract) * @param _amount amount of lp token */ function leaveStaking(address swapMaster, uint256 _amount) external isUsedMaster(swapMaster) onlyOwnerAndAdmin { IMasterChef(swapMaster).leaveStaking(_amount); } /** * @notice Add reserve staked lp token to end list * @param reserveLiquidity Data is about staked lp in farm */ function addReserveLiquidity(ReserveLiquidity memory reserveLiquidity) external onlyOwnerAndAdmin { reserves.push(reserveLiquidity); } /** * @notice Delete last ReserveLiquidity from list of ReserveLiquidity */ function deleteLastReserveLiquidity() external onlyOwnerAndAdmin { reserves.pop(); } /** * @notice Return count reserves staked lp tokens for return users their tokens. */ function getReservesCount() external view returns (uint256) { return reserves.length; } /** * @notice Return reserves staked lp tokens for return user their tokens. return ReserveLiquidity */ function getReserve(uint256 id) external view returns (ReserveLiquidity memory) { return reserves[id]; } /*** Prive Function ***/ /** * @notice Repay borrow when in farms erc20 and BNB */ function repayBorrowBNBandToken( address swap, address tokenB, address VTokenA, address VTokenB, uint256 lpAmount ) private { (uint256 amountToken, uint256 amountETH) = IPancakeRouter01(swap).removeLiquidityETH( tokenB, lpAmount, 0, 0, address(this), block.timestamp + 1 days ); { uint256 totalBorrow = IVToken(VTokenA).borrowBalanceCurrent(address(this)); if (totalBorrow >= amountETH) { IVToken(VTokenA).repayBorrow{ value: amountETH }(); } else { IVToken(VTokenA).repayBorrow{ value: totalBorrow }(); } totalBorrow = IVToken(VTokenB).borrowBalanceCurrent(address(this)); if (totalBorrow >= amountToken) { IVToken(VTokenB).repayBorrow(amountToken); } else { IVToken(VTokenB).repayBorrow(totalBorrow); } } } /** * @notice Repay borrow when in farms only erc20 */ function repayBorrowOnlyTokens( address swap, address tokenA, address tokenB, address VTokenA, address VTokenB, uint256 lpAmount ) private { (uint256 amountA, uint256 amountB) = IPancakeRouter01(swap).removeLiquidity( tokenA, tokenB, lpAmount, 0, 0, address(this), block.timestamp + 1 days ); { uint256 totalBorrow = IVToken(VTokenA).borrowBalanceCurrent(address(this)); if (totalBorrow >= amountA) { IVToken(VTokenA).repayBorrow(amountA); } else { IVToken(VTokenA).repayBorrow(totalBorrow); } totalBorrow = IVToken(VTokenB).borrowBalanceCurrent(address(this)); if (totalBorrow >= amountB) { IVToken(VTokenB).repayBorrow(amountB); } else { IVToken(VTokenB).repayBorrow(totalBorrow); } } } /** * @notice Withdraw lp token from farms and repay borrow */ function withdrawAndRepay(ReserveLiquidity memory reserve, uint256 lpAmount) private { IMasterChef(reserve.swapMaster).withdraw(reserve.poolID, lpAmount); if (reserve.tokenA == address(0) || reserve.tokenB == address(0)) { //if tokenA is BNB if (reserve.tokenA == address(0)) { repayBorrowBNBandToken( reserve.swap, reserve.tokenB, reserve.vTokenA, reserve.vTokenB, lpAmount ); } //if tokenB is BNB else { repayBorrowBNBandToken( reserve.swap, reserve.tokenA, reserve.vTokenB, reserve.vTokenA, lpAmount ); } } //if token A and B is not BNB else { repayBorrowOnlyTokens( reserve.swap, reserve.tokenA, reserve.tokenB, reserve.vTokenA, reserve.vTokenB, lpAmount ); } } /*** Prive View Function ***/ /** * @notice Convert Lp Token To Token */ function getPriceFromLpToToken( address lpToken, uint256 value, address token, address swap, address[] memory path ) private view returns (uint256) { //make price returned not affected by slippage rate uint256 totalSupply = IERC20(lpToken).totalSupply(); address token0 = IPancakePair(lpToken).token0(); uint256 totalTokenAmount = IERC20(token0).balanceOf(lpToken) * (2); uint256 amountIn = (value * totalTokenAmount) / (totalSupply); if (amountIn == 0 || token0 == token) { return amountIn; } uint256[] memory price = IPancakeRouter01(swap).getAmountsOut(amountIn, path); return price[price.length - 1]; } /** * @notice Convert Token To Lp Token */ function getPriceFromTokenToLp( address lpToken, uint256 value, address token, address swap, address[] memory path ) private view returns (uint256) { //make price returned not affected by slippage rate uint256 totalSupply = IERC20(lpToken).totalSupply(); address token0 = IPancakePair(lpToken).token0(); uint256 totalTokenAmount = IERC20(token0).balanceOf(lpToken); if (token0 == token) { return (value * (totalSupply)) / (totalTokenAmount) / 2; } uint256[] memory price = IPancakeRouter01(swap).getAmountsOut((1 gwei), path); return (value * (totalSupply)) / ((price[price.length - 1] * 2 * totalTokenAmount) / (1 gwei)); } /** * @notice FindPath for swap router */ function findPath(uint256 id, address token) private view returns (address[] memory path) { ReserveLiquidity memory reserve = reserves[id]; uint256 length = reserve.path.length; for (uint256 i = 0; i < length; i++) { if (reserve.path[i][reserve.path[i].length - 1] == token) { return reserve.path[i]; } } } }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 11 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the security assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: strategies/low_risk/contracts/libs/Aggregator.sol strategies/low_risk /contracts/libs/ERC20ForTestStorage.sol strategies/low_risk/contracts/libs/Migrations.sol strategies/low_risk/contracts/Logic.sol strategies/low_risk/contracts/Storage.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided functional requirements and technical requirements. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 7 out of 10. Code duplications. Not following solidity code style guidelines. Gas over -usage. Architecture quality The architecture quality score is 8 out of 10. Logic is split into modules. Contracts are self -descriptive. No thinking about gas efficiency. Room for improvements in code structuring. Security score As a result of the audit, security engineers found no issues . The security score is 10 out of 10. All found issues are displayed in the “Issues overview” section. Summary According to the assessment, the Cus tomer's smart contract has the following score: 9.5 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High No high severity issues were found. Medium 1. Test failed One of the two tests is failing. That could be either an issue in the test or an error in the contract logic implementation. Scope: strategies Recommendation : Ensure that the tests are successful and cover all the code branches. Status: 6 of 73 tests are failing (Revised Commit: 9378f79) Low 1. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 2. Excessive state access It is not recommended to read the state at each code line. It would be much more gas effective to read the state value into the local memory variable and use it for reading. Contract : StorageV0.sol Recommendation : Read the state variable to a local memory instead of multiple reading . Status: Fixed (Revised Commit: 9ca0cf0) 3. Not emitting events StorageV0 and Logic are not emitting events on state changes. There should be events to allow the community to track the current state off-chain. Contract: StorageV0.sol, Logic.sol Functions: setBLID, addToken, setLogic, setStorage, setAdmin www.hacken.io Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9ca0cf0) 4. Implicit variables visibility State variables that do not have specified visibility are declared internal implicitly. That could not be obvious. Contract: StorageV0.sol Variables : earnBLID, countEarns, countTokens, tokens, tokenBalance, oracles, tokensAdd, deposits, tokenDeposited, to kenTime, reserveBLID, logicContract, BLID Recommendation : Always declare visibility explicitly. Status: Fixed (Revised Commit: 9378f79) 5. Reading state variable’s `length` in the loop Reading `length` attribute in the loop may cost excess gas fees. Contract: Logic.sol Function : returnToken Recommendation : Save `length` attribute value into a local memory variable. Status: Fixed (Revised Commit: 9378f79) 6. Reading state variable in the loop Reading `countTokens` state variable in the loop would cost excess gas fees. Contract: StorageV0.sol Function : addEarn, _upBalance, _upBalanceByItarate, balanceEarnBLID, balanceOf, getTotalDeposit Recommendation : Save `countTokens` value into a local memor y variable. Status: Fixed (Revised Commit: 9ca0cf0) 7. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: Logic.sol, StorageV0.sol Functions : Logic.getReservesCount, Logic.getReserve, StorageV0.initialize, StorageV0._upBalance, StorageV0._upBalanceByItarate, StorageV0.balanceOf, StorageV0.getBLIDReserve, StorageV0.getTotalDeposit, StorageV0.getTokenBalance, StorageV0.getTokenDeposit, StorageV0._isUsedToken, StorageV0. getCountEarns www.hacken.io Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9ca0cf0) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no statements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements. While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hac ks. Thus, the audit can not guarantee the explicit security of the audited smart contracts.
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 external call in Storage.sol:L51 2.b Fix (one line with code reference): Add require statement to check the return value of the external call 3.a Problem (one line with code reference): Unchecked math in Storage.sol:L51 3.b Fix (one line with code reference): Add require statement to check the return value of the math operation 4.a Problem (one line with code reference): Unsafe type inference in Storage.sol:L51 4.b Fix (one line with code reference): Add explicit type conversion 5.a Problem (one line with code reference): Implicit visibility level in Storage.sol:L51 5.b Fix (one line with code reference): Add explicit visibility level Moderate 6.a Problem (one line with code reference): Code duplications in Storage.sol 6.b Fix (one line with code reference): Refactor the code to remove duplications Issues Count of Minor/Moderate/Major/Critical - Critical: 0 - High: 0 - Moderate: 1 - Minor: 3 Minor Issues 2.a Test failed (Scope: strategies, Revised Commit: 9378f79) 2.b Ensure that the tests are successful and cover all the code branches. Moderate 3.a Floating solidity version (Contracts: all, Revised Commit: 9378f79) 3.b Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Major 4.a Excessive state access (Contract: StorageV0.sol, Revised Commit: 9ca0cf0) 4.b Read the state variable to a local memory instead of multiple reading. Critical No critical severity issues were found. Observations - Logic is split into modules. - Contracts are self-descriptive. - No thinking about gas efficiency. - Room for improvements in code structuring. Conclusion According to the assessment, the Customer's smart contract has the following score: 9.5. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
pragma solidity 0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract TreasuryVester is Ownable { using SafeMath for uint256; address public immutable blid; address public recipient; uint256 public immutable vestingAmount; uint256 public immutable vestingBegin; uint256 public immutable vestingCliff; uint256 public immutable vestingEnd; uint256 public lastUpdate; constructor( address blid_, address recipient_, uint256 vestingAmount_, uint256 vestingBegin_, uint256 vestingCliff_, uint256 vestingEnd_ ) { require(vestingBegin_ >= block.timestamp, "TreasuryVester::constructor: vesting begin too early"); require(vestingCliff_ >= vestingBegin_, "TreasuryVester::constructor: cliff is too early"); require(vestingEnd_ > vestingCliff_, "TreasuryVester::constructor: end is too early"); blid = blid_; recipient = recipient_; vestingAmount = vestingAmount_; vestingBegin = vestingBegin_; vestingCliff = vestingCliff_; vestingEnd = vestingEnd_; lastUpdate = vestingBegin_; } function setRecipient(address recipient_) public { require(msg.sender == owner(), "TreasuryVester::setRecipient: unauthorized"); recipient = recipient_; } function claim() public { require(block.timestamp >= vestingCliff, "TreasuryVester::claim: not time yet"); uint256 amount; if (block.timestamp >= vestingEnd) { amount = IBlid(blid).balanceOf(address(this)); } else { amount = vestingAmount * 10**18; amount = amount.mul(block.timestamp - lastUpdate).div(vestingEnd - vestingBegin); lastUpdate = block.timestamp; } IBlid(blid).transfer(recipient, amount); } } interface IBlid { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint256 rawAmount) external returns (bool); }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 11 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the security assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: strategies/low_risk/contracts/libs/Aggregator.sol strategies/low_risk /contracts/libs/ERC20ForTestStorage.sol strategies/low_risk/contracts/libs/Migrations.sol strategies/low_risk/contracts/Logic.sol strategies/low_risk/contracts/Storage.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided functional requirements and technical requirements. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 7 out of 10. Code duplications. Not following solidity code style guidelines. Gas over -usage. Architecture quality The architecture quality score is 8 out of 10. Logic is split into modules. Contracts are self -descriptive. No thinking about gas efficiency. Room for improvements in code structuring. Security score As a result of the audit, security engineers found no issues . The security score is 10 out of 10. All found issues are displayed in the “Issues overview” section. Summary According to the assessment, the Cus tomer's smart contract has the following score: 9.5 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High No high severity issues were found. Medium 1. Test failed One of the two tests is failing. That could be either an issue in the test or an error in the contract logic implementation. Scope: strategies Recommendation : Ensure that the tests are successful and cover all the code branches. Status: 6 of 73 tests are failing (Revised Commit: 9378f79) Low 1. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 2. Excessive state access It is not recommended to read the state at each code line. It would be much more gas effective to read the state value into the local memory variable and use it for reading. Contract : StorageV0.sol Recommendation : Read the state variable to a local memory instead of multiple reading . Status: Fixed (Revised Commit: 9ca0cf0) 3. Not emitting events StorageV0 and Logic are not emitting events on state changes. There should be events to allow the community to track the current state off-chain. Contract: StorageV0.sol, Logic.sol Functions: setBLID, addToken, setLogic, setStorage, setAdmin www.hacken.io Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9ca0cf0) 4. Implicit variables visibility State variables that do not have specified visibility are declared internal implicitly. That could not be obvious. Contract: StorageV0.sol Variables : earnBLID, countEarns, countTokens, tokens, tokenBalance, oracles, tokensAdd, deposits, tokenDeposited, to kenTime, reserveBLID, logicContract, BLID Recommendation : Always declare visibility explicitly. Status: Fixed (Revised Commit: 9378f79) 5. Reading state variable’s `length` in the loop Reading `length` attribute in the loop may cost excess gas fees. Contract: Logic.sol Function : returnToken Recommendation : Save `length` attribute value into a local memory variable. Status: Fixed (Revised Commit: 9378f79) 6. Reading state variable in the loop Reading `countTokens` state variable in the loop would cost excess gas fees. Contract: StorageV0.sol Function : addEarn, _upBalance, _upBalanceByItarate, balanceEarnBLID, balanceOf, getTotalDeposit Recommendation : Save `countTokens` value into a local memor y variable. Status: Fixed (Revised Commit: 9ca0cf0) 7. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: Logic.sol, StorageV0.sol Functions : Logic.getReservesCount, Logic.getReserve, StorageV0.initialize, StorageV0._upBalance, StorageV0._upBalanceByItarate, StorageV0.balanceOf, StorageV0.getBLIDReserve, StorageV0.getTotalDeposit, StorageV0.getTokenBalance, StorageV0.getTokenDeposit, StorageV0._isUsedToken, StorageV0. getCountEarns www.hacken.io Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9ca0cf0) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no statements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements. While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hac ks. Thus, the audit can not guarantee the explicit security of the audited smart contracts.
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 external call in Storage.sol:L51 2.b Fix (one line with code reference): Add require statement to check the return value of the external call 3.a Problem (one line with code reference): Unchecked math in Storage.sol:L51 3.b Fix (one line with code reference): Add require statement to check the return value of the math operation 4.a Problem (one line with code reference): Unsafe type inference in Storage.sol:L51 4.b Fix (one line with code reference): Add explicit type conversion 5.a Problem (one line with code reference): Implicit visibility level in Storage.sol:L51 5.b Fix (one line with code reference): Add explicit visibility level Moderate 6.a Problem (one line with code reference): Code duplications in Storage.sol 6.b Fix (one line with code reference): Refactor the code to remove duplications Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Test failed 2.b Fix: Ensure that the tests are successful and cover all the code branches. Moderate 3.a Problem: Floating solidity version 3.b Fix: Specify the exact solidity version. Major None Critical None Observations - The architecture quality score is 8 out of 10. - The security score is 10 out of 10. - All found issues have been fixed. Conclusion The Customer's smart contract has a score of 9.5 out of 10. No critical or high severity issues were found. All minor and moderate issues have been fixed. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
pragma solidity 0.8.13; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract TreasuryVester is Ownable { using SafeMath for uint256; address public immutable blid; address public recipient; uint256 public immutable vestingAmount; uint256 public immutable vestingBegin; uint256 public immutable vestingCliff; uint256 public immutable vestingEnd; uint256 public lastUpdate; constructor( address blid_, address recipient_, uint256 vestingAmount_, uint256 vestingBegin_, uint256 vestingCliff_, uint256 vestingEnd_ ) { require(vestingBegin_ >= block.timestamp, "TreasuryVester::constructor: vesting begin too early"); require(vestingCliff_ >= vestingBegin_, "TreasuryVester::constructor: cliff is too early"); require(vestingEnd_ > vestingCliff_, "TreasuryVester::constructor: end is too early"); blid = blid_; recipient = recipient_; vestingAmount = vestingAmount_; vestingBegin = vestingBegin_; vestingCliff = vestingCliff_; vestingEnd = vestingEnd_; lastUpdate = vestingBegin_; } function setRecipient(address recipient_) public { require(msg.sender == owner(), "TreasuryVester::setRecipient: unauthorized"); recipient = recipient_; } function claim() public { require(block.timestamp >= vestingCliff, "TreasuryVester::claim: not time yet"); uint256 amount; if (block.timestamp >= vestingEnd) { amount = IBlid(blid).balanceOf(address(this)); } else { amount = vestingAmount * 10**18; amount = amount.mul(block.timestamp - lastUpdate).div(vestingEnd - vestingBegin); lastUpdate = block.timestamp; } IBlid(blid).transfer(recipient, amount); } } interface IBlid { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint256 rawAmount) external returns (bool); }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 10 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the securit y assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: farming/contracts/libs/PancakeVoteProxy.sol farming/contracts/libs/Migrations.sol farming/contracts/MasterChef.sol farming/contracts/Timelock.sol farming/contracts/libs/Mo ckBEP20.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided some functional requirements and no technical requirements. The contracts are forks of well -known ones. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 9 out of 10. No NatSpecs. Architecture quality The architecture quality score is 10 out of 10. Security score As a result of the audit, security engineers found 1 low severity issue. The security score is 10 out of 10. All found issues are displayed in the “Issues overview” sectio n. Summary According to the assessment, the Customer's smart contract has the following score: 9.9 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High 1. Possible rewards lost or receiving more Changing allocPoint in the MasterBlid.set method while _withUpdate flag is set to false may lead to rewards lost or receiving rewards more than deserved. Contract: MasterChef.sol Function: set Recommendation : Call updatePool(_pid) in the case if _withUpdate flag is false and you do not want to update all pools. Status: Fixed. (Revised Commit: 9ca0cf0) Medium 1. Privileged ownership The owner of the MasterBlid contract has permission to `updateMultiplier`, add new pools, change pool’s allocation points, and set a migrator contract (which will move all LPs from the pool to itself) without community consensus. Contract: MasterChef.sol Recommendation : Consider using one of the following methodologies: - Transfer ownership to a Time -lock contract with reasonable latency (i.e. 24h) so the community may react to changes; - Transfer ownership to a multi -signature wallet to prevent a single point of failure; - Transfer ownership to DAO so the community could decide whether the privileged operations should be executed by voting. Status: Fixed; Moved ownership to a Timelock (Revised Commit: 9ca0cf0) Low 1. Excess writing operation When _allocPoint is not changed for the pool, there is still an assignment for a new value, which consumes gas doing nothing. Contract: MasterChef.sol Function: set Recommendation :Move “poolInfo[_pid].allocPoint = _allocPoint” assignment inside the if block. www.hacken.io Status: Fixed (Revised Commit: 9378f79) 2. Missing Emit Events Functions that change critical values should emit events for better off-chain tracking. Contract: MasterChef.sol Function: setMigrator, updateMultiplier, setBlidPerBlock Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9378f79) 3. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 4. Balance upda ted after transfer It is recommended to update the balance state before doing any token transfer. Contract : MasterChef.sol Functions : emergencyWithdraw, migrate Recommendation : Update the balance and do transfer after that . Status: Reported (Revised Commit: 9378f79) 5. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: MasterChef.sol Functions : updateMultiplier, add, set, setBlidPerBlock, setM igrator, setExpenseAddress, migrate, deposit, withdraw, enterStaking, leaveStaking Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9378f79) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no sta tements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements . While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hacks. Thus, the audit can not guarantee the explicit security o f the audited smart contracts.
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 external call in Storage.sol:L51 2.b Fix (one line with code reference): Add require statement to check the return value of the external call 3.a Problem (one line with code reference): Unchecked math in Storage.sol:L51 3.b Fix (one line with code reference): Add require statement to check the return value of the math operation 4.a Problem (one line with code reference): Unsafe type inference in Storage.sol:L51 4.b Fix (one line with code reference): Add explicit type conversion 5.a Problem (one line with code reference): Implicit visibility level in Storage.sol:L51 5.b Fix (one line with code reference): Add explicit visibility level Moderate 6.a Problem (one line with code reference): Code duplications in Storage.sol 6.b Fix (one line with code reference): Refactor the code to remove duplications Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Test failed 2.b Fix: Ensure that the tests are successful and cover all the code branches. Moderate 3.a Problem: Floating solidity version 3.b Fix: Specify the exact solidity version. Major None Critical None Observations - The architecture quality score is 8 out of 10. - The security score is 10 out of 10. - All found issues have been fixed. Conclusion The Customer's smart contract has a score of 9.5 out of 10. No critical or high severity issues were found. All minor and moderate issues have been fixed. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./TokenVestingGroup.sol"; interface AggregatorV3Interface { function decimals() external view returns (uint8); function latestAnswer() external view returns (int256 answer); } interface IBurnable { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } contract PrivateSale is Ownable { using SafeERC20 for IERC20; //*** Structs ***// struct Round { mapping(address => bool) whiteList; mapping(address => uint256) sums; mapping(address => address) depositToken; mapping(address => uint256) tokenReserve; uint256 totalReserve; uint256 tokensSold; uint256 tokenRate; uint256 maxMoney; uint256 sumTokens; uint256 minimumSaleAmount; uint256 maximumSaleAmount; uint256 startTimestamp; uint256 endTimestamp; uint256 duration; uint256 durationCount; uint256 lockup; TokenVestingGroup vestingContract; uint8 percentOnInvestorWallet; uint8 typeRound; bool finished; bool open; bool burnable; } struct InputNewRound { uint256 _tokenRate; uint256 _maxMoney; uint256 _sumTokens; uint256 _startTimestamp; uint256 _endTimestamp; uint256 _minimumSaleAmount; uint256 _maximumSaleAmount; uint256 _duration; uint256 _durationCount; uint256 _lockup; uint8 _typeRound; uint8 _percentOnInvestorWallet; bool _burnable; bool _open; } //*** Variable ***// mapping(uint256 => Round) rounds; address investorWallet; uint256 countRound; uint256 countTokens; mapping(uint256 => address) tokens; mapping(address => address) oracles; mapping(address => bool) tokensAdd; address BLID; address expenseAddress; //*** Modifiers ***// modifier isUsedToken(address _token) { require(tokensAdd[_token], "Token is not used "); _; } modifier finishedRound() { require(countRound == 0 || rounds[countRound - 1].finished, "Last round has not been finished"); _; } modifier unfinishedRound() { require(countRound != 0 && !rounds[countRound - 1].finished, "Last round has been finished"); _; } modifier existRound(uint256 round) { require(round < countRound, "Number round more than Rounds count"); _; } /*** User function ***/ /** * @notice User deposit amount of token for * @param amount Amount of token * @param token Address of token */ function deposit(uint256 amount, address token) external isUsedToken(token) unfinishedRound { require(rounds[countRound - 1].open || rounds[countRound - 1].whiteList[msg.sender], "No access"); require(!isParticipatedInTheRound(countRound - 1), "You have already made a deposit"); require(rounds[countRound - 1].startTimestamp < block.timestamp, "Round dont start"); require( rounds[countRound - 1].minimumSaleAmount <= amount * 10**(18 - AggregatorV3Interface(token).decimals()), "Minimum sale amount more than your amount" ); require( rounds[countRound - 1].maximumSaleAmount == 0 || rounds[countRound - 1].maximumSaleAmount >= amount * 10**(18 - AggregatorV3Interface(token).decimals()), " Your amount more than maximum sale amount" ); require( rounds[countRound - 1].endTimestamp > block.timestamp || rounds[countRound - 1].endTimestamp == 0, "Round is ended, round time expired" ); require( rounds[countRound - 1].tokenRate == 0 || rounds[countRound - 1].sumTokens == 0 || rounds[countRound - 1].sumTokens >= ((rounds[countRound - 1].totalReserve + amount * 10**(18 - AggregatorV3Interface(token).decimals())) * (1 ether)) / rounds[countRound - 1].tokenRate, "Round is ended, all tokens sold" ); require( rounds[countRound - 1].maxMoney == 0 || rounds[countRound - 1].maxMoney >= (rounds[countRound - 1].totalReserve + amount * 10**(18 - AggregatorV3Interface(token).decimals())), "The round is over, the maximum required value has been reached, or your amount is greater than specified in the conditions of the round" ); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); rounds[countRound - 1].tokenReserve[token] += amount * 10**(18 - AggregatorV3Interface(token).decimals()); rounds[countRound - 1].sums[msg.sender] += amount * 10**(18 - AggregatorV3Interface(token).decimals()); rounds[countRound - 1].depositToken[msg.sender] = token; rounds[countRound - 1].totalReserve += amount * 10**(18 - AggregatorV3Interface(token).decimals()); rounds[countRound - 1].vestingContract.deposit( msg.sender, token, amount * 10**(18 - AggregatorV3Interface(token).decimals()) ); } /** * @notice User return deposit of round * @param round number of round */ function returnDeposit(uint256 round) external { require(round < countRound, "Number round more than Rounds count"); require(rounds[round].sums[msg.sender] > 0, "You don't have deposit or you return your deposit"); require( !rounds[round].finished || rounds[round].typeRound == 0, "round has been finished successfully" ); IERC20(rounds[round].depositToken[msg.sender]).safeTransfer( msg.sender, rounds[round].sums[msg.sender] / 10**(18 - AggregatorV3Interface(rounds[round].depositToken[msg.sender]).decimals()) ); rounds[round].vestingContract.returnDeposit(msg.sender); rounds[round].totalReserve -= rounds[round].sums[msg.sender]; rounds[round].tokenReserve[rounds[round].depositToken[msg.sender]] -= rounds[round].sums[msg.sender]; rounds[round].sums[msg.sender] = 0; rounds[round].depositToken[msg.sender] = address(0); } /** * @notice Add token and token's oracle * @param _token Address of Token * @param _oracles Address of token's oracle(https://docs.chain.link/docs/binance-smart-chain-addresses/ */ function addToken(address _token, address _oracles) external onlyOwner { require(_token != address(0) && _oracles != address(0)); require(!tokensAdd[_token], "token was added"); oracles[_token] = _oracles; tokens[countTokens++] = _token; tokensAdd[_token] = true; } /** * @notice Set Investor Wallet * @param _investorWallet address of InvestorWallet */ function setInvestorWallet(address _investorWallet) external onlyOwner finishedRound { investorWallet = _investorWallet; } /** * @notice Set Expense Wallet * @param _expenseAddress address of Expense Address */ function setExpenseAddress(address _expenseAddress) external onlyOwner finishedRound { expenseAddress = _expenseAddress; } /** * @notice Set Expense Wallet and Investor Wallet * @param _investorWallet address of InvestorWallet * @param _expenseAddress address of Expense Address */ function setExpenseAddressAndInvestorWallet(address _expenseAddress, address _investorWallet) external onlyOwner finishedRound { expenseAddress = _expenseAddress; investorWallet = _investorWallet; } /** * @notice Set blid in contract * @param _BLID address of BLID */ function setBLID(address _BLID) external onlyOwner { require(BLID == address(0), "BLID was set"); BLID = _BLID; } /** * @notice Creat new round with input parameters * @param input Data about of new round */ function newRound(InputNewRound memory input) external onlyOwner finishedRound { require(BLID != address(0), "BLID is not set"); require(expenseAddress != address(0), "Require set expense address "); require( investorWallet != address(0) || input._percentOnInvestorWallet == 0, "Require set Logic contract" ); require( input._endTimestamp == 0 || input._endTimestamp > block.timestamp, "_endTimestamp must be unset or more than now timestamp" ); if (input._typeRound == 1) { require(input._tokenRate > 0, "Need set _tokenRate and _tokenRate must be more than 0"); require( IERC20(BLID).balanceOf(address(this)) >= input._sumTokens, "_sumTokens more than this smart contract have BLID" ); require(input._sumTokens > 0, "Need set _sumTokens "); rounds[countRound].tokenRate = input._tokenRate; rounds[countRound].maxMoney = input._maxMoney; rounds[countRound].startTimestamp = input._startTimestamp; rounds[countRound].sumTokens = input._sumTokens; rounds[countRound].endTimestamp = input._endTimestamp; rounds[countRound].duration = input._duration; rounds[countRound].durationCount = input._durationCount; rounds[countRound].minimumSaleAmount = input._minimumSaleAmount; rounds[countRound].maximumSaleAmount = input._maximumSaleAmount; rounds[countRound].lockup = input._lockup; rounds[countRound].percentOnInvestorWallet = input._percentOnInvestorWallet; rounds[countRound].burnable = input._burnable; rounds[countRound].open = input._open; rounds[countRound].typeRound = input._typeRound; address[] memory inputTokens = new address[](countTokens); for (uint256 i = 0; i < countTokens; i++) { inputTokens[i] = tokens[i]; } rounds[countRound].vestingContract = new TokenVestingGroup( BLID, input._duration, input._durationCount, inputTokens ); countRound++; } else if (input._typeRound == 2) { require(input._sumTokens > 0, "Need set _sumTokens"); require(input._tokenRate == 0, "Need unset _tokenRate (_tokenRate==0)"); require(!input._burnable, "Need not burnable round"); require( IERC20(BLID).balanceOf(address(this)) >= input._sumTokens, "_sumTokens more than this smart contract have BLID" ); rounds[countRound].tokenRate = input._tokenRate; rounds[countRound].maxMoney = input._maxMoney; rounds[countRound].startTimestamp = input._startTimestamp; rounds[countRound].endTimestamp = input._endTimestamp; rounds[countRound].sumTokens = input._sumTokens; rounds[countRound].duration = input._duration; rounds[countRound].minimumSaleAmount = input._minimumSaleAmount; rounds[countRound].maximumSaleAmount = input._maximumSaleAmount; rounds[countRound].durationCount = input._durationCount; rounds[countRound].lockup = input._lockup; rounds[countRound].percentOnInvestorWallet = input._percentOnInvestorWallet; rounds[countRound].burnable = input._burnable; rounds[countRound].open = input._open; rounds[countRound].typeRound = input._typeRound; address[] memory inputTokens = new address[](countTokens); for (uint256 i = 0; i < countTokens; i++) { inputTokens[i] = (tokens[i]); } rounds[countRound].vestingContract = new TokenVestingGroup( BLID, input._duration, input._durationCount, inputTokens ); countRound++; } } /** * @notice Set rate of token for last round(only for round that typy is 1) * @param rate Rate token token/usd * 10**18 */ function setRateToken(uint256 rate) external onlyOwner unfinishedRound { require(rounds[countRound - 1].typeRound == 1, "This round auto generate rate"); rounds[countRound - 1].tokenRate = rate; } /** * @notice Set timestamp when end round * @param _endTimestamp timesetamp when round is ended */ function setEndTimestamp(uint256 _endTimestamp) external onlyOwner unfinishedRound { rounds[countRound - 1].endTimestamp = _endTimestamp; } /** * @notice Set Sum Tokens * @param _sumTokens Amount of selling BLID. Necessarily with the type of round 2 */ function setSumTokens(uint256 _sumTokens) external onlyOwner unfinishedRound { require( IERC20(BLID).balanceOf(address(this)) >= _sumTokens, "_sumTokens more than this smart contract have BLID" ); require(_sumTokens > rounds[countRound - 1].tokensSold, "Token sold more than _sumTokens"); rounds[countRound - 1].sumTokens = _sumTokens; } /** * @notice Set Start Timestamp * @param _startTimestamp Unix timestamp Start Round */ function setStartTimestamp(uint256 _startTimestamp) external onlyOwner unfinishedRound { require(block.timestamp < _startTimestamp, "Round has been started"); rounds[countRound - 1].startTimestamp = _startTimestamp; } /** * @notice Set Max Money * @param _maxMoney Amount USD when close round */ function setMaxMoney(uint256 _maxMoney) external onlyOwner unfinishedRound { require(rounds[countRound - 1].totalReserve < _maxMoney, "Now total reserve more than _maxMoney"); rounds[countRound - 1].maxMoney = _maxMoney; } /** * @notice Add account in white list * @param account Address is added in white list */ function addWhiteList(address account) external onlyOwner unfinishedRound { rounds[countRound - 1].whiteList[account] = true; } /** * @notice Add accounts in white list * @param accounts Addresses are added in white list */ function addWhiteListByArray(address[] calldata accounts) external onlyOwner unfinishedRound { for (uint256 i = 0; i < accounts.length; i++) { rounds[countRound - 1].whiteList[accounts[i]] = true; } } /** * @notice Delete accounts in white list * @param account Address is deleted in white list */ function deleteWhiteList(address account) external onlyOwner unfinishedRound { rounds[countRound - 1].whiteList[account] = false; } /** * @notice Delete accounts in white list * @param accounts Addresses are deleted in white list */ function deleteWhiteListByArray(address[] calldata accounts) external onlyOwner unfinishedRound { for (uint256 i = 0; i < accounts.length; i++) { rounds[countRound - 1].whiteList[accounts[i]] = false; } } /** * @notice Finish round, send rate to VestingGroup contracts */ function finishRound() external onlyOwner { require(countRound != 0 && !rounds[countRound - 1].finished, "Last round has been finished"); uint256[] memory rates = new uint256[](countTokens); uint256 sumUSD = 0; for (uint256 i = 0; i < countTokens; i++) { if (rounds[countRound - 1].tokenReserve[tokens[i]] == 0) continue; IERC20(tokens[i]).safeTransfer( expenseAddress, rounds[countRound - 1].tokenReserve[tokens[i]] / 10**(18 - AggregatorV3Interface(tokens[i]).decimals()) - ((rounds[countRound - 1].tokenReserve[tokens[i]] / 10**(18 - AggregatorV3Interface(tokens[i]).decimals())) * (rounds[countRound - 1].percentOnInvestorWallet)) / 100 ); IERC20(tokens[i]).safeTransfer( investorWallet, ((rounds[countRound - 1].tokenReserve[tokens[i]] / 10**(18 - AggregatorV3Interface(tokens[i]).decimals())) * (rounds[countRound - 1].percentOnInvestorWallet)) / 100 ); rates[i] = (uint256(AggregatorV3Interface(oracles[tokens[i]]).latestAnswer()) * 10**(18 - AggregatorV3Interface(oracles[tokens[i]]).decimals())); sumUSD += (rounds[countRound - 1].tokenReserve[tokens[i]] * rates[i]) / (1 ether); if (rounds[countRound - 1].typeRound == 1) rates[i] = (rates[i] * (1 ether)) / rounds[countRound - 1].tokenRate; if (rounds[countRound - 1].typeRound == 2) rates[i] = (rounds[countRound - 1].sumTokens * rates[i]) / sumUSD; } if (sumUSD != 0) { rounds[countRound - 1].vestingContract.finishRound( block.timestamp + rounds[countRound - 1].lockup, rates ); if (rounds[countRound - 1].typeRound == 1) IERC20(BLID).safeTransfer( address(rounds[countRound - 1].vestingContract), (sumUSD * (1 ether)) / rounds[countRound - 1].tokenRate ); } if (rounds[countRound - 1].typeRound == 2) IERC20(BLID).safeTransfer( address(rounds[countRound - 1].vestingContract), rounds[countRound - 1].sumTokens ); if ( rounds[countRound - 1].burnable && rounds[countRound - 1].sumTokens - (sumUSD * (1 ether)) / rounds[countRound - 1].tokenRate != 0 ) { IBurnable(BLID).burn( rounds[countRound - 1].sumTokens - (sumUSD * (1 ether)) / rounds[countRound - 1].tokenRate ); } rounds[countRound - 1].finished = true; } /** * @notice Cancel round */ function cancelRound() external onlyOwner { require(countRound != 0 && !rounds[countRound - 1].finished, "Last round has been finished"); rounds[countRound - 1].finished = true; rounds[countRound - 1].typeRound = 0; } /** * @param id Number of round * @return InputNewRound - information about round */ function getRoundStateInfromation(uint256 id) public view returns (InputNewRound memory) { InputNewRound memory out = InputNewRound( rounds[id].tokenRate, rounds[id].maxMoney, rounds[id].sumTokens, rounds[id].startTimestamp, rounds[id].endTimestamp, rounds[id].minimumSaleAmount, rounds[id].maximumSaleAmount, rounds[id].duration, rounds[id].durationCount, rounds[id].lockup, rounds[id].typeRound, rounds[id].percentOnInvestorWallet, rounds[id].burnable, rounds[id].open ); return out; } /** * @param id Number of round * @return Locked Tokens */ function getLockedTokens(uint256 id) public view returns (uint256) { if (rounds[id].tokenRate == 0) return 0; return ((rounds[id].totalReserve * (1 ether)) / rounds[id].tokenRate); } /** * @param id Number of round * @return Returns (all deposited money, sold tokens, open or close round) */ function getRoundDynamicInfromation(uint256 id) public view returns ( uint256, uint256, bool ) { if (rounds[id].typeRound == 1) { return (rounds[id].totalReserve, rounds[id].totalReserve / rounds[id].tokenRate, rounds[id].open); } else { return (rounds[id].totalReserve, rounds[id].sumTokens, rounds[id].open); } } /** * @return True if `account` is in white list */ function isInWhiteList(address account) public view returns (bool) { return rounds[countRound - 1].whiteList[account]; } /** * @return Count round */ function getCountRound() public view returns (uint256) { return countRound; } /** * @param id Number of round * @return Address Vesting contract */ function getVestingAddress(uint256 id) public view existRound(id) returns (address) { return address(rounds[id].vestingContract); } /** * @param id Number of round * @param account Address of depositor * @return Investor Deposited Tokens */ function getInvestorDepositedTokens(uint256 id, address account) public view existRound(id) returns (uint256) { return (rounds[id].sums[account]); } /** * @return Investor Deposited Tokens */ function getInvestorWallet() public view returns (address) { return investorWallet; } /** * @param id Number of round * @return True if `id` round is cancelled */ function isCancelled(uint256 id) public view existRound(id) returns (bool) { return rounds[id].typeRound == 0; } /** * @param id Number of round * @return True if `msg.sender` is Participated In The Round */ function isParticipatedInTheRound(uint256 id) public view existRound(id) returns (bool) { return rounds[id].depositToken[msg.sender] != address(0); } /** * @param id Number of round * @return Deposited token addres of `msg.sender` */ function getUserToken(uint256 id) public view existRound(id) returns (address) { return rounds[id].depositToken[msg.sender]; } /** * @param id Number of round * @return True if `id` round is finished */ function isFinished(uint256 id) public view returns (bool) { return rounds[id].finished; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TokenVestingGroup is Ownable { using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); mapping(address => uint256) _sumUser; mapping(address => uint256) _rateToken; mapping(address => uint256) _released; mapping(address => address) _userToken; address[] _tokens; IERC20 public _token; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _durationCount; uint256 private _startTimestamp; uint256 private _duration; uint256 private _endTimestamp; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary. By then all * of the balance will have vested. */ constructor( address tokenValue, uint256 durationValue, uint256 durationCountValue, address[] memory tokensValue ) { _token = IERC20(tokenValue); _duration = durationValue; _durationCount = durationCountValue; _tokens = tokensValue; } /** * @notice Set amount of token for user deposited token */ function deposit( address user, address token, uint256 amount ) external onlyOwner { _userToken[user] = token; _sumUser[user] = amount; } /** * @notice Transfers vested tokens to beneficiary. */ function finishRound(uint256 startTimestampValue, uint256[] memory tokenRate) external onlyOwner { require(_startTimestamp == 0, "Vesting has been started"); _startTimestamp = startTimestampValue; for (uint256 i = 0; i < tokenRate.length; i++) { _rateToken[_tokens[i]] = tokenRate[i]; } } /** * @notice Transfers vested tokens to beneficiary. */ function claim() external { uint256 unreleased = releasableAmount(); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[msg.sender] = _released[msg.sender] + (unreleased); _token.safeTransfer(msg.sender, unreleased); emit TokensReleased(address(_token), unreleased); } /** * @notice Set 0 for user deposited token */ function returnDeposit(address user) external onlyOwner { require(_startTimestamp == 0, "Vesting has been started"); _userToken[user] = address(0); _sumUser[user] = 0; } /** * @return the end time of the token vesting. */ function end() public view returns (uint256) { return _startTimestamp + _duration * _durationCount; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _startTimestamp; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return the count of duration of the token vesting. */ function durationCount() public view returns (uint256) { return _durationCount; } /** * @return the amount of the token released. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns (uint256) { return _vestedAmount(msg.sender) - (_released[msg.sender]); } /** * @dev Calculates the user dollar deposited. */ function getUserShare(address account) public view returns (uint256) { return (_sumUser[account] * _rateToken[_userToken[account]]) / (1 ether); } /** * @dev Calculates the amount that has already vested. */ function _vestedAmount(address account) public view returns (uint256) { require(_startTimestamp != 0, "Vesting has not been started"); uint256 totalBalance = (_sumUser[account] * _rateToken[_userToken[account]]) / (1 ether); if (block.timestamp < _startTimestamp) { return 0; } else if (block.timestamp >= _startTimestamp + _duration * _durationCount) { return totalBalance; } else { return (totalBalance * ((block.timestamp - _startTimestamp) / (_duration))) / (_durationCount); } } }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 11 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the security assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: strategies/low_risk/contracts/libs/Aggregator.sol strategies/low_risk /contracts/libs/ERC20ForTestStorage.sol strategies/low_risk/contracts/libs/Migrations.sol strategies/low_risk/contracts/Logic.sol strategies/low_risk/contracts/Storage.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided functional requirements and technical requirements. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 7 out of 10. Code duplications. Not following solidity code style guidelines. Gas over -usage. Architecture quality The architecture quality score is 8 out of 10. Logic is split into modules. Contracts are self -descriptive. No thinking about gas efficiency. Room for improvements in code structuring. Security score As a result of the audit, security engineers found no issues . The security score is 10 out of 10. All found issues are displayed in the “Issues overview” section. Summary According to the assessment, the Cus tomer's smart contract has the following score: 9.5 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High No high severity issues were found. Medium 1. Test failed One of the two tests is failing. That could be either an issue in the test or an error in the contract logic implementation. Scope: strategies Recommendation : Ensure that the tests are successful and cover all the code branches. Status: 6 of 73 tests are failing (Revised Commit: 9378f79) Low 1. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 2. Excessive state access It is not recommended to read the state at each code line. It would be much more gas effective to read the state value into the local memory variable and use it for reading. Contract : StorageV0.sol Recommendation : Read the state variable to a local memory instead of multiple reading . Status: Fixed (Revised Commit: 9ca0cf0) 3. Not emitting events StorageV0 and Logic are not emitting events on state changes. There should be events to allow the community to track the current state off-chain. Contract: StorageV0.sol, Logic.sol Functions: setBLID, addToken, setLogic, setStorage, setAdmin www.hacken.io Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9ca0cf0) 4. Implicit variables visibility State variables that do not have specified visibility are declared internal implicitly. That could not be obvious. Contract: StorageV0.sol Variables : earnBLID, countEarns, countTokens, tokens, tokenBalance, oracles, tokensAdd, deposits, tokenDeposited, to kenTime, reserveBLID, logicContract, BLID Recommendation : Always declare visibility explicitly. Status: Fixed (Revised Commit: 9378f79) 5. Reading state variable’s `length` in the loop Reading `length` attribute in the loop may cost excess gas fees. Contract: Logic.sol Function : returnToken Recommendation : Save `length` attribute value into a local memory variable. Status: Fixed (Revised Commit: 9378f79) 6. Reading state variable in the loop Reading `countTokens` state variable in the loop would cost excess gas fees. Contract: StorageV0.sol Function : addEarn, _upBalance, _upBalanceByItarate, balanceEarnBLID, balanceOf, getTotalDeposit Recommendation : Save `countTokens` value into a local memor y variable. Status: Fixed (Revised Commit: 9ca0cf0) 7. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: Logic.sol, StorageV0.sol Functions : Logic.getReservesCount, Logic.getReserve, StorageV0.initialize, StorageV0._upBalance, StorageV0._upBalanceByItarate, StorageV0.balanceOf, StorageV0.getBLIDReserve, StorageV0.getTotalDeposit, StorageV0.getTokenBalance, StorageV0.getTokenDeposit, StorageV0._isUsedToken, StorageV0. getCountEarns www.hacken.io Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9ca0cf0) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no statements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements. While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hac ks. Thus, the audit can not guarantee the explicit security of the audited smart contracts.
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 external call in Storage.sol:L51 2.b Fix (one line with code reference): Add require statement to check the return value of the external call. 3.a Problem (one line with code reference): Unchecked math in Storage.sol:L51 3.b Fix (one line with code reference): Add require statement to check the return value of the math operation. 4.a Problem (one line with code reference): Unsafe type inference in Storage.sol:L51 4.b Fix (one line with code reference): Add explicit type conversion to ensure the correct type is used. 5.a Problem (one line with code reference): Implicit visibility level in Storage.sol:L51 5.b Fix (one line with code reference): Add explicit visibility level to ensure the correct visibility is used. Moderate 6.a Problem (one line with code reference): Code duplications in Storage.sol 6.b Issues Count of Minor/Moderate/Major/Critical - Critical: 0 - High: 0 - Moderate: 1 - Minor: 3 Minor Issues 2.a Test failed (Scope: strategies, Revised Commit: 9378f79) 2.b Ensure that the tests are successful and cover all the code branches. Moderate 3.a Floating solidity version (Contracts: all, Revised Commit: 9378f79) 3.b Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Major 4.a Excessive state access (Contract: StorageV0.sol, Revised Commit: 9ca0cf0) 4.b Read the state variable to a local memory instead of multiple reading. Critical No critical severity issues were found. Observations - Logic is split into modules. - Contracts are self-descriptive. - No thinking about gas efficiency. - Room for improvements in code structuring. Conclusion According to the assessment, the Customer's smart contract has the following score: 9.5. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./TokenVestingGroup.sol"; interface AggregatorV3Interface { function decimals() external view returns (uint8); function latestAnswer() external view returns (int256 answer); } interface IBurnable { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } contract PrivateSale is Ownable { using SafeERC20 for IERC20; //*** Structs ***// struct Round { mapping(address => bool) whiteList; mapping(address => uint256) sums; mapping(address => address) depositToken; mapping(address => uint256) tokenReserve; uint256 totalReserve; uint256 tokensSold; uint256 tokenRate; uint256 maxMoney; uint256 sumTokens; uint256 minimumSaleAmount; uint256 maximumSaleAmount; uint256 startTimestamp; uint256 endTimestamp; uint256 duration; uint256 durationCount; uint256 lockup; TokenVestingGroup vestingContract; uint8 percentOnInvestorWallet; uint8 typeRound; bool finished; bool open; bool burnable; } struct InputNewRound { uint256 _tokenRate; uint256 _maxMoney; uint256 _sumTokens; uint256 _startTimestamp; uint256 _endTimestamp; uint256 _minimumSaleAmount; uint256 _maximumSaleAmount; uint256 _duration; uint256 _durationCount; uint256 _lockup; uint8 _typeRound; uint8 _percentOnInvestorWallet; bool _burnable; bool _open; } //*** Variable ***// mapping(uint256 => Round) rounds; address investorWallet; uint256 countRound; uint256 countTokens; mapping(uint256 => address) tokens; mapping(address => address) oracles; mapping(address => bool) tokensAdd; address BLID; address expenseAddress; //*** Modifiers ***// modifier isUsedToken(address _token) { require(tokensAdd[_token], "Token is not used "); _; } modifier finishedRound() { require(countRound == 0 || rounds[countRound - 1].finished, "Last round has not been finished"); _; } modifier unfinishedRound() { require(countRound != 0 && !rounds[countRound - 1].finished, "Last round has been finished"); _; } modifier existRound(uint256 round) { require(round < countRound, "Number round more than Rounds count"); _; } /*** User function ***/ /** * @notice User deposit amount of token for * @param amount Amount of token * @param token Address of token */ function deposit(uint256 amount, address token) external isUsedToken(token) unfinishedRound { require(rounds[countRound - 1].open || rounds[countRound - 1].whiteList[msg.sender], "No access"); require(!isParticipatedInTheRound(countRound - 1), "You have already made a deposit"); require(rounds[countRound - 1].startTimestamp < block.timestamp, "Round dont start"); require( rounds[countRound - 1].minimumSaleAmount <= amount * 10**(18 - AggregatorV3Interface(token).decimals()), "Minimum sale amount more than your amount" ); require( rounds[countRound - 1].maximumSaleAmount == 0 || rounds[countRound - 1].maximumSaleAmount >= amount * 10**(18 - AggregatorV3Interface(token).decimals()), " Your amount more than maximum sale amount" ); require( rounds[countRound - 1].endTimestamp > block.timestamp || rounds[countRound - 1].endTimestamp == 0, "Round is ended, round time expired" ); require( rounds[countRound - 1].tokenRate == 0 || rounds[countRound - 1].sumTokens == 0 || rounds[countRound - 1].sumTokens >= ((rounds[countRound - 1].totalReserve + amount * 10**(18 - AggregatorV3Interface(token).decimals())) * (1 ether)) / rounds[countRound - 1].tokenRate, "Round is ended, all tokens sold" ); require( rounds[countRound - 1].maxMoney == 0 || rounds[countRound - 1].maxMoney >= (rounds[countRound - 1].totalReserve + amount * 10**(18 - AggregatorV3Interface(token).decimals())), "The round is over, the maximum required value has been reached, or your amount is greater than specified in the conditions of the round" ); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); rounds[countRound - 1].tokenReserve[token] += amount * 10**(18 - AggregatorV3Interface(token).decimals()); rounds[countRound - 1].sums[msg.sender] += amount * 10**(18 - AggregatorV3Interface(token).decimals()); rounds[countRound - 1].depositToken[msg.sender] = token; rounds[countRound - 1].totalReserve += amount * 10**(18 - AggregatorV3Interface(token).decimals()); rounds[countRound - 1].vestingContract.deposit( msg.sender, token, amount * 10**(18 - AggregatorV3Interface(token).decimals()) ); } /** * @notice User return deposit of round * @param round number of round */ function returnDeposit(uint256 round) external { require(round < countRound, "Number round more than Rounds count"); require(rounds[round].sums[msg.sender] > 0, "You don't have deposit or you return your deposit"); require( !rounds[round].finished || rounds[round].typeRound == 0, "round has been finished successfully" ); IERC20(rounds[round].depositToken[msg.sender]).safeTransfer( msg.sender, rounds[round].sums[msg.sender] / 10**(18 - AggregatorV3Interface(rounds[round].depositToken[msg.sender]).decimals()) ); rounds[round].vestingContract.returnDeposit(msg.sender); rounds[round].totalReserve -= rounds[round].sums[msg.sender]; rounds[round].tokenReserve[rounds[round].depositToken[msg.sender]] -= rounds[round].sums[msg.sender]; rounds[round].sums[msg.sender] = 0; rounds[round].depositToken[msg.sender] = address(0); } /** * @notice Add token and token's oracle * @param _token Address of Token * @param _oracles Address of token's oracle(https://docs.chain.link/docs/binance-smart-chain-addresses/ */ function addToken(address _token, address _oracles) external onlyOwner { require(_token != address(0) && _oracles != address(0)); require(!tokensAdd[_token], "token was added"); oracles[_token] = _oracles; tokens[countTokens++] = _token; tokensAdd[_token] = true; } /** * @notice Set Investor Wallet * @param _investorWallet address of InvestorWallet */ function setInvestorWallet(address _investorWallet) external onlyOwner finishedRound { investorWallet = _investorWallet; } /** * @notice Set Expense Wallet * @param _expenseAddress address of Expense Address */ function setExpenseAddress(address _expenseAddress) external onlyOwner finishedRound { expenseAddress = _expenseAddress; } /** * @notice Set Expense Wallet and Investor Wallet * @param _investorWallet address of InvestorWallet * @param _expenseAddress address of Expense Address */ function setExpenseAddressAndInvestorWallet(address _expenseAddress, address _investorWallet) external onlyOwner finishedRound { expenseAddress = _expenseAddress; investorWallet = _investorWallet; } /** * @notice Set blid in contract * @param _BLID address of BLID */ function setBLID(address _BLID) external onlyOwner { require(BLID == address(0), "BLID was set"); BLID = _BLID; } /** * @notice Creat new round with input parameters * @param input Data about of new round */ function newRound(InputNewRound memory input) external onlyOwner finishedRound { require(BLID != address(0), "BLID is not set"); require(expenseAddress != address(0), "Require set expense address "); require( investorWallet != address(0) || input._percentOnInvestorWallet == 0, "Require set Logic contract" ); require( input._endTimestamp == 0 || input._endTimestamp > block.timestamp, "_endTimestamp must be unset or more than now timestamp" ); if (input._typeRound == 1) { require(input._tokenRate > 0, "Need set _tokenRate and _tokenRate must be more than 0"); require( IERC20(BLID).balanceOf(address(this)) >= input._sumTokens, "_sumTokens more than this smart contract have BLID" ); require(input._sumTokens > 0, "Need set _sumTokens "); rounds[countRound].tokenRate = input._tokenRate; rounds[countRound].maxMoney = input._maxMoney; rounds[countRound].startTimestamp = input._startTimestamp; rounds[countRound].sumTokens = input._sumTokens; rounds[countRound].endTimestamp = input._endTimestamp; rounds[countRound].duration = input._duration; rounds[countRound].durationCount = input._durationCount; rounds[countRound].minimumSaleAmount = input._minimumSaleAmount; rounds[countRound].maximumSaleAmount = input._maximumSaleAmount; rounds[countRound].lockup = input._lockup; rounds[countRound].percentOnInvestorWallet = input._percentOnInvestorWallet; rounds[countRound].burnable = input._burnable; rounds[countRound].open = input._open; rounds[countRound].typeRound = input._typeRound; address[] memory inputTokens = new address[](countTokens); for (uint256 i = 0; i < countTokens; i++) { inputTokens[i] = tokens[i]; } rounds[countRound].vestingContract = new TokenVestingGroup( BLID, input._duration, input._durationCount, inputTokens ); countRound++; } else if (input._typeRound == 2) { require(input._sumTokens > 0, "Need set _sumTokens"); require(input._tokenRate == 0, "Need unset _tokenRate (_tokenRate==0)"); require(!input._burnable, "Need not burnable round"); require( IERC20(BLID).balanceOf(address(this)) >= input._sumTokens, "_sumTokens more than this smart contract have BLID" ); rounds[countRound].tokenRate = input._tokenRate; rounds[countRound].maxMoney = input._maxMoney; rounds[countRound].startTimestamp = input._startTimestamp; rounds[countRound].endTimestamp = input._endTimestamp; rounds[countRound].sumTokens = input._sumTokens; rounds[countRound].duration = input._duration; rounds[countRound].minimumSaleAmount = input._minimumSaleAmount; rounds[countRound].maximumSaleAmount = input._maximumSaleAmount; rounds[countRound].durationCount = input._durationCount; rounds[countRound].lockup = input._lockup; rounds[countRound].percentOnInvestorWallet = input._percentOnInvestorWallet; rounds[countRound].burnable = input._burnable; rounds[countRound].open = input._open; rounds[countRound].typeRound = input._typeRound; address[] memory inputTokens = new address[](countTokens); for (uint256 i = 0; i < countTokens; i++) { inputTokens[i] = (tokens[i]); } rounds[countRound].vestingContract = new TokenVestingGroup( BLID, input._duration, input._durationCount, inputTokens ); countRound++; } } /** * @notice Set rate of token for last round(only for round that typy is 1) * @param rate Rate token token/usd * 10**18 */ function setRateToken(uint256 rate) external onlyOwner unfinishedRound { require(rounds[countRound - 1].typeRound == 1, "This round auto generate rate"); rounds[countRound - 1].tokenRate = rate; } /** * @notice Set timestamp when end round * @param _endTimestamp timesetamp when round is ended */ function setEndTimestamp(uint256 _endTimestamp) external onlyOwner unfinishedRound { rounds[countRound - 1].endTimestamp = _endTimestamp; } /** * @notice Set Sum Tokens * @param _sumTokens Amount of selling BLID. Necessarily with the type of round 2 */ function setSumTokens(uint256 _sumTokens) external onlyOwner unfinishedRound { require( IERC20(BLID).balanceOf(address(this)) >= _sumTokens, "_sumTokens more than this smart contract have BLID" ); require(_sumTokens > rounds[countRound - 1].tokensSold, "Token sold more than _sumTokens"); rounds[countRound - 1].sumTokens = _sumTokens; } /** * @notice Set Start Timestamp * @param _startTimestamp Unix timestamp Start Round */ function setStartTimestamp(uint256 _startTimestamp) external onlyOwner unfinishedRound { require(block.timestamp < _startTimestamp, "Round has been started"); rounds[countRound - 1].startTimestamp = _startTimestamp; } /** * @notice Set Max Money * @param _maxMoney Amount USD when close round */ function setMaxMoney(uint256 _maxMoney) external onlyOwner unfinishedRound { require(rounds[countRound - 1].totalReserve < _maxMoney, "Now total reserve more than _maxMoney"); rounds[countRound - 1].maxMoney = _maxMoney; } /** * @notice Add account in white list * @param account Address is added in white list */ function addWhiteList(address account) external onlyOwner unfinishedRound { rounds[countRound - 1].whiteList[account] = true; } /** * @notice Add accounts in white list * @param accounts Addresses are added in white list */ function addWhiteListByArray(address[] calldata accounts) external onlyOwner unfinishedRound { for (uint256 i = 0; i < accounts.length; i++) { rounds[countRound - 1].whiteList[accounts[i]] = true; } } /** * @notice Delete accounts in white list * @param account Address is deleted in white list */ function deleteWhiteList(address account) external onlyOwner unfinishedRound { rounds[countRound - 1].whiteList[account] = false; } /** * @notice Delete accounts in white list * @param accounts Addresses are deleted in white list */ function deleteWhiteListByArray(address[] calldata accounts) external onlyOwner unfinishedRound { for (uint256 i = 0; i < accounts.length; i++) { rounds[countRound - 1].whiteList[accounts[i]] = false; } } /** * @notice Finish round, send rate to VestingGroup contracts */ function finishRound() external onlyOwner { require(countRound != 0 && !rounds[countRound - 1].finished, "Last round has been finished"); uint256[] memory rates = new uint256[](countTokens); uint256 sumUSD = 0; for (uint256 i = 0; i < countTokens; i++) { if (rounds[countRound - 1].tokenReserve[tokens[i]] == 0) continue; IERC20(tokens[i]).safeTransfer( expenseAddress, rounds[countRound - 1].tokenReserve[tokens[i]] / 10**(18 - AggregatorV3Interface(tokens[i]).decimals()) - ((rounds[countRound - 1].tokenReserve[tokens[i]] / 10**(18 - AggregatorV3Interface(tokens[i]).decimals())) * (rounds[countRound - 1].percentOnInvestorWallet)) / 100 ); IERC20(tokens[i]).safeTransfer( investorWallet, ((rounds[countRound - 1].tokenReserve[tokens[i]] / 10**(18 - AggregatorV3Interface(tokens[i]).decimals())) * (rounds[countRound - 1].percentOnInvestorWallet)) / 100 ); rates[i] = (uint256(AggregatorV3Interface(oracles[tokens[i]]).latestAnswer()) * 10**(18 - AggregatorV3Interface(oracles[tokens[i]]).decimals())); sumUSD += (rounds[countRound - 1].tokenReserve[tokens[i]] * rates[i]) / (1 ether); if (rounds[countRound - 1].typeRound == 1) rates[i] = (rates[i] * (1 ether)) / rounds[countRound - 1].tokenRate; if (rounds[countRound - 1].typeRound == 2) rates[i] = (rounds[countRound - 1].sumTokens * rates[i]) / sumUSD; } if (sumUSD != 0) { rounds[countRound - 1].vestingContract.finishRound( block.timestamp + rounds[countRound - 1].lockup, rates ); if (rounds[countRound - 1].typeRound == 1) IERC20(BLID).safeTransfer( address(rounds[countRound - 1].vestingContract), (sumUSD * (1 ether)) / rounds[countRound - 1].tokenRate ); } if (rounds[countRound - 1].typeRound == 2) IERC20(BLID).safeTransfer( address(rounds[countRound - 1].vestingContract), rounds[countRound - 1].sumTokens ); if ( rounds[countRound - 1].burnable && rounds[countRound - 1].sumTokens - (sumUSD * (1 ether)) / rounds[countRound - 1].tokenRate != 0 ) { IBurnable(BLID).burn( rounds[countRound - 1].sumTokens - (sumUSD * (1 ether)) / rounds[countRound - 1].tokenRate ); } rounds[countRound - 1].finished = true; } /** * @notice Cancel round */ function cancelRound() external onlyOwner { require(countRound != 0 && !rounds[countRound - 1].finished, "Last round has been finished"); rounds[countRound - 1].finished = true; rounds[countRound - 1].typeRound = 0; } /** * @param id Number of round * @return InputNewRound - information about round */ function getRoundStateInfromation(uint256 id) public view returns (InputNewRound memory) { InputNewRound memory out = InputNewRound( rounds[id].tokenRate, rounds[id].maxMoney, rounds[id].sumTokens, rounds[id].startTimestamp, rounds[id].endTimestamp, rounds[id].minimumSaleAmount, rounds[id].maximumSaleAmount, rounds[id].duration, rounds[id].durationCount, rounds[id].lockup, rounds[id].typeRound, rounds[id].percentOnInvestorWallet, rounds[id].burnable, rounds[id].open ); return out; } /** * @param id Number of round * @return Locked Tokens */ function getLockedTokens(uint256 id) public view returns (uint256) { if (rounds[id].tokenRate == 0) return 0; return ((rounds[id].totalReserve * (1 ether)) / rounds[id].tokenRate); } /** * @param id Number of round * @return Returns (all deposited money, sold tokens, open or close round) */ function getRoundDynamicInfromation(uint256 id) public view returns ( uint256, uint256, bool ) { if (rounds[id].typeRound == 1) { return (rounds[id].totalReserve, rounds[id].totalReserve / rounds[id].tokenRate, rounds[id].open); } else { return (rounds[id].totalReserve, rounds[id].sumTokens, rounds[id].open); } } /** * @return True if `account` is in white list */ function isInWhiteList(address account) public view returns (bool) { return rounds[countRound - 1].whiteList[account]; } /** * @return Count round */ function getCountRound() public view returns (uint256) { return countRound; } /** * @param id Number of round * @return Address Vesting contract */ function getVestingAddress(uint256 id) public view existRound(id) returns (address) { return address(rounds[id].vestingContract); } /** * @param id Number of round * @param account Address of depositor * @return Investor Deposited Tokens */ function getInvestorDepositedTokens(uint256 id, address account) public view existRound(id) returns (uint256) { return (rounds[id].sums[account]); } /** * @return Investor Deposited Tokens */ function getInvestorWallet() public view returns (address) { return investorWallet; } /** * @param id Number of round * @return True if `id` round is cancelled */ function isCancelled(uint256 id) public view existRound(id) returns (bool) { return rounds[id].typeRound == 0; } /** * @param id Number of round * @return True if `msg.sender` is Participated In The Round */ function isParticipatedInTheRound(uint256 id) public view existRound(id) returns (bool) { return rounds[id].depositToken[msg.sender] != address(0); } /** * @param id Number of round * @return Deposited token addres of `msg.sender` */ function getUserToken(uint256 id) public view existRound(id) returns (address) { return rounds[id].depositToken[msg.sender]; } /** * @param id Number of round * @return True if `id` round is finished */ function isFinished(uint256 id) public view returns (bool) { return rounds[id].finished; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TokenVestingGroup is Ownable { using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); mapping(address => uint256) _sumUser; mapping(address => uint256) _rateToken; mapping(address => uint256) _released; mapping(address => address) _userToken; address[] _tokens; IERC20 public _token; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _durationCount; uint256 private _startTimestamp; uint256 private _duration; uint256 private _endTimestamp; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary. By then all * of the balance will have vested. */ constructor( address tokenValue, uint256 durationValue, uint256 durationCountValue, address[] memory tokensValue ) { _token = IERC20(tokenValue); _duration = durationValue; _durationCount = durationCountValue; _tokens = tokensValue; } /** * @notice Set amount of token for user deposited token */ function deposit( address user, address token, uint256 amount ) external onlyOwner { _userToken[user] = token; _sumUser[user] = amount; } /** * @notice Transfers vested tokens to beneficiary. */ function finishRound(uint256 startTimestampValue, uint256[] memory tokenRate) external onlyOwner { require(_startTimestamp == 0, "Vesting has been started"); _startTimestamp = startTimestampValue; for (uint256 i = 0; i < tokenRate.length; i++) { _rateToken[_tokens[i]] = tokenRate[i]; } } /** * @notice Transfers vested tokens to beneficiary. */ function claim() external { uint256 unreleased = releasableAmount(); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[msg.sender] = _released[msg.sender] + (unreleased); _token.safeTransfer(msg.sender, unreleased); emit TokensReleased(address(_token), unreleased); } /** * @notice Set 0 for user deposited token */ function returnDeposit(address user) external onlyOwner { require(_startTimestamp == 0, "Vesting has been started"); _userToken[user] = address(0); _sumUser[user] = 0; } /** * @return the end time of the token vesting. */ function end() public view returns (uint256) { return _startTimestamp + _duration * _durationCount; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _startTimestamp; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return the count of duration of the token vesting. */ function durationCount() public view returns (uint256) { return _durationCount; } /** * @return the amount of the token released. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function releasableAmount() public view returns (uint256) { return _vestedAmount(msg.sender) - (_released[msg.sender]); } /** * @dev Calculates the user dollar deposited. */ function getUserShare(address account) public view returns (uint256) { return (_sumUser[account] * _rateToken[_userToken[account]]) / (1 ether); } /** * @dev Calculates the amount that has already vested. */ function _vestedAmount(address account) public view returns (uint256) { require(_startTimestamp != 0, "Vesting has not been started"); uint256 totalBalance = (_sumUser[account] * _rateToken[_userToken[account]]) / (1 ether); if (block.timestamp < _startTimestamp) { return 0; } else if (block.timestamp >= _startTimestamp + _duration * _durationCount) { return totalBalance; } else { return (totalBalance * ((block.timestamp - _startTimestamp) / (_duration))) / (_durationCount); } } }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 10 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the securit y assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: farming/contracts/libs/PancakeVoteProxy.sol farming/contracts/libs/Migrations.sol farming/contracts/MasterChef.sol farming/contracts/Timelock.sol farming/contracts/libs/Mo ckBEP20.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided some functional requirements and no technical requirements. The contracts are forks of well -known ones. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 9 out of 10. No NatSpecs. Architecture quality The architecture quality score is 10 out of 10. Security score As a result of the audit, security engineers found 1 low severity issue. The security score is 10 out of 10. All found issues are displayed in the “Issues overview” sectio n. Summary According to the assessment, the Customer's smart contract has the following score: 9.9 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High 1. Possible rewards lost or receiving more Changing allocPoint in the MasterBlid.set method while _withUpdate flag is set to false may lead to rewards lost or receiving rewards more than deserved. Contract: MasterChef.sol Function: set Recommendation : Call updatePool(_pid) in the case if _withUpdate flag is false and you do not want to update all pools. Status: Fixed. (Revised Commit: 9ca0cf0) Medium 1. Privileged ownership The owner of the MasterBlid contract has permission to `updateMultiplier`, add new pools, change pool’s allocation points, and set a migrator contract (which will move all LPs from the pool to itself) without community consensus. Contract: MasterChef.sol Recommendation : Consider using one of the following methodologies: - Transfer ownership to a Time -lock contract with reasonable latency (i.e. 24h) so the community may react to changes; - Transfer ownership to a multi -signature wallet to prevent a single point of failure; - Transfer ownership to DAO so the community could decide whether the privileged operations should be executed by voting. Status: Fixed; Moved ownership to a Timelock (Revised Commit: 9ca0cf0) Low 1. Excess writing operation When _allocPoint is not changed for the pool, there is still an assignment for a new value, which consumes gas doing nothing. Contract: MasterChef.sol Function: set Recommendation :Move “poolInfo[_pid].allocPoint = _allocPoint” assignment inside the if block. www.hacken.io Status: Fixed (Revised Commit: 9378f79) 2. Missing Emit Events Functions that change critical values should emit events for better off-chain tracking. Contract: MasterChef.sol Function: setMigrator, updateMultiplier, setBlidPerBlock Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9378f79) 3. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 4. Balance upda ted after transfer It is recommended to update the balance state before doing any token transfer. Contract : MasterChef.sol Functions : emergencyWithdraw, migrate Recommendation : Update the balance and do transfer after that . Status: Reported (Revised Commit: 9378f79) 5. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: MasterChef.sol Functions : updateMultiplier, add, set, setBlidPerBlock, setM igrator, setExpenseAddress, migrate, deposit, withdraw, enterStaking, leaveStaking Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9378f79) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no sta tements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements . While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hacks. Thus, the audit can not guarantee the explicit security o f the audited smart contracts.
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 external call in Storage.sol:L51 2.b Fix (one line with code reference): Add require statement to check the return value of the external call. 3.a Problem (one line with code reference): Unchecked math in Storage.sol:L51 3.b Fix (one line with code reference): Add require statement to check the return value of the math operation. 4.a Problem (one line with code reference): Unsafe type inference in Storage.sol:L51 4.b Fix (one line with code reference): Add explicit type conversion to ensure the correct type is used. 5.a Problem (one line with code reference): Implicit visibility level in Storage.sol:L51 5.b Fix (one line with code reference): Add explicit visibility level to ensure the correct visibility is used. Moderate 6.a Problem (one line with code reference): Code duplications in Storage.sol 6.b Issues Count of Minor/Moderate/Major/Critical - Critical: 0 - High: 0 - Moderate: 1 - Minor: 3 Minor Issues 2.a Test failed (Scope: strategies, Revised Commit: 9378f79) 2.b Ensure that the tests are successful and cover all the code branches. Moderate 3.a Floating solidity version (Contracts: all, Revised Commit: 9378f79) 3.b Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Major 4.a Excessive state access (Contract: StorageV0.sol, Revised Commit: 9ca0cf0) 4.b Read the state variable to a local memory instead of multiple reading. Critical No critical severity issues were found. Observations - Logic is split into modules. - Contracts are self-descriptive. - No thinking about gas efficiency. - Room for improvements in code structuring. Conclusion According to the assessment, the Customer's smart contract has the following score: 9.5. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol // 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. // // Ctrl+f for XXX to see all the modifications. // XXX: pragma solidity ^0.5.16; pragma solidity 0.8.13; // XXX: import "./SafeMath.sol"; import "@pancakeswap/pancake-swap-lib/contracts/math/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 = 1 hours; 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; } // XXX: function() external payable { } receive() 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); } // Queue new transaction for executing with delay. 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; } // Cancel queued transaction. 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); } // Execute queued transaction if it is ready by conditions. 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Timelock.sol"; interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } contract MasterBlid is Ownable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BLIDs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBlidPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBlidPerShare` (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. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BLIDs to distribute per block. uint256 lastRewardBlock; // Last block number that BLIDs distribution occurs. uint256 accBlidPerShare; // Accumulated BLIDs per share, times 1e12. See below. } // The BLID TOKEN! IERC20 public blid; // Expense address. address public expenseAddress; // BLID tokens created per block. uint256 public blidPerBlock; // Bonus muliplier for early blid makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Timelock contract address Timelock public timelock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BLID mining starts. uint256 public startBlock; 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); event SetMigrator(address migrator); event UpdateMultiplier(uint256 multiplier); event SetBlidPerBlock(uint256 blidPerBlock); constructor( address _blid, address _expenseAddress, uint256 _blidPerBlock, uint256 _startBlock, uint256 _timelockDelay ) public { blid = IERC20(_blid); expenseAddress = _expenseAddress; blidPerBlock = _blidPerBlock; startBlock = _startBlock; Timelock _timelock = new Timelock(msg.sender, _timelockDelay); timelock = _timelock; // staking pool poolInfo.push( PoolInfo({ lpToken: IERC20(_blid), allocPoint: 1000, lastRewardBlock: startBlock, accBlidPerShare: 0 }) ); totalAllocPoint = 1000; transferOwnership(address(timelock)); } function updateMultiplier(uint256 multiplierNumber) external onlyOwner { BONUS_MULTIPLIER = multiplierNumber; emit UpdateMultiplier(multiplierNumber); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBlidPerShare: 0 }) ); } // Update the given pool's BLID allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } else { updatePool(_pid); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; if (prevAllocPoint != _allocPoint) { poolInfo[_pid].allocPoint = _allocPoint; totalAllocPoint = totalAllocPoint - prevAllocPoint + _allocPoint; } } // Set blid per block. Can only be called by the owner. function setBlidPerBlock(uint256 _blidPerBlock) external onlyOwner { blidPerBlock = _blidPerBlock; emit SetBlidPerBlock(_blidPerBlock); } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) external onlyOwner { migrator = _migrator; emit SetMigrator(address(_migrator)); } // Set the expense address. Can only be called by the owner. function setExpenseAddress(address _expenseAddress) external onlyOwner { expenseAddress = _expenseAddress; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return (_to - _from) * BONUS_MULTIPLIER; } // View function to see pending BLIDs on frontend. function pendingBlid(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBlidPerShare = pool.accBlidPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 blidReward = (multiplier * blidPerBlock * pool.allocPoint) / totalAllocPoint; accBlidPerShare = accBlidPerShare + ((blidReward * 1e12) / lpSupply); } return ((user.amount * accBlidPerShare) / 1e12) - user.rewardDebt; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 blidReward = (multiplier * blidPerBlock * pool.allocPoint) / totalAllocPoint; pool.accBlidPerShare = pool.accBlidPerShare + ((blidReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterBlid for BLID allocation. function deposit(uint256 _pid, uint256 _amount) external { require(_pid != 0, "deposit BLID by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount + _amount; } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterBlid. function withdraw(uint256 _pid, uint256 _amount) external { require(_pid != 0, "withdraw BLID by unstaking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount - _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Withdraw(msg.sender, _pid, _amount); } // Stake BLID tokens to MasterBlid function enterStaking(uint256 _amount) external { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount + _amount; } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Deposit(msg.sender, 0, _amount); } // Withdraw BLID tokens from STAKING. function leaveStaking(uint256 _amount) external { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount - _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 userAmount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), userAmount); emit EmergencyWithdraw(msg.sender, _pid, userAmount); } // Safe blid transfer function, just in case if rounding error causes pool to not have enough BLIDs. function safeBlidTransfer(address _to, uint256 _amount) internal { blid.safeTransferFrom(expenseAddress, _to, _amount); } }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 11 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the security assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: strategies/low_risk/contracts/libs/Aggregator.sol strategies/low_risk /contracts/libs/ERC20ForTestStorage.sol strategies/low_risk/contracts/libs/Migrations.sol strategies/low_risk/contracts/Logic.sol strategies/low_risk/contracts/Storage.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided functional requirements and technical requirements. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 7 out of 10. Code duplications. Not following solidity code style guidelines. Gas over -usage. Architecture quality The architecture quality score is 8 out of 10. Logic is split into modules. Contracts are self -descriptive. No thinking about gas efficiency. Room for improvements in code structuring. Security score As a result of the audit, security engineers found no issues . The security score is 10 out of 10. All found issues are displayed in the “Issues overview” section. Summary According to the assessment, the Cus tomer's smart contract has the following score: 9.5 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High No high severity issues were found. Medium 1. Test failed One of the two tests is failing. That could be either an issue in the test or an error in the contract logic implementation. Scope: strategies Recommendation : Ensure that the tests are successful and cover all the code branches. Status: 6 of 73 tests are failing (Revised Commit: 9378f79) Low 1. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 2. Excessive state access It is not recommended to read the state at each code line. It would be much more gas effective to read the state value into the local memory variable and use it for reading. Contract : StorageV0.sol Recommendation : Read the state variable to a local memory instead of multiple reading . Status: Fixed (Revised Commit: 9ca0cf0) 3. Not emitting events StorageV0 and Logic are not emitting events on state changes. There should be events to allow the community to track the current state off-chain. Contract: StorageV0.sol, Logic.sol Functions: setBLID, addToken, setLogic, setStorage, setAdmin www.hacken.io Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9ca0cf0) 4. Implicit variables visibility State variables that do not have specified visibility are declared internal implicitly. That could not be obvious. Contract: StorageV0.sol Variables : earnBLID, countEarns, countTokens, tokens, tokenBalance, oracles, tokensAdd, deposits, tokenDeposited, to kenTime, reserveBLID, logicContract, BLID Recommendation : Always declare visibility explicitly. Status: Fixed (Revised Commit: 9378f79) 5. Reading state variable’s `length` in the loop Reading `length` attribute in the loop may cost excess gas fees. Contract: Logic.sol Function : returnToken Recommendation : Save `length` attribute value into a local memory variable. Status: Fixed (Revised Commit: 9378f79) 6. Reading state variable in the loop Reading `countTokens` state variable in the loop would cost excess gas fees. Contract: StorageV0.sol Function : addEarn, _upBalance, _upBalanceByItarate, balanceEarnBLID, balanceOf, getTotalDeposit Recommendation : Save `countTokens` value into a local memor y variable. Status: Fixed (Revised Commit: 9ca0cf0) 7. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: Logic.sol, StorageV0.sol Functions : Logic.getReservesCount, Logic.getReserve, StorageV0.initialize, StorageV0._upBalance, StorageV0._upBalanceByItarate, StorageV0.balanceOf, StorageV0.getBLIDReserve, StorageV0.getTotalDeposit, StorageV0.getTokenBalance, StorageV0.getTokenDeposit, StorageV0._isUsedToken, StorageV0. getCountEarns www.hacken.io Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9ca0cf0) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no statements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements. While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hac ks. Thus, the audit can not guarantee the explicit security of the audited smart contracts.
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 external call in Storage.sol:L51 2.b Fix (one line with code reference): Add require statement to check the return value of the external call 3.a Problem (one line with code reference): Unchecked math in Storage.sol:L51 3.b Fix (one line with code reference): Add require statement to check the return value of the math operation 4.a Problem (one line with code reference): Unsafe type inference in Storage.sol:L51 4.b Fix (one line with code reference): Add explicit type conversion 5.a Problem (one line with code reference): Implicit visibility level in Storage.sol:L51 5.b Fix (one line with code reference): Add explicit visibility level Moderate 6.a Problem (one line with code reference): Code duplications in Storage.sol 6.b Fix (one line with code reference): Refactor the code to remove duplications Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Test failed 2.b Fix: Ensure that the tests are successful and cover all the code branches. Moderate 3.a Problem: Floating solidity version 3.b Fix: Specify the exact solidity version. Major None Critical None Observations - The architecture quality score is 8 out of 10. - The security score is 10 out of 10. - The overall score is 9.5 out of 10. Conclusion The audit of the customer's smart contract revealed no critical or high severity issues. Minor and moderate issues were found and fixed. The overall score is 9.5 out of 10. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
// COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol // 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. // // Ctrl+f for XXX to see all the modifications. // XXX: pragma solidity ^0.5.16; pragma solidity 0.8.13; // XXX: import "./SafeMath.sol"; import "@pancakeswap/pancake-swap-lib/contracts/math/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 = 1 hours; 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; } // XXX: function() external payable { } receive() 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); } // Queue new transaction for executing with delay. 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; } // Cancel queued transaction. 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); } // Execute queued transaction if it is ready by conditions. 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Timelock.sol"; interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } contract MasterBlid is Ownable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of BLIDs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accBlidPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accBlidPerShare` (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. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BLIDs to distribute per block. uint256 lastRewardBlock; // Last block number that BLIDs distribution occurs. uint256 accBlidPerShare; // Accumulated BLIDs per share, times 1e12. See below. } // The BLID TOKEN! IERC20 public blid; // Expense address. address public expenseAddress; // BLID tokens created per block. uint256 public blidPerBlock; // Bonus muliplier for early blid makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Timelock contract address Timelock public timelock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BLID mining starts. uint256 public startBlock; 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); event SetMigrator(address migrator); event UpdateMultiplier(uint256 multiplier); event SetBlidPerBlock(uint256 blidPerBlock); constructor( address _blid, address _expenseAddress, uint256 _blidPerBlock, uint256 _startBlock, uint256 _timelockDelay ) public { blid = IERC20(_blid); expenseAddress = _expenseAddress; blidPerBlock = _blidPerBlock; startBlock = _startBlock; Timelock _timelock = new Timelock(msg.sender, _timelockDelay); timelock = _timelock; // staking pool poolInfo.push( PoolInfo({ lpToken: IERC20(_blid), allocPoint: 1000, lastRewardBlock: startBlock, accBlidPerShare: 0 }) ); totalAllocPoint = 1000; transferOwnership(address(timelock)); } function updateMultiplier(uint256 multiplierNumber) external onlyOwner { BONUS_MULTIPLIER = multiplierNumber; emit UpdateMultiplier(multiplierNumber); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint + _allocPoint; poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accBlidPerShare: 0 }) ); } // Update the given pool's BLID allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } else { updatePool(_pid); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; if (prevAllocPoint != _allocPoint) { poolInfo[_pid].allocPoint = _allocPoint; totalAllocPoint = totalAllocPoint - prevAllocPoint + _allocPoint; } } // Set blid per block. Can only be called by the owner. function setBlidPerBlock(uint256 _blidPerBlock) external onlyOwner { blidPerBlock = _blidPerBlock; emit SetBlidPerBlock(_blidPerBlock); } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) external onlyOwner { migrator = _migrator; emit SetMigrator(address(_migrator)); } // Set the expense address. Can only be called by the owner. function setExpenseAddress(address _expenseAddress) external onlyOwner { expenseAddress = _expenseAddress; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) external { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return (_to - _from) * BONUS_MULTIPLIER; } // View function to see pending BLIDs on frontend. function pendingBlid(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBlidPerShare = pool.accBlidPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 blidReward = (multiplier * blidPerBlock * pool.allocPoint) / totalAllocPoint; accBlidPerShare = accBlidPerShare + ((blidReward * 1e12) / lpSupply); } return ((user.amount * accBlidPerShare) / 1e12) - user.rewardDebt; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 blidReward = (multiplier * blidPerBlock * pool.allocPoint) / totalAllocPoint; pool.accBlidPerShare = pool.accBlidPerShare + ((blidReward * 1e12) / lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterBlid for BLID allocation. function deposit(uint256 _pid, uint256 _amount) external { require(_pid != 0, "deposit BLID by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount + _amount; } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterBlid. function withdraw(uint256 _pid, uint256 _amount) external { require(_pid != 0, "withdraw BLID by unstaking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount - _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Withdraw(msg.sender, _pid, _amount); } // Stake BLID tokens to MasterBlid function enterStaking(uint256 _amount) external { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount + _amount; } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Deposit(msg.sender, 0, _amount); } // Withdraw BLID tokens from STAKING. function leaveStaking(uint256 _amount) external { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = ((user.amount * pool.accBlidPerShare) / 1e12) - user.rewardDebt; if (pending > 0) { safeBlidTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount - _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = (user.amount * pool.accBlidPerShare) / 1e12; emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 userAmount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), userAmount); emit EmergencyWithdraw(msg.sender, _pid, userAmount); } // Safe blid transfer function, just in case if rounding error causes pool to not have enough BLIDs. function safeBlidTransfer(address _to, uint256 _amount) internal { blid.safeTransferFrom(expenseAddress, _to, _amount); } }
Customer : Bolide Date: June 8th, 2022 www.hacken.io This document may contain confidential information about IT systems and the intellectual property of the Customer as well as information about potential vulnerabilities and methods of their exploitation. The report containing confidential information can be used internally by the Customer, or it can be disclosed publicly after all vulnerabilities are fixed — upon a decision of the Customer. Document Name Smart Contract Code Review and Security Analysis Report for Bolide. Approved By Andrew Matiukhin | CTO Hacken OU Type of Contracts ERC20 token; Farming; TokenSale; Strategy; Vesting Platform EVM Language Solidity Methods Architecture Review, Functional Testing, Computer -Aided Verification, Manual Review Website https://bolide.fi/ Timeline 21.03.2022 – 07.06.2022 Changelog 30.03.2022 – Initial Review 18.04.2022 – Revise 07.06.2022 – Revise www.hacken.io Table of contents Introduction 4 Scope 4 Executive Summary 6 Severity Definitions 7 Findings 8 Disclaimers 10 www.hacken.io Introduction Hacken OÜ (Consultant) was co ntracted by B olide (Customer) to conduct a Smart Contract Code Review and Security Analysis. This report presents the findings of the securit y assessment of the Customer's smart contract s. Scope The scope of the project is smart contracts in the repository: Repository: https://github.com/bolide -fi/contracts Commit: 9ca0cf09d7707bcbd942f0000f11059c5fb9c026 Documentation: Yes JS tests: Yes Contracts: farming/contracts/libs/PancakeVoteProxy.sol farming/contracts/libs/Migrations.sol farming/contracts/MasterChef.sol farming/contracts/Timelock.sol farming/contracts/libs/Mo ckBEP20.sol www.hacken.io We have scanned this smart contract for commonly known and more specific vulnerabilities. Here are some of the commonly known vulnerabilities that are considered: Category Check Item Code review ▪ Reentrancy ▪ Ownership Takeover ▪ Timestamp Dependence ▪ Gas Limit and Loops ▪ Transaction -Ordering Dependence ▪ Style guide violation ▪ EIP standards violation ▪ Unchecked external call ▪ Unchecked math ▪ Unsafe type inference ▪ Implicit visibility level ▪ Deployment Consistency ▪ Repository Consistency Functional review ▪ Business Logics Review ▪ Functionality Checks ▪ Access Control & Authorization ▪ Escrow manipulation ▪ Token Supply manipulation ▪ Assets integrity ▪ User Balances manipulation ▪ Data Consistency ▪ Kill-Switch Mechanism www.hacken.io Executive Summary The score measurements details can be found in the corresponding section of the methodology . Documentation quality The Customer provided some functional requirements and no technical requirements. The contracts are forks of well -known ones. The total Documentation Quality score is 10 out of 10. Code quality The total CodeQuality score is 9 out of 10. No NatSpecs. Architecture quality The architecture quality score is 10 out of 10. Security score As a result of the audit, security engineers found 1 low severity issue. The security score is 10 out of 10. All found issues are displayed in the “Issues overview” sectio n. Summary According to the assessment, the Customer's smart contract has the following score: 9.9 www.hacken.io Severity Definitions Risk Level Description Critical Critical vulnerabilities are usually straightforward to exploit and can lead to assets loss or data manipulations. High High-level vulnerabilities are difficult to exploit; however, they also have a significant impact on smart contract execution, e.g., public access to crucial functions Medium Medium-level vulnerabilities are important to fix; however, they cannot lead to assets loss or data manipulations. Low Low-level vulnerabilities are mostly related to outdated, unused, etc. code snippets that cannot have a significant impact on execution www.hacken.io Findings Critical No critical severity issues were found. High 1. Possible rewards lost or receiving more Changing allocPoint in the MasterBlid.set method while _withUpdate flag is set to false may lead to rewards lost or receiving rewards more than deserved. Contract: MasterChef.sol Function: set Recommendation : Call updatePool(_pid) in the case if _withUpdate flag is false and you do not want to update all pools. Status: Fixed. (Revised Commit: 9ca0cf0) Medium 1. Privileged ownership The owner of the MasterBlid contract has permission to `updateMultiplier`, add new pools, change pool’s allocation points, and set a migrator contract (which will move all LPs from the pool to itself) without community consensus. Contract: MasterChef.sol Recommendation : Consider using one of the following methodologies: - Transfer ownership to a Time -lock contract with reasonable latency (i.e. 24h) so the community may react to changes; - Transfer ownership to a multi -signature wallet to prevent a single point of failure; - Transfer ownership to DAO so the community could decide whether the privileged operations should be executed by voting. Status: Fixed; Moved ownership to a Timelock (Revised Commit: 9ca0cf0) Low 1. Excess writing operation When _allocPoint is not changed for the pool, there is still an assignment for a new value, which consumes gas doing nothing. Contract: MasterChef.sol Function: set Recommendation :Move “poolInfo[_pid].allocPoint = _allocPoint” assignment inside the if block. www.hacken.io Status: Fixed (Revised Commit: 9378f79) 2. Missing Emit Events Functions that change critical values should emit events for better off-chain tracking. Contract: MasterChef.sol Function: setMigrator, updateMultiplier, setBlidPerBlock Recommendation : Consider adding events when changing critical values and emit them in the function. Status: Fixed (Revised Commit: 9378f79) 3. Floating solidity version It is recommended to specify the exact solidity version in the contracts. Contracts : all Recommendation : Specify the exact solidity version (ex. pragma solidity 0.8.10 instead of pragma solidity ^0.8.0 ). Status: Fixed (Revised Commit: 9378f79) 4. Balance upda ted after transfer It is recommended to update the balance state before doing any token transfer. Contract : MasterChef.sol Functions : emergencyWithdraw, migrate Recommendation : Update the balance and do transfer after that . Status: Reported (Revised Commit: 9378f79) 5. A public function that could be declared external Public functions that are never called by the contract should be declared external . Contracts: MasterChef.sol Functions : updateMultiplier, add, set, setBlidPerBlock, setM igrator, setExpenseAddress, migrate, deposit, withdraw, enterStaking, leaveStaking Recommendation : Use the external attribute for functions never called from the contract. Status: Fixed (Revised Commit: 9378f79) www.hacken.io Disclaimers Hacken Disclaimer The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report (Source Code); the Source Code compilation, deployment, and functionality (performing the intended functions). The audit makes no sta tements or warranties on the security of the code. It also cannot be considered a sufficient assessment regarding the utility and safety of the code, bug-free status, or any other contract statements . While we have done our best in conducting the analysis and producing this report, it is important to note that you should not rely on this report only — we recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contracts. Technical Disclaimer Smart contracts are deployed and executed on a blockchain platform. The platform, its programming language, and other software related to the smart contract can have vulnerabilities that can lead to hacks. Thus, the audit can not guarantee the explicit security o f the audited smart contracts.
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 external call in Storage.sol:L51 2.b Fix (one line with code reference): Add require statement to check the return value of the external call 3.a Problem (one line with code reference): Unchecked math in Storage.sol:L51 3.b Fix (one line with code reference): Add require statement to check the return value of the math operation 4.a Problem (one line with code reference): Unsafe type inference in Storage.sol:L51 4.b Fix (one line with code reference): Add explicit type conversion 5.a Problem (one line with code reference): Implicit visibility level in Storage.sol:L51 5.b Fix (one line with code reference): Add explicit visibility level Moderate 6.a Problem (one line with code reference): Code duplications in Storage.sol 6.b Fix (one line with code reference): Refactor the code to remove duplications Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Test failed 2.b Fix: Ensure that the tests are successful and cover all the code branches. Moderate 3.a Problem: Floating solidity version 3.b Fix: Specify the exact solidity version. Major None Critical None Observations - The architecture quality score is 8 out of 10. - The security score is 10 out of 10. - The overall score is 9.5 out of 10. Conclusion The audit of the customer's smart contract revealed no critical or high severity issues. Minor and moderate issues were found and fixed. The overall score is 9.5 out of 10. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Reading `length` attribute in the loop may cost excess gas fees. (Contract: StorageV0.sol) 2.b Fix: Save `length` attribute value into a local memory variable. (Revised Commit: 9378f79) Moderate: 3.a Problem: Reading `countTokens` state variable in the loop would cost excess gas fees. (Contract: StorageV0.sol) 3.b Fix: Save `countTokens` value into a local memory variable. (Revised Commit: 9ca0cf0) Major: None Critical: None Observations: Public functions that are never called by the contract should be declared external. (Contracts: Logic.sol, StorageV0.sol) Conclusion: The smart contracts given for audit have been analyzed by the best industry practices at the date of this report, with cybersecurity vulnerabilities and issues in smart contract source code, the details of which are disclosed in this report. The audit makes no
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import '@openzeppelin/contracts/interfaces/IERC721.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import './OKLGProduct.sol'; /** * @title MTGYTokenLocker * @dev This is the main contract that supports locking/vesting tokens. */ contract MTGYTokenLocker is OKLGProduct { using SafeMath for uint48; using SafeMath for uint256; struct Locker { address owner; address token; bool isNft; // rewardToken is either ERC20 or ERC721 uint256 amountSupply; // If ERC-721, will always be 1, otherwise is amount of tokens locked uint256 tokenId; // only populated if isNft is true uint48 start; // timestamp (uint256) of start lock time (block.timestamp at creation) uint48 end; // timestamp (uint256) of end lock time address[] withdrawable; // any additional addresses that can withdraw tokens from this locker uint256 amountWithdrawn; // numberVests: // 1 means can only withdraw tokens at end of lock period // any other number is evenly distributed throughout lock period uint8 numberVests; } mapping(address => uint16[]) public lockersByOwner; mapping(address => uint16[]) public lockersByToken; mapping(address => uint16[]) public lockersByWithdrawable; Locker[] public lockers; event CreateLocker(address indexed creator, uint256 idx); event WithdrawTokens( uint256 indexed idx, address withdrawer, uint256 numTokensOrTokenId ); constructor(address _tokenAddress, address _spendAddress) OKLGProduct(uint8(5), _tokenAddress, _spendAddress) {} function getAllLockers() external view returns (Locker[] memory) { return lockers; } function createLocker( address _tokenAddress, uint256 _amountOrTokenId, uint48 _end, uint8 _numberVests, address[] memory _withdrawableAddresses, bool _isNft ) external payable { require( _end > block.timestamp, 'Locker end date must be after current time.' ); _payForService(0); if (_isNft) { IERC721 _token = IERC721(_tokenAddress); _token.transferFrom(msg.sender, address(this), _amountOrTokenId); } else { IERC20 _token = IERC20(_tokenAddress); _token.transferFrom(msg.sender, address(this), _amountOrTokenId); } lockers.push( Locker({ owner: msg.sender, isNft: _isNft, token: _tokenAddress, amountSupply: _isNft ? 1 : _amountOrTokenId, tokenId: _isNft ? _amountOrTokenId : 0, start: uint48(block.timestamp), end: _end, withdrawable: _withdrawableAddresses, amountWithdrawn: 0, numberVests: _isNft ? 1 : (_numberVests == 0 ? 1 : _numberVests) }) ); uint16 _newIdx = uint16(lockers.length - 1); lockersByOwner[msg.sender].push(_newIdx); lockersByToken[_tokenAddress].push(_newIdx); if (_withdrawableAddresses.length > 0) { for (uint16 _i = 0; _i < _withdrawableAddresses.length; _i++) { lockersByWithdrawable[_withdrawableAddresses[_i]].push(_newIdx); } } emit CreateLocker(msg.sender, _newIdx); } function withdrawLockedTokens(uint16 _idx, uint256 _amountOrTokenId) external { Locker storage _locker = lockers[_idx]; require( _locker.amountWithdrawn < _locker.amountSupply, 'All tokens have been withdrawn from this locker.' ); bool _isWithdrawableUser = msg.sender == _locker.owner; if (!_isWithdrawableUser) { for (uint256 _i = 0; _i < _locker.withdrawable.length; _i++) { if (_locker.withdrawable[_i] == msg.sender) { _isWithdrawableUser = true; break; } } } require( _isWithdrawableUser, 'Must be locker owner or a withdrawable wallet.' ); // SWC-Reentrancy: L126 _locker.amountWithdrawn += _locker.isNft ? 1 : _amountOrTokenId; if (_locker.isNft) { require( block.timestamp > _locker.end, 'Must wait until locker expires to withdraw.' ); IERC721 _token = IERC721(_locker.token); _token.transferFrom(address(this), msg.sender, _amountOrTokenId); } else { uint256 _maxAmount = maxWithdrawableTokens(_idx); require( _amountOrTokenId > 0 && _amountOrTokenId <= _maxAmount, 'Make sure you enter a valid withdrawable amount and not more than has vested.' ); IERC20 _token = IERC20(_locker.token); _token.transferFrom(address(this), msg.sender, _amountOrTokenId); } emit WithdrawTokens(_idx, msg.sender, _amountOrTokenId); } function changeLockerOwner(uint16 _idx, address _newOwner) external { Locker storage _locker = lockers[_idx]; require( _locker.owner == msg.sender, 'Must be the locker owner to change owner.' ); _locker.owner = _newOwner; } function changeLockerEndTime(uint16 _idx, uint48 _newEnd) external { Locker storage _locker = lockers[_idx]; require( _locker.owner == msg.sender, 'Must be the locker owner to change owner.' ); require(_newEnd > _locker.end, 'Can only extend end time, not shorten it.'); _locker.end = _newEnd; } function maxWithdrawableTokens(uint16 _idx) public view returns (uint256) { Locker memory _locker = lockers[_idx]; uint256 _fullLockPeriodSec = _locker.end.sub(_locker.start); uint256 _secondsPerVest = _fullLockPeriodSec.div(_locker.numberVests); uint256 _tokensPerVest = _locker.amountSupply.div(_locker.numberVests); uint256 _numberWithdrawableVests = (block.timestamp.sub(_locker.start)).div( _secondsPerVest ); if (_numberWithdrawableVests == 0) return 0; return _numberWithdrawableVests.mul(_tokensPerVest).sub(_locker.amountWithdrawn); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import './interfaces/IConditional.sol'; contract HasERC20Balance is IConditional, Ownable { address public tokenContract; uint256 public minTokenBalance = 1; constructor(address _tokenContract) { tokenContract = _tokenContract; } function passesTest(address wallet) external view override returns (bool) { return IERC20(tokenContract).balanceOf(wallet) >= minTokenBalance; } function setTokenAddress(address _tokenContract) external onlyOwner { tokenContract = _tokenContract; } function setMinTokenBalance(uint256 _newMin) external onlyOwner { minTokenBalance = _newMin; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/interfaces/IERC20.sol'; /** * @title OKLGWithdrawable * @dev Supports being able to get tokens or ETH out of a contract with ease */ contract OKLGWithdrawable is Ownable { function withdrawTokens(address _tokenAddy, uint256 _amount) external onlyOwner { IERC20 _token = IERC20(_tokenAddy); _amount = _amount > 0 ? _amount : _token.balanceOf(address(this)); require(_amount > 0, 'make sure there is a balance available to withdraw'); _token.transfer(owner(), _amount); } function withdrawETH() external onlyOwner { payable(owner()).call{ value: address(this).balance }(''); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/interfaces/IERC20.sol'; /** * @title MTGYOKLGSwap * @dev Swap MTGY for OKLG on BSC */ contract MTGYOKLGSwap is Ownable { IERC20 private mtgy = IERC20(0x025c9f1146d4d94F8F369B9d98104300A3c8ca23); IERC20 private oklg = IERC20(0x55E8b37a3c43B049deDf56C77f462Db095108651); uint8 public mtgyOklgRatio = 120; function swap() external { uint256 mtgyBalance = mtgy.balanceOf(msg.sender); require(mtgyBalance > 0, 'must have a MTGY balance to swap for OKLG'); uint256 oklgToTransfer = (mtgyBalance * mtgyOklgRatio) / 10**9; // MTGY has 18 decimals, OKLG has 9 decimals require( oklg.balanceOf(address(this)) >= oklgToTransfer, 'not enough OKLG liquidity to execute swap' ); mtgy.transferFrom(msg.sender, address(this), mtgyBalance); oklg.transfer(msg.sender, oklgToTransfer); } function changeRatio(uint8 _newRatio) external onlyOwner { mtgyOklgRatio = _newRatio; } function withdrawTokens(address _tokenAddy, uint256 _amount) external onlyOwner { IERC20 _token = IERC20(_tokenAddy); _amount = _amount > 0 ? _amount : _token.balanceOf(address(this)); require(_amount > 0, 'make sure there is a balance available to withdraw'); _token.transfer(owner(), _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import './OKLGFaaSToken.sol'; import './OKLGProduct.sol'; /** * @title OKLGFaaS (sOKLG) * @author Lance Whatley * @notice Implements the master FaaS contract to keep track of all tokens being added * to be staked and staking. */ contract OKLGFaaS is OKLGProduct { // this is a mapping of tokenAddress => contractAddress[] that represents // a particular address for the token that someone has put up // to be staked and a list of contract addresses for the staking token // contracts paying out stakers for the given token. mapping(address => address[]) public tokensUpForStaking; address[] public allFarmingContracts; uint256 public totalStakingContracts; /** * @notice The constructor for the staking master contract. */ constructor(address _tokenAddress, address _spendAddress) OKLGProduct(uint8(8), _tokenAddress, _spendAddress) {} function getAllFarmingContracts() external view returns (address[] memory) { return allFarmingContracts; } function getTokensForStaking(address _tokenAddress) external view returns (address[] memory) { return tokensUpForStaking[_tokenAddress]; } function createNewTokenContract( address _rewardsTokenAddy, address _stakedTokenAddy, uint256 _supply, uint256 _perBlockAllocation, uint256 _lockedUntilDate, uint256 _timelockSeconds, bool _isStakedNft ) external payable { _payForService(0); // create new OKLGFaaSToken contract which will serve as the core place for // users to stake their tokens and earn rewards ERC20 _rewToken = ERC20(_rewardsTokenAddy); // Send the new contract all the tokens from the sending user to be staked and harvested _rewToken.transferFrom(msg.sender, address(this), _supply); // in order to handle tokens that take tax, are burned, etc. when transferring, need to get // the user's balance after transferring in order to send the remainder of the tokens // instead of the full original supply. Similar to slippage on a DEX uint256 _updatedSupply = _supply <= _rewToken.balanceOf(address(this)) ? _supply : _rewToken.balanceOf(address(this)); OKLGFaaSToken _contract = new OKLGFaaSToken( 'OKLG Staking Token', 'sOKLG', _updatedSupply, _rewardsTokenAddy, _stakedTokenAddy, msg.sender, _perBlockAllocation, _lockedUntilDate, _timelockSeconds, _isStakedNft ); allFarmingContracts.push(address(_contract)); tokensUpForStaking[_stakedTokenAddy].push(address(_contract)); totalStakingContracts++; _rewToken.transfer(address(_contract), _updatedSupply); // do one more double check on balance of rewards token // in the staking contract and update if need be uint256 _finalSupply = _updatedSupply <= _rewToken.balanceOf(address(_contract)) ? _updatedSupply : _rewToken.balanceOf(address(_contract)); if (_updatedSupply != _finalSupply) { _contract.updateSupply(_finalSupply); } } function removeTokenContract(address _faasTokenAddy) external { OKLGFaaSToken _contract = OKLGFaaSToken(_faasTokenAddy); require( msg.sender == _contract.tokenOwner(), 'user must be the original token owner to remove tokens' ); require( block.timestamp > _contract.getLockedUntilDate() && _contract.getLockedUntilDate() != 0, 'it must be after the locked time the user originally configured and not locked forever' ); _contract.removeStakeableTokens(); totalStakingContracts--; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import '@openzeppelin/contracts/interfaces/IERC721.sol'; import './OKLGProduct.sol'; /** * @title OKLGRaffle * @dev This is the main contract that supports lotteries and raffles. */ contract OKLGRaffle is OKLGProduct { struct Raffle { address owner; bool isNft; // rewardToken is either ERC20 or ERC721 address rewardToken; uint256 rewardAmountOrTokenId; uint256 start; // timestamp (uint256) of start time (0 if start when raffle is created) uint256 end; // timestamp (uint256) of end time (0 if can be entered until owner draws) address entryToken; // ERC20 token requiring user to send to enter uint256 entryFee; // ERC20 num tokens user must send to enter, or 0 if no entry fee uint256 entryFeesCollected; // amount of fees collected by entries and paid to raffle/lottery owner uint256 maxEntriesPerAddress; // 0 means unlimited entries address[] entries; address winner; bool isComplete; bool isClosed; } uint8 public entryFeePercentageCharge = 2; mapping(bytes32 => Raffle) public raffles; bytes32[] public raffleIds; mapping(bytes32 => mapping(address => uint256)) public entriesIndexed; event CreateRaffle(address indexed creator, bytes32 id); event EnterRaffle( bytes32 indexed id, address raffler, uint256 numberOfEntries ); event DrawWinner(bytes32 indexed id, address winner, uint256 amount); event CloseRaffle(bytes32 indexed id); constructor(address _tokenAddress, address _spendAddress) OKLGProduct(uint8(4), _tokenAddress, _spendAddress) {} function getAllRaffles() external view returns (bytes32[] memory) { return raffleIds; } function getRaffleEntries(bytes32 _id) external view returns (address[] memory) { return raffles[_id].entries; } function createRaffle( address _rewardTokenAddress, uint256 _rewardAmountOrTokenId, bool _isNft, uint256 _start, uint256 _end, address _entryToken, uint256 _entryFee, uint256 _maxEntriesPerAddress ) external payable { _validateDates(_start, _end); _payForService(0); if (_isNft) { IERC721 _rewardToken = IERC721(_rewardTokenAddress); _rewardToken.transferFrom( msg.sender, address(this), _rewardAmountOrTokenId ); } else { IERC20 _rewardToken = IERC20(_rewardTokenAddress); _rewardToken.transferFrom( msg.sender, address(this), _rewardAmountOrTokenId ); } bytes32 _id = sha256(abi.encodePacked(msg.sender, block.number)); address[] memory _entries; raffles[_id] = Raffle({ owner: msg.sender, isNft: _isNft, rewardToken: _rewardTokenAddress, rewardAmountOrTokenId: _rewardAmountOrTokenId, start: _start, end: _end, entryToken: _entryToken, entryFee: _entryFee, entryFeesCollected: 0, maxEntriesPerAddress: _maxEntriesPerAddress, entries: _entries, winner: address(0), isComplete: false, isClosed: false }); raffleIds.push(_id); emit CreateRaffle(msg.sender, _id); } function drawWinner(bytes32 _id) external { Raffle storage _raffle = raffles[_id]; // SWC-Weak Sources of Randomness from Chain Attributes: L115 - L159 require( _raffle.end == 0 || block.timestamp > _raffle.end, 'Raffle entry period is not over yet.' ); require( !_raffle.isComplete, 'Raffle has already been drawn and completed.' ); if (_raffle.entryFeesCollected > 0) { IERC20 _entryToken = IERC20(_raffle.entryToken); uint256 _feesToSendOwner = _raffle.entryFeesCollected; if (entryFeePercentageCharge > 0) { uint256 _feeChargeAmount = (_feesToSendOwner * entryFeePercentageCharge) / 100; _entryToken.transfer(owner(), _feeChargeAmount); _feesToSendOwner -= _feeChargeAmount; } _entryToken.transfer(_raffle.owner, _feesToSendOwner); } uint256 _winnerIdx = _random(_raffle.entries.length) % _raffle.entries.length; address _winner = _raffle.entries[_winnerIdx]; _raffle.winner = _winner; if (_raffle.isNft) { IERC721 _rewardToken = IERC721(_raffle.rewardToken); _rewardToken.transferFrom( address(this), _winner, _raffle.rewardAmountOrTokenId ); } else { IERC20 _rewardToken = IERC20(_raffle.rewardToken); _rewardToken.transfer(_winner, _raffle.rewardAmountOrTokenId); } _raffle.isComplete = true; emit DrawWinner(_id, _winner, _raffle.rewardAmountOrTokenId); } function closeRaffleAndRefund(bytes32 _id) external { Raffle storage _raffle = raffles[_id]; require( _raffle.owner == msg.sender, 'Must be the raffle owner to draw winner.' ); require( !_raffle.isComplete, 'Raffle cannot be closed if it is completed already.' ); IERC20 _entryToken = IERC20(_raffle.entryToken); for (uint256 _i = 0; _i < _raffle.entries.length; _i++) { address _user = _raffle.entries[_i]; _entryToken.transfer(_user, _raffle.entryFee); } if (_raffle.isNft) { IERC721 _rewardToken = IERC721(_raffle.rewardToken); _rewardToken.transferFrom( address(this), msg.sender, _raffle.rewardAmountOrTokenId ); } else { IERC20 _rewardToken = IERC20(_raffle.rewardToken); _rewardToken.transfer(msg.sender, _raffle.rewardAmountOrTokenId); } _raffle.isComplete = true; _raffle.isClosed = true; emit CloseRaffle(_id); } function enterRaffle(bytes32 _id, uint256 _numEntries) external { Raffle storage _raffle = raffles[_id]; require(_raffle.owner != address(0), 'We do not recognize this raffle.'); require( _raffle.start <= block.timestamp, 'It must be after the start time to enter the raffle.' ); require( _raffle.end == 0 || _raffle.end >= block.timestamp, 'It must be before the end time to enter the raffle.' ); require( _numEntries > 0 && (_raffle.maxEntriesPerAddress == 0 || entriesIndexed[_id][msg.sender] + _numEntries <= _raffle.maxEntriesPerAddress), 'You have entered the maximum number of times you are allowed.' ); require(!_raffle.isComplete, 'Raffle cannot be complete to be entered.'); if (_raffle.entryFee > 0) { IERC20 _entryToken = IERC20(_raffle.entryToken); _entryToken.transferFrom( msg.sender, address(this), _raffle.entryFee * _numEntries ); _raffle.entryFeesCollected += _raffle.entryFee * _numEntries; } for (uint256 _i = 0; _i < _numEntries; _i++) { _raffle.entries.push(msg.sender); } entriesIndexed[_id][msg.sender] += _numEntries; emit EnterRaffle(_id, msg.sender, _numEntries); } function changeRaffleOwner(bytes32 _id, address _newOwner) external { Raffle storage _raffle = raffles[_id]; require( _raffle.owner == msg.sender, 'Must be the raffle owner to change owner.' ); require( !_raffle.isComplete, 'Raffle has already been drawn and completed.' ); _raffle.owner = _newOwner; } function changeEndDate(bytes32 _id, uint256 _newEnd) external { Raffle storage _raffle = raffles[_id]; require( _raffle.owner == msg.sender, 'Must be the raffle owner to change owner.' ); require( !_raffle.isComplete, 'Raffle has already been drawn and completed.' ); _raffle.end = _newEnd; } function changeEntryFeePercentageCharge(uint8 _newPercentage) external onlyOwner { require( _newPercentage >= 0 && _newPercentage < 100, 'Should be between 0 and 100.' ); entryFeePercentageCharge = _newPercentage; } function _validateDates(uint256 _start, uint256 _end) private view { require( _start == 0 || _start >= block.timestamp, 'start time should be 0 or after the current time' ); require( _end == 0 || _end > block.timestamp, 'end time should be 0 or after the current time' ); if (_start > 0) { if (_end > 0) { require(_start < _end, 'start time must be before end time'); } } } function _random(uint256 _entries) private view returns (uint256) { return uint256( keccak256(abi.encodePacked(block.difficulty, block.timestamp, _entries)) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/interfaces/IERC721.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; import './interfaces/IConditional.sol'; import './interfaces/IMultiplier.sol'; import './OKLGWithdrawable.sol'; contract OKLGDividendDistributor is OKLGWithdrawable { using SafeMath for uint256; struct Dividend { uint256 totalExcluded; // excluded dividend uint256 totalRealised; uint256 lastClaim; // used for boosting logic } struct Share { uint256 amount; uint256 amountBase; uint256[] nftBoostTokenIds; } address public shareholderToken; address public nftBoosterToken; uint256 public totalSharesBoosted; uint256 public totalSharesDeposited; // will only be actual deposited tokens without handling any reflections or otherwise address wrappedNative; IUniswapV2Router02 router; // used to fetch in a frontend to get full list // of tokens that dividends can be claimed address[] public tokens; mapping(address => bool) tokenAwareness; mapping(address => uint256) shareholderClaims; // amount of shares a user has mapping(address => Share) shares; // dividend information per user mapping(address => mapping(address => Dividend)) public dividends; address public boostContract; address public boostMultiplierContract; // per token dividends mapping(address => uint256) public totalDividends; mapping(address => uint256) public totalDistributed; // to be shown in UI mapping(address => uint256) public dividendsPerShare; uint256 public constant ACC_FACTOR = 10**36; address public constant DEAD = 0x000000000000000000000000000000000000dEaD; constructor( address _dexRouter, address _shareholderToken, address _nftBoosterToken, address _wrappedNative ) { router = IUniswapV2Router02(_dexRouter); shareholderToken = _shareholderToken; nftBoosterToken = _nftBoosterToken; wrappedNative = _wrappedNative; } function stake( address token, uint256 amount, uint256[] memory nftTokenIds ) external { _stake(msg.sender, token, amount, nftTokenIds, false); } function _stake( address shareholder, address token, uint256 amount, uint256[] memory nftTokenIds, bool contractOverride ) private { if (shares[shareholder].amount > 0 && !contractOverride) { distributeDividend(token, shareholder, false); } IERC20 shareContract = IERC20(shareholderToken); uint256 stakeAmount = amount == 0 ? shareContract.balanceOf(shareholder) : amount; // for compounding we will pass in this contract override flag and assume the tokens // received by the contract during the compounding process are already here, therefore // whatever the amount is passed in is what we care about and leave it at that. If a normal // staking though by a user, transfer tokens from the user to the contract. uint256 finalBaseAmount = stakeAmount; if (!contractOverride) { uint256 shareBalanceBefore = shareContract.balanceOf(address(this)); shareContract.transferFrom(shareholder, address(this), stakeAmount); finalBaseAmount = shareContract.balanceOf(address(this)).sub( shareBalanceBefore ); IERC721 nftContract = IERC721(nftBoosterToken); for (uint256 i = 0; i < nftTokenIds.length; i++) { nftContract.transferFrom(shareholder, address(this), nftTokenIds[i]); shares[shareholder].nftBoostTokenIds.push(nftTokenIds[i]); } } // NOTE: temporarily setting shares[shareholder].amount to base deposited to get elevated shares. // They depend on shares[shareholder].amount being populated, but we're simply reversing this // after calculating boosted amount uint256 currentAmountWithBoost = shares[msg.sender].amount; shares[shareholder].amount = shares[shareholder].amountBase.add( finalBaseAmount ); // this is the final amount AFTER adding the new base amount, not just the additional uint256 finalBoostedAmount = getElevatedSharesWithBooster( shareholder, shares[shareholder].amount ); shares[shareholder].amount = currentAmountWithBoost; totalSharesDeposited = totalSharesDeposited.add(finalBaseAmount); totalSharesBoosted = totalSharesBoosted.sub(shares[shareholder].amount).add( finalBoostedAmount ); shares[shareholder].amountBase += finalBaseAmount; shares[shareholder].amount = finalBoostedAmount; dividends[shareholder][token].totalExcluded = getCumulativeDividends( token, shares[shareholder].amount ); } function unstake(address token, uint256 boostedAmount) external { require( shares[msg.sender].amount > 0 && (boostedAmount == 0 || boostedAmount <= shares[msg.sender].amount), 'you can only unstake if you have some staked' ); distributeDividend(token, msg.sender, false); IERC20 shareContract = IERC20(shareholderToken); uint256 boostedAmountToUnstake = boostedAmount == 0 ? shares[msg.sender].amount : boostedAmount; // NOTE: temporarily setting shares[shareholder].amount to base deposited to get elevated shares. // They depend on shares[shareholder].amount being populated, but we're simply reversing this // after calculating boosted amount uint256 currentAmountWithBoost = shares[msg.sender].amount; shares[msg.sender].amount = shares[msg.sender].amountBase; uint256 baseAmount = getBaseSharesFromBoosted( msg.sender, boostedAmountToUnstake ); shares[msg.sender].amount = currentAmountWithBoost; // handle reflections tokens uint256 finalWithdrawAmount = getAppreciatedShares(baseAmount); if (boostedAmount == 0) { uint256[] memory tokenIds = shares[msg.sender].nftBoostTokenIds; IERC721 nftContract = IERC721(nftBoosterToken); for (uint256 i = 0; i < tokenIds.length; i++) { nftContract.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } delete shares[msg.sender].nftBoostTokenIds; } shareContract.transfer(msg.sender, finalWithdrawAmount); totalSharesDeposited = totalSharesDeposited.sub(baseAmount); totalSharesBoosted = totalSharesBoosted.sub(boostedAmountToUnstake); shares[msg.sender].amountBase -= baseAmount; shares[msg.sender].amount -= boostedAmountToUnstake; dividends[msg.sender][token].totalExcluded = getCumulativeDividends( token, shares[msg.sender].amount ); } // tokenAddress == address(0) means native token // any other token should be ERC20 listed on DEX router provided in constructor // // NOTE: Using this function will add tokens to the core rewards/dividends to be // distributed to all shareholders. However, to implement boosting, the token // should be directly transferred to this contract. Anything above and // beyond the totalDividends[tokenAddress] amount will be used for boosting. function depositDividends(address tokenAddress, uint256 erc20DirectAmount) external payable { require( erc20DirectAmount > 0 || msg.value > 0, 'value must be greater than 0' ); require( totalSharesBoosted > 0, 'must be shares deposited to be rewarded dividends' ); if (!tokenAwareness[tokenAddress]) { tokenAwareness[tokenAddress] = true; tokens.push(tokenAddress); } IERC20 token; uint256 amount; if (tokenAddress == address(0)) { payable(address(this)).call{ value: msg.value }(''); amount = msg.value; } else if (erc20DirectAmount > 0) { token = IERC20(tokenAddress); uint256 balanceBefore = token.balanceOf(address(this)); token.transferFrom(msg.sender, address(this), erc20DirectAmount); amount = token.balanceOf(address(this)).sub(balanceBefore); } else { token = IERC20(tokenAddress); uint256 balanceBefore = token.balanceOf(address(this)); address[] memory path = new address[](2); path[0] = wrappedNative; path[1] = tokenAddress; router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: msg.value }(0, path, address(this), block.timestamp); amount = token.balanceOf(address(this)).sub(balanceBefore); } totalDividends[tokenAddress] = totalDividends[tokenAddress].add(amount); dividendsPerShare[tokenAddress] = dividendsPerShare[tokenAddress].add( ACC_FACTOR.mul(amount).div(totalSharesBoosted) ); } function distributeDividend( address token, address shareholder, bool compound ) internal { if (shares[shareholder].amount == 0) { return; } uint256 amount = getUnpaidEarnings(token, shareholder); if (amount > 0) { totalDistributed[token] = totalDistributed[token].add(amount); // native transfer if (token == address(0)) { if (compound) { IERC20 shareToken = IERC20(shareholderToken); uint256 balBefore = shareToken.balanceOf(address(this)); address[] memory path = new address[](2); path[0] = wrappedNative; path[1] = shareholderToken; router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: amount }(0, path, address(this), block.timestamp); uint256 amountReceived = shareToken.balanceOf(address(this)).sub( balBefore ); if (amountReceived > 0) { uint256[] memory _empty = new uint256[](0); _stake(shareholder, token, amountReceived, _empty, true); } } else { payable(shareholder).call{ value: amount }(''); } } else { IERC20(token).transfer(shareholder, amount); } shareholderClaims[shareholder] = block.timestamp; dividends[shareholder][token].totalRealised = dividends[shareholder][ token ].totalRealised.add(amount); dividends[shareholder][token].totalExcluded = getCumulativeDividends( token, shares[shareholder].amount ); dividends[shareholder][token].lastClaim = block.timestamp; } } function claimDividend(address token, bool compound) external { distributeDividend(token, msg.sender, compound); } function getAppreciatedShares(uint256 amount) public view returns (uint256) { IERC20 shareContract = IERC20(shareholderToken); uint256 totalSharesBalance = shareContract.balanceOf(address(this)).sub( totalDividends[shareholderToken].sub(totalDistributed[shareholderToken]) ); uint256 appreciationRatio18 = totalSharesBalance.mul(10**18).div( totalSharesDeposited ); return amount.mul(appreciationRatio18).div(10**18); } function getDividendTokens() external view returns (address[] memory) { return tokens; } // getElevatedSharesWithBooster: // A + Ax = B // ------------------------ // getBaseSharesFromBoosted: // A + Ax = B // A(1 + x) = B // A = B/(1 + x) function getElevatedSharesWithBooster(address shareholder, uint256 baseAmount) internal view returns (uint256) { return eligibleForRewardBooster(shareholder) ? baseAmount.add( baseAmount.mul(getBoostMultiplier(shareholder)).div(10**2) ) : baseAmount; } function getBaseSharesFromBoosted(address shareholder, uint256 boostedAmount) public view returns (uint256) { uint256 multiplier = 10**18; return eligibleForRewardBooster(shareholder) ? boostedAmount.mul(multiplier).div( multiplier.add( multiplier.mul(getBoostMultiplier(shareholder)).div(10**2) ) ) : boostedAmount; } // NOTE: 2022-01-31 LW: new boost contract assumes OKLG and booster NFTs are staked in this contract function getBoostMultiplier(address wallet) public view returns (uint256) { return boostMultiplierContract == address(0) ? 0 : IMultiplier(boostMultiplierContract).getMultiplier(wallet); } // NOTE: 2022-01-31 LW: new boost contract assumes OKLG and booster NFTs are staked in this contract function eligibleForRewardBooster(address shareholder) public view returns (bool) { return boostContract != address(0) && IConditional(boostContract).passesTest(shareholder); } // returns the unpaid earnings function getUnpaidEarnings(address token, address shareholder) public view returns (uint256) { if (shares[shareholder].amount == 0) { return 0; } uint256 earnedDividends = getCumulativeDividends( token, shares[shareholder].amount ); uint256 dividendsExcluded = dividends[shareholder][token].totalExcluded; if (earnedDividends <= dividendsExcluded) { return 0; } return earnedDividends.sub(dividendsExcluded); } function getCumulativeDividends(address token, uint256 share) internal view returns (uint256) { return share.mul(dividendsPerShare[token]).div(ACC_FACTOR); } function getBaseShares(address user) external view returns (uint256) { return shares[user].amountBase; } function getShares(address user) external view returns (uint256) { return shares[user].amount; } function getBoostNfts(address user) external view returns (uint256[] memory) { return shares[user].nftBoostTokenIds; } function setShareholderToken(address _token) external onlyOwner { shareholderToken = _token; } function setBoostContract(address _contract) external onlyOwner { if (_contract != address(0)) { IConditional _contCheck = IConditional(_contract); // allow setting to zero address to effectively turn off check logic require( _contCheck.passesTest(address(0)) == true || _contCheck.passesTest(address(0)) == false, 'contract does not implement interface' ); } boostContract = _contract; } function setBoostMultiplierContract(address _contract) external onlyOwner { if (_contract != address(0)) { IMultiplier _contCheck = IMultiplier(_contract); // allow setting to zero address to effectively turn off check logic require( _contCheck.getMultiplier(address(0)) >= 0, 'contract does not implement interface' ); } boostMultiplierContract = _contract; } function withdrawNfts(address nftContractAddy, uint256[] memory _tokenIds) external onlyOwner { IERC721 nftContract = IERC721(nftContractAddy); for (uint256 i = 0; i < _tokenIds.length; i++) { nftContract.transferFrom(address(this), owner(), _tokenIds[i]); } } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import './OKLGProduct.sol'; /** * @title OKLGTrustedTimestamping * @dev Stores SHA256 data hashes for trusted timestamping implementations. */ contract OKLGTrustedTimestamping is OKLGProduct { struct DataHash { bytes32 dataHash; uint256 time; string fileName; uint256 fileSizeBytes; } struct Address { address addy; uint256 time; } uint256 public totalNumberHashesStored; mapping(address => DataHash[]) public addressHashes; mapping(bytes32 => Address[]) public fileHashesToAddress; event StoreHash(address from, bytes32 dataHash); constructor(address _tokenAddress, address _pendAddress) OKLGProduct(uint8(3), _tokenAddress, _pendAddress) {} /** * @dev Process transaction and store hash in blockchain */ function storeHash( bytes32 dataHash, string memory fileName, uint256 fileSizeBytes ) external payable { _payForService(0); uint256 theTimeNow = block.timestamp; addressHashes[msg.sender].push( DataHash({ dataHash: dataHash, time: theTimeNow, fileName: fileName, fileSizeBytes: fileSizeBytes }) ); fileHashesToAddress[dataHash].push( Address({ addy: msg.sender, time: theTimeNow }) ); totalNumberHashesStored++; emit StoreHash(msg.sender, dataHash); } function getHashesForAddress(address _userAddy) external view returns (DataHash[] memory) { return addressHashes[_userAddy]; } function getAddressesForHash(bytes32 dataHash) external view returns (Address[] memory) { return fileHashesToAddress[dataHash]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import './OKLGWithdrawable.sol'; /** * @title OKLGAffiliate * @dev Support affiliate logic */ contract OKLGAffiliate is OKLGWithdrawable { modifier onlyAffiliateOrOwner() { require( msg.sender == owner() || affiliates[msg.sender] > 0, 'caller must be affiliate or owner' ); _; } uint16 public constant PERCENT_DENOMENATOR = 10000; address public paymentWallet = 0x0000000000000000000000000000000000000000; mapping(address => uint256) public affiliates; // value is percentage of fees for affiliate (denomenator of 10000) mapping(address => uint256) public discounts; // value is percentage off for user (denomenator of 10000) event AddAffiliate(address indexed wallet, uint256 percent); event RemoveAffiliate(address indexed wallet); event AddDiscount(address indexed wallet, uint256 percent); event RemoveDiscount(address indexed wallet); event Pay(address indexed payee, uint256 amount); function pay( address _caller, address _referrer, uint256 _basePrice ) internal { uint256 price = getFinalPrice(_caller, _basePrice); require(msg.value >= price, 'not enough ETH to pay'); // affiliate fee if applicable if (affiliates[_referrer] > 0) { uint256 referrerFee = (price * affiliates[_referrer]) / PERCENT_DENOMENATOR; (bool sent, ) = payable(_referrer).call{ value: referrerFee }(''); require(sent, 'affiliate payment did not go through'); price -= referrerFee; } // if affiliate does not take everything, send normal payment if (price > 0) { address wallet = paymentWallet == address(0) ? owner() : paymentWallet; (bool sent, ) = payable(wallet).call{ value: price }(''); require(sent, 'main payment did not go through'); } emit Pay(msg.sender, _basePrice); } function getFinalPrice(address _caller, uint256 _basePrice) public view returns (uint256) { if (discounts[_caller] > 0) { return _basePrice - ((_basePrice * discounts[_caller]) / PERCENT_DENOMENATOR); } return _basePrice; } function addDiscount(address _wallet, uint256 _percent) external onlyAffiliateOrOwner { require( _percent <= PERCENT_DENOMENATOR, 'cannot have more than 100% discount' ); discounts[_wallet] = _percent; emit AddDiscount(_wallet, _percent); } function removeDiscount(address _wallet) external onlyAffiliateOrOwner { require(discounts[_wallet] > 0, 'affiliate must exist'); delete discounts[_wallet]; emit RemoveDiscount(_wallet); } function addAffiliate(address _wallet, uint256 _percent) external onlyOwner { require( _percent <= PERCENT_DENOMENATOR, 'cannot have more than 100% referral fee' ); affiliates[_wallet] = _percent; emit AddAffiliate(_wallet, _percent); } function removeAffiliate(address _wallet) external onlyOwner { require(affiliates[_wallet] > 0, 'affiliate must exist'); delete affiliates[_wallet]; emit RemoveAffiliate(_wallet); } function setPaymentWallet(address _wallet) external onlyOwner { paymentWallet = _wallet; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import './OKLGProduct.sol'; interface IERC20Decimals is IERC20 { function decimals() external view returns (uint8); } /** * @title OKLGAtomicSwapInstance * @dev This is the main contract that supports holding metadata for OKLG atomic inter and intrachain swapping */ contract OKLGAtomicSwapInstance is OKLGProduct { IERC20Decimals private _token; address public tokenOwner; address payable public oracleAddress; uint256 public maxSwapAmount; uint8 public targetTokenDecimals; uint256 public minimumGasForOperation = 2 * 10**15; // 2 finney (0.002 ETH) bool public isActive = true; struct Swap { bytes32 id; uint256 origTimestamp; uint256 currentTimestamp; bool isOutbound; bool isComplete; bool isRefunded; bool isRefundable; bool isSendGasFunded; address swapAddress; uint256 amount; } mapping(bytes32 => Swap) public swaps; mapping(address => Swap) public lastUserSwap; event ReceiveTokensFromSource( bytes32 indexed id, uint256 origTimestamp, address sender, uint256 amount ); event SendTokensToDestination( bytes32 indexed id, address receiver, uint256 amount ); event RefundTokensToSource( bytes32 indexed id, address sender, uint256 amount ); event TokenOwnerUpdated(address previousOwner, address newOwner); constructor( address _costToken, address _spendAddress, address _oracleAddress, address _tokenOwner, address _tokenAddy, uint8 _targetTokenDecimals, uint256 _maxSwapAmount ) OKLGProduct(uint8(7), _costToken, _spendAddress) { oracleAddress = payable(_oracleAddress); tokenOwner = _tokenOwner; maxSwapAmount = _maxSwapAmount; targetTokenDecimals = _targetTokenDecimals; _token = IERC20Decimals(_tokenAddy); } function getSwapTokenAddress() external view returns (address) { return address(_token); } function setActiveState(bool _isActive) external { require( msg.sender == owner() || msg.sender == tokenOwner, 'setActiveState user must be contract creator' ); isActive = _isActive; } function setOracleAddress(address _oracleAddress) external onlyOwner { oracleAddress = payable(_oracleAddress); transferOwnership(oracleAddress); } function setTargetTokenDecimals(uint8 _decimals) external onlyOwner { targetTokenDecimals = _decimals; } function setTokenOwner(address newOwner) external { require( msg.sender == tokenOwner, 'user must be current token owner to change it' ); address previousOwner = tokenOwner; tokenOwner = newOwner; emit TokenOwnerUpdated(previousOwner, newOwner); } function withdrawTokens(uint256 _amount) external { require( msg.sender == tokenOwner, 'withdrawTokens user must be token owner' ); _token.transfer(msg.sender, _amount); } function setSwapCompletionStatus(bytes32 _id, bool _isComplete) external onlyOwner { swaps[_id].isComplete = _isComplete; } function setMinimumGasForOperation(uint256 _amountGas) external onlyOwner { minimumGasForOperation = _amountGas; } function receiveTokensFromSource(uint256 _amount) external payable returns (bytes32, uint256) { require(isActive, 'this atomic swap instance is not active'); require( msg.value >= minimumGasForOperation, 'you must also send enough gas to cover the target transaction' ); require( maxSwapAmount == 0 || _amount <= maxSwapAmount, 'trying to send more than maxSwapAmount' ); _payForService(minimumGasForOperation); if (minimumGasForOperation > 0) { oracleAddress.call{ value: minimumGasForOperation }(''); } _token.transferFrom(msg.sender, address(this), _amount); uint256 _ts = block.timestamp; bytes32 _id = sha256(abi.encodePacked(msg.sender, _ts, _amount)); swaps[_id] = Swap({ id: _id, origTimestamp: _ts, currentTimestamp: _ts, isOutbound: false, isComplete: false, isRefunded: false, isRefundable: true, isSendGasFunded: false, swapAddress: msg.sender, amount: _amount }); lastUserSwap[msg.sender] = swaps[_id]; emit ReceiveTokensFromSource(_id, _ts, msg.sender, _amount); return (_id, _ts); } function unsetLastUserSwap(address _addy) external onlyOwner { delete lastUserSwap[_addy]; } // msg.sender must be the user who originally created the swap. // Otherwise, the unique identifier will not match from the originally // sending txn. // // NOTE: We're aware this function can be spoofed by creating a sha256 hash of msg.sender's address // and _origTimestamp, but it's important to note refundTokensFromSource and sendTokensToDestination // can only be executed by the owner/oracle. Therefore validation should be done by the oracle before // executing those and the only possibility of a vulnerability is if someone has compromised the oracle account. function fundSendToDestinationGas( bytes32 _id, uint256 _origTimestamp, uint256 _amount ) external payable { require( msg.value >= minimumGasForOperation, 'you must send enough gas to cover the send transaction' ); require( _id == sha256(abi.encodePacked(msg.sender, _origTimestamp, _amount)), 'we do not recognize this swap' ); require(!swaps[_id].isSendGasFunded, 'cannot fund swap again'); if (minimumGasForOperation > 0) { oracleAddress.call{ value: minimumGasForOperation }(''); } swaps[_id] = Swap({ id: _id, origTimestamp: _origTimestamp, currentTimestamp: block.timestamp, isOutbound: true, isComplete: swaps[_id].isComplete, isRefunded: swaps[_id].isRefunded, isRefundable: swaps[_id].isRefundable, isSendGasFunded: true, swapAddress: msg.sender, amount: _amount }); } // This must be called AFTER fundSendToDestinationGas has been executed // for this txn to fund this send operation function refundTokensFromSource(bytes32 _id) external { require(isActive, 'this atomic swap instance is not active'); Swap storage swap = swaps[_id]; require( swap.isRefundable, 'swap must have been initiated from this chain in order to refund' ); _confirmSwapExistsGasFundedAndSenderValid(swap); swap.isRefunded = true; _token.transfer(swap.swapAddress, swap.amount); emit RefundTokensToSource(_id, swap.swapAddress, swap.amount); } // This must be called AFTER fundSendToDestinationGas has been executed // for this txn to fund this send operation function sendTokensToDestination(bytes32 _id) external returns (bytes32) { require(isActive, 'this atomic swap instance is not active'); Swap storage swap = swaps[_id]; _confirmSwapExistsGasFundedAndSenderValid(swap); // handle if this token and target chain token in bridge have different decimals // current decimals = 9 -- 100 tokens == 100000000000 // target decimals = 18 -- 100 tokens == 100000000000000000000 // to get current amount to transfer, need to multiply by ratio of 10^currentDecimals / 10^targetDecimals uint256 _swapAmount = swap.amount; if (targetTokenDecimals > 0) { _swapAmount = (_swapAmount * 10**_token.decimals()) / 10**targetTokenDecimals; } _token.transfer(swap.swapAddress, _swapAmount); swap.currentTimestamp = block.timestamp; swap.isComplete = true; emit SendTokensToDestination(_id, swap.swapAddress, _swapAmount); return _id; } function _confirmSwapExistsGasFundedAndSenderValid(Swap memory swap) private view onlyOwner { // functions that call this should only be called by the current owner // or oracle address as they will do the appropriate validation beforehand // to confirm the receiving swap is valid before sending tokens to the user. require( swap.origTimestamp > 0 && swap.amount > 0, 'swap does not exist yet.' ); // We're just validating here that the swap has not been // completed and gas has been funded before moving forward. require( !swap.isComplete && !swap.isRefunded && swap.isSendGasFunded, 'swap has already been completed, refunded, or gas has not been funded' ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; interface IKetherNFT { function ownerOf(uint256 _tokenId) external view returns (address); function transferFrom( address _from, address _to, uint256 _tokenId ) external payable; function publish( uint256 _idx, string calldata _link, string calldata _image, string calldata _title, bool _NSFW ) external; } /** * @title KetherNFTLoaner * @dev Support loaning KetherNFT plots of ad space to others over a period of time */ contract KetherNFTLoaner is Ownable { using SafeMath for uint256; uint256 private constant _1ETH = 1 ether; uint256 public loanServiceCharge = _1ETH.div(100).mul(5); uint256 public loanChargePerDay = _1ETH.div(1000); uint16 public maxLoanDurationDays = 30; uint8 public loanPercentageCharge = 10; IKetherNFT private _ketherNft; struct PlotOwner { address owner; uint256 overrideLoanChargePerDay; uint16 overrideMaxLoanDurationDays; uint256 totalFeesCollected; } struct PlotLoan { address loaner; uint256 start; uint256 end; uint256 totalFee; } struct PublishParams { string link; string image; string title; bool NSFW; } mapping(uint256 => PlotOwner) public owners; mapping(uint256 => PlotLoan) public loans; event AddPlot( uint256 indexed idx, address owner, uint256 overridePerDayCharge, uint16 overrideMaxLoanDays ); event UpdatePlot( uint256 indexed idx, uint256 overridePerDayCharge, uint16 overrideMaxLoanDays ); event RemovePlot(uint256 indexed idx, address owner); event LoanPlot(uint256 indexed idx, address loaner); event Transfer(address to, uint256 idx); constructor(address _ketherNFTAddress) { _ketherNft = IKetherNFT(_ketherNFTAddress); } function addPlot( uint256 _idx, uint256 _overridePerDayCharge, uint16 _overrideMaxDays ) external payable { require( msg.sender == _ketherNft.ownerOf(_idx), 'You need to be the owner of the plot to loan it out.' ); require( msg.value >= loanServiceCharge, 'You must send the appropriate service charge to support loaning your plot.' ); payable(owner()).call{ value: msg.value }(''); _ketherNft.transferFrom(msg.sender, address(this), _idx); owners[_idx] = PlotOwner({ owner: msg.sender, overrideLoanChargePerDay: _overridePerDayCharge, overrideMaxLoanDurationDays: _overrideMaxDays, totalFeesCollected: 0 }); emit AddPlot(_idx, msg.sender, _overridePerDayCharge, _overrideMaxDays); } function updatePlot( uint256 _idx, uint256 _overridePerDayCharge, uint16 _overrideMaxDays ) external { PlotOwner storage _owner = owners[_idx]; require( msg.sender == _owner.owner, 'You must be the plot owner to update information about it.' ); _owner.overrideLoanChargePerDay = _overridePerDayCharge; _owner.overrideMaxLoanDurationDays = _overrideMaxDays; emit UpdatePlot(_idx, _overridePerDayCharge, _overrideMaxDays); } function removePlot(uint256 _idx) external payable { address _owner = owners[_idx].owner; require( msg.sender == _owner, 'You must be the original owner of the plot to remove it from the loan contract.' ); // If there is an active loan, make sure the owner of the plot who's removing pays the loaner // back a the full amount of the original loan fee for breaking the loan agreement if (hasActiveLoan(_idx)) { PlotLoan storage _loan = loans[_idx]; uint256 _loanFee = _loan.totalFee; require( msg.value >= _loanFee, 'You need to reimburse the loaner for breaking the loan agreement early.' ); payable(_loan.loaner).call{ value: _loanFee }(''); _loan.end = 0; } _ketherNft.transferFrom(address(this), msg.sender, _idx); emit RemovePlot(_idx, msg.sender); } function loanPlot( uint256 _idx, uint16 _numDays, PublishParams memory _publishParams ) external payable { require(_numDays > 0, 'You must loan the plot for at least a day.'); PlotOwner storage _plotOwner = owners[_idx]; PlotLoan memory _loan = loans[_idx]; require(_loan.end < block.timestamp, 'Plot is currently being loaned.'); _ensureValidLoanDays(_plotOwner, _numDays); _ensureValidLoanCharge(_plotOwner, _numDays); uint256 _serviceCharge = msg.value.mul(uint256(loanPercentageCharge)).div( 100 ); uint256 _plotOwnerCharge = msg.value.sub(_serviceCharge); payable(owner()).call{ value: _serviceCharge }(''); payable(_plotOwner.owner).call{ value: _plotOwnerCharge }(''); _plotOwner.totalFeesCollected += _plotOwnerCharge; loans[_idx] = PlotLoan({ loaner: msg.sender, start: block.timestamp, end: block.timestamp.add(_daysToSeconds(_numDays)), totalFee: msg.value }); _publish(_idx, _publishParams); emit LoanPlot(_idx, msg.sender); } function publish(uint256 _idx, PublishParams memory _publishParams) external { PlotOwner memory _owner = owners[_idx]; PlotLoan memory _loan = loans[_idx]; bool _hasActiveLoan = hasActiveLoan(_idx); if (_hasActiveLoan) { require( msg.sender == _loan.loaner, 'Must be the current loaner to update published information.' ); } else { require( msg.sender == _owner.owner, 'Must be the owner to update published information.' ); } _publish(_idx, _publishParams); } function transfer(address _to, uint256 _idx) external { PlotOwner storage _owner = owners[_idx]; require( msg.sender == _owner.owner, 'You must own the current plot to transfer it.' ); _owner.owner = _to; emit Transfer(_to, _idx); } function hasActiveLoan(uint256 _idx) public view returns (bool) { PlotLoan memory _loan = loans[_idx]; if (_loan.loaner == address(0)) { return false; } return _loan.end > block.timestamp; } function setLoanServiceCharge(uint256 _amountWei) external onlyOwner { loanServiceCharge = _amountWei; } function setLoanChargePerDay(uint256 _amountWei) external onlyOwner { loanChargePerDay = _amountWei; } function setMaxLoanDurationDays(uint16 _numDays) external onlyOwner { maxLoanDurationDays = _numDays; } function setLoanPercentageCharge(uint8 _percentage) external onlyOwner { require(_percentage <= 100, 'Must be between 0 and 100'); loanPercentageCharge = _percentage; } function _daysToSeconds(uint256 _days) private pure returns (uint256) { return _days.mul(24).mul(60).mul(60); } function _ensureValidLoanDays(PlotOwner memory _owner, uint16 _numDays) private view { uint16 _maxNumDays = _owner.overrideMaxLoanDurationDays > 0 ? _owner.overrideMaxLoanDurationDays : maxLoanDurationDays; require( _numDays <= _maxNumDays, 'You cannot loan this plot for this long.' ); } function _ensureValidLoanCharge(PlotOwner memory _owner, uint16 _numDays) private view { uint256 _perDayCharge = _owner.overrideLoanChargePerDay > 0 ? _owner.overrideLoanChargePerDay : loanChargePerDay; uint256 _loanCharge = _perDayCharge.mul(uint256(_numDays)); require( msg.value >= _loanCharge, 'Make sure you send the appropriate amount of ETH to process your loan.' ); } function _publish(uint256 _idx, PublishParams memory _publishParams) private { _ketherNft.publish( _idx, _publishParams.link, _publishParams.image, _publishParams.title, _publishParams.NSFW ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @title OKLGAtomicSwapInstHash * @dev Hash an address, timestamp, amount like that happens in OKLGAtomicSwapInstance.sol */ contract OKLGAtomicSwapInstHash { function hash( address _addy, uint256 _ts, uint256 _amount ) external pure returns (bytes32) { return sha256(abi.encodePacked(_addy, _ts, _amount)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import './interfaces/IERC721Helpers.sol'; import './utils/Counters.sol'; /** * ok.lets.ape. NFT contract */ contract OKLetsApe is Ownable, ERC721Burnable, ERC721Enumerable, ERC721Pausable { using SafeMath for uint256; using Strings for uint256; using Counters for Counters.Counter; // Token id counter Counters.Counter private _tokenIds; // Sale round counters Counters.Counter public _preSaleRound; Counters.Counter public _publicSaleRound; // Mints per sale round counter Counters.Counter public _tokensMintedPerSaleRound; // Base token uri string private baseTokenURI; // baseTokenURI can point to IPFS folder like https://ipfs.io/ipfs/{cid}/ // Payment address address private paymentAddress; // Royalties address address private royaltyAddress; // Royalties basis points (percentage using 2 decimals - 10000 = 100, 0 = 0) uint256 private royaltyBasisPoints = 1000; // 10% // Token info string public constant TOKEN_NAME = 'ok.lets.ape.'; string public constant TOKEN_SYMBOL = 'OKLApe'; uint256 public constant TOTAL_TOKENS = 10000; // Mint cost and max per wallet uint256 public mintCost = 0.0542069 ether; // Mint cost contract address public mintCostContract; // Max wallet amount uint256 public maxWalletAmount = 10; // Amount of tokens to mint before automatically stopping public sale uint256 public maxMintsPerSaleRound = 1000; // Pre sale/Public sale active bool public preSaleActive; bool public publicSaleActive; // Presale whitelist mapping(address => bool) public presaleWhitelist; // Authorized addresses mapping(address => bool) public authorizedAddresses; //-- Events --// event RoyaltyBasisPoints(uint256 indexed _royaltyBasisPoints); //-- Modifiers --// // Public sale active modifier modifier whenPreSaleActive() { require(preSaleActive, 'Pre sale is not active'); _; } // Public sale active modifier modifier whenPublicSaleActive() { require(publicSaleActive, 'Public sale is not active'); _; } // Owner or public sale active modifier modifier whenOwnerOrSaleActive() { require( owner() == _msgSender() || preSaleActive || publicSaleActive, 'Sale is not active' ); _; } // Owner or authorized addresses modifier modifier whenOwnerOrAuthorizedAddress() { require( owner() == _msgSender() || authorizedAddresses[_msgSender()], 'Not authorized' ); _; } // -- Constructor --// constructor(string memory _baseTokenURI, uint8 _counterType) ERC721(TOKEN_NAME, TOKEN_SYMBOL) { baseTokenURI = _baseTokenURI; paymentAddress = owner(); royaltyAddress = owner(); _tokenIds.setType(_counterType); } // -- External Functions -- // // Start pre sale function startPreSale() external onlyOwner { _preSaleRound.increment(); _tokensMintedPerSaleRound.reset(); preSaleActive = true; publicSaleActive = false; } // End pre sale function endPreSale() external onlyOwner { preSaleActive = false; publicSaleActive = false; } // Start public sale function startPublicSale() external onlyOwner { _publicSaleRound.increment(); _tokensMintedPerSaleRound.reset(); preSaleActive = false; publicSaleActive = true; } // End public sale function endPublicSale() external onlyOwner { preSaleActive = false; publicSaleActive = false; } // Support royalty info - See {EIP-2981}: https://eips.ethereum.org/EIPS/eip-2981 function royaltyInfo(uint256, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { return (royaltyAddress, (_salePrice.mul(royaltyBasisPoints)).div(10000)); } // Adds multiple addresses to whitelist function addToPresaleWhitelist(address[] memory _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { address _address = _addresses[i]; presaleWhitelist[_address] = true; } } // Removes multiple addresses from whitelist function removeFromPresaleWhitelist(address[] memory _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { address _address = _addresses[i]; presaleWhitelist[_address] = false; } } // Mint token - requires amount function mint(uint256 _amount) external payable whenOwnerOrSaleActive { require(_amount > 0, 'Must mint at least one'); // Check there enough mints left to mint require(_amount <= getMintsLeft(), 'Minting would exceed max supply'); // Check there are mints left per sale round require( _amount <= getMintsLeftPerSaleRound(), 'Minting would exceed max mint amount per sale round' ); // Set cost to mint uint256 costToMint = 0; bool isOwner = owner() == _msgSender(); if (!isOwner) { // If pre sale is active, make sure user is on whitelist if (preSaleActive) { require(presaleWhitelist[_msgSender()], 'Must be on whitelist'); } // Set cost to mint costToMint = getMintCost(_msgSender()) * _amount; // Get current address total balance uint256 currentWalletAmount = super.balanceOf(_msgSender()); // Check current token amount and mint amount is not more than max wallet amount require( currentWalletAmount.add(_amount) <= maxWalletAmount, 'Requested amount exceeds maximum mint amount per wallet' ); } // Check cost to mint, and if enough ETH is passed to mint require(costToMint <= msg.value, 'ETH amount sent is not correct'); for (uint256 i = 0; i < _amount; i++) { // Increment token id _tokenIds.increment(); // Safe mint _safeMint(_msgSender(), _tokenIds.current()); // Increment tokens minted per sale round _tokensMintedPerSaleRound.increment(); } // Send mint cost to payment address Address.sendValue(payable(paymentAddress), costToMint); // Return unused value if (msg.value > costToMint) { Address.sendValue(payable(_msgSender()), msg.value.sub(costToMint)); } // If tokens minted per sale round hits the max mints per sale round, end pre/public sale if (_tokensMintedPerSaleRound.current() >= maxMintsPerSaleRound) { preSaleActive = false; publicSaleActive = false; } } // Custom mint function - requires token id and reciever address // Mint or transfer token id - Used for cross chain bridging function customMint(uint256 _tokenId, address _reciever) external whenOwnerOrAuthorizedAddress { require(!publicSaleActive && !preSaleActive, 'Sales must be inactive'); require( _tokenId > 0 && _tokenId <= TOTAL_TOKENS, 'Must pass valid token id' ); if (_exists(_tokenId)) { // If token exists, make sure token owner is contract owner require(owner() == ownerOf(_tokenId), 'Token is already owned'); // Transfer from contract owner to reciever safeTransferFrom(owner(), _reciever, _tokenId); } else { require( _tokenIds.current() > _tokenId, 'Cannot custom mint NFT if it is still in line for standard mint' ); // Safe mint _safeMint(_reciever, _tokenId); } } // Custom burn function - required token id // Transfer token id to contract owner - used for cross chain bridging function customBurn(uint256 _tokenId) external whenOwnerOrAuthorizedAddress { require(!publicSaleActive && !preSaleActive, 'Sales must be inactive'); require( _tokenId > 0 && _tokenId <= TOTAL_TOKENS, 'Must pass valid token id' ); require(_exists(_tokenId), 'Nonexistent token'); // Transfer from token owner to contract owner safeTransferFrom(ownerOf(_tokenId), owner(), _tokenId); } // Adds multiple addresses to authorized addresses function addToAuthorizedAddresses(address[] memory _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { address _address = _addresses[i]; authorizedAddresses[_address] = true; } } // Removes multiple addresses from authorized addresses function removeFromAuthorizedAddresses(address[] memory _addresses) external onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { address _address = _addresses[i]; authorizedAddresses[_address] = false; } } // Set mint cost function setMintCost(uint256 _cost) external onlyOwner { mintCost = _cost; } // Set mint cost contract function setERC721HelperContract(address _contract) external onlyOwner { if (_contract != address(0)) { IERC721Helpers _contCheck = IERC721Helpers(_contract); // allow setting to zero address to effectively turn off logic require( _contCheck.getMintCost(_msgSender()) == 0 || _contCheck.getMintCost(_msgSender()) > 0, 'Contract does not implement interface' ); } mintCostContract = _contract; } // Set max wallet amount function setMaxWalletAmount(uint256 _amount) external onlyOwner { maxWalletAmount = _amount; } // Set max mints per sale round amount function setMaxMintsPerSaleRound(uint256 _amount) external onlyOwner { maxMintsPerSaleRound = _amount; } // Reset tokens minted per sale round function resetTokensMintedPerSaleRound() external onlyOwner { _tokensMintedPerSaleRound.reset(); } // Reset pre sale rounds function resetPreSaleRounds() external onlyOwner { _preSaleRound.reset(); } // Reset public sale rounds function resetPublicSaleRounds() external onlyOwner { _publicSaleRound.reset(); } // Set payment address function setPaymentAddress(address _address) external onlyOwner { paymentAddress = _address; } // Set royalty wallet address function setRoyaltyAddress(address _address) external onlyOwner { royaltyAddress = _address; } // Set royalty basis points function setRoyaltyBasisPoints(uint256 _basisPoints) external onlyOwner { royaltyBasisPoints = _basisPoints; emit RoyaltyBasisPoints(_basisPoints); } // Set base URI function setBaseURI(string memory _uri) external onlyOwner { baseTokenURI = _uri; } //-- Public Functions --// // Get mint cost from mint cost contract, or fallback to local mintCost function getMintCost(address _address) public view returns (uint256) { return mintCostContract != address(0) ? IERC721Helpers(mintCostContract).getMintCost(_address) : mintCost; } // Get mints left function getMintsLeft() public view returns (uint256) { uint256 currentSupply = super.totalSupply(); uint256 counterType = _tokenIds._type; uint256 totalTokens = counterType != 0 ? TOTAL_TOKENS.div(2) : TOTAL_TOKENS; return totalTokens.sub(currentSupply); } // Get mints left per sale round function getMintsLeftPerSaleRound() public view returns (uint256) { return maxMintsPerSaleRound.sub(_tokensMintedPerSaleRound.current()); } // Get circulating supply - current supply minus contract owner supply function getCirculatingSupply() public view returns (uint256) { uint256 currentSupply = super.totalSupply(); uint256 ownerSupply = balanceOf(owner()); return currentSupply.sub(ownerSupply); } // Get total tokens based on counter type function getTotalTokens() public view returns (uint256) { uint256 counterType = _tokenIds._type; uint256 totalTokens = counterType != 0 ? TOTAL_TOKENS.div(2) : TOTAL_TOKENS; return totalTokens; } // Token URI (baseTokenURI + tokenId) function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), 'Nonexistent token'); return string(abi.encodePacked(_baseURI(), _tokenId.toString(), '.json')); } // Contract metadata URI - Support for OpenSea: https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return string(abi.encodePacked(_baseURI(), 'contract.json')); } // Override supportsInterface - See {IERC165-supportsInterface} function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(_interfaceId); } // Pauses all token transfers - See {ERC721Pausable} function pause() external virtual onlyOwner { _pause(); } // Unpauses all token transfers - See {ERC721Pausable} function unpause() external virtual onlyOwner { _unpause(); } //-- Internal Functions --// // Get base URI function _baseURI() internal view override returns (string memory) { return baseTokenURI; } // Before all token transfer function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(_from, _to, _tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import './OKLGProduct.sol'; import './OKLGAtomicSwapInstance.sol'; /** * @title OKLGAtomicSwap * @dev This is the main contract that supports holding metadata for OKLG atomic inter and intrachain swapping */ contract OKLGAtomicSwap is OKLGProduct { struct TargetSwapInfo { bytes32 id; uint256 timestamp; uint256 index; address creator; address sourceContract; string targetNetwork; address targetContract; uint8 targetDecimals; bool isActive; } uint256 public swapCreationGasLoadAmount = 1 * 10**16; // 10 finney (0.01 ether) address payable public oracleAddress; // mapping with "0xSourceContractInstance" => targetContractInstanceInfo that // our oracle can query and get the target network contract as needed. TargetSwapInfo[] public targetSwapContracts; mapping(address => TargetSwapInfo) public targetSwapContractsIndexed; mapping(address => TargetSwapInfo) private lastUserCreatedContract; // event CreateSwapContract( // uint256 timestamp, // address contractAddress, // string targetNetwork, // address indexed targetContract, // address creator // ); constructor( address _tokenAddress, address _spendAddress, address _oracleAddress ) OKLGProduct(uint8(6), _tokenAddress, _spendAddress) { oracleAddress = payable(_oracleAddress); } function updateSwapCreationGasLoadAmount(uint256 _amount) external onlyOwner { swapCreationGasLoadAmount = _amount; } function getLastCreatedContract(address _addy) external view returns (TargetSwapInfo memory) { return lastUserCreatedContract[_addy]; } function setOracleAddress( address _oracleAddress, bool _changeAll, uint256 _start, uint256 _max ) external onlyOwner { oracleAddress = payable(_oracleAddress); if (_changeAll) { uint256 _index = 0; uint256 _numLoops = _max > 0 ? _max : 50; // SWC-DoS With Block Gas Limit: L73 - L79 while (_index + _start < _start + _numLoops) { OKLGAtomicSwapInstance _contract = OKLGAtomicSwapInstance( targetSwapContracts[_start].sourceContract ); _contract.setOracleAddress(oracleAddress); _index++; } } } function getAllSwapContracts() external view returns (TargetSwapInfo[] memory) { return targetSwapContracts; } function updateSwapContract( uint256 _createdBlockTimestamp, address _sourceContract, string memory _targetNetwork, address _targetContract, uint8 _targetDecimals, bool _isActive ) external { TargetSwapInfo storage swapContInd = targetSwapContractsIndexed[ _sourceContract ]; TargetSwapInfo storage swapCont = targetSwapContracts[swapContInd.index]; require( msg.sender == owner() || msg.sender == swapCont.creator || msg.sender == oracleAddress, 'updateSwapContract must be contract creator' ); bytes32 _id = sha256( abi.encodePacked(swapCont.creator, _createdBlockTimestamp) ); require( address(0) != _targetContract, 'target contract cannot be 0 address' ); require( swapCont.id == _id && swapContInd.id == _id, "we don't recognize the info you sent with the swap" ); swapCont.targetNetwork = _targetNetwork; swapContInd.targetNetwork = swapCont.targetNetwork; swapCont.targetContract = _targetContract; swapContInd.targetContract = swapCont.targetContract; swapCont.targetDecimals = _targetDecimals; swapContInd.targetDecimals = swapCont.targetDecimals; // TODO: if the decimals are changed from the original execution, // should also execute #setTargetTokenDecimals on the instance contract. swapCont.isActive = _isActive; swapContInd.isActive = swapCont.isActive; } function createNewAtomicSwapContract( address _tokenAddy, uint256 _tokenSupply, uint256 _maxSwapAmount, string memory _targetNetwork, address _targetContract, uint8 _targetDecimals ) external payable returns (uint256, address) { _payForService(swapCreationGasLoadAmount); oracleAddress.call{ value: swapCreationGasLoadAmount }(''); IERC20 _token = IERC20(_tokenAddy); OKLGAtomicSwapInstance _contract = new OKLGAtomicSwapInstance( getTokenAddress(), getSpendAddress(), oracleAddress, msg.sender, _tokenAddy, _targetDecimals, _maxSwapAmount ); if (_tokenSupply > 0) { _token.transferFrom(msg.sender, address(_contract), _tokenSupply); } _contract.transferOwnership(oracleAddress); uint256 _ts = block.timestamp; TargetSwapInfo memory newContract = TargetSwapInfo({ id: sha256(abi.encodePacked(msg.sender, _ts)), timestamp: _ts, index: targetSwapContracts.length, creator: msg.sender, sourceContract: address(_contract), targetNetwork: _targetNetwork, targetContract: _targetContract, targetDecimals: _targetDecimals, isActive: true }); targetSwapContracts.push(newContract); targetSwapContractsIndexed[address(_contract)] = newContract; lastUserCreatedContract[msg.sender] = newContract; // emit CreateSwapContract( // _ts, // address(_contract), // _targetNetwork, // _targetContract, // msg.sender // ); return (_ts, address(_contract)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import '@openzeppelin/contracts/interfaces/IERC721.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; /** * @title OKLGFaaSToken (sOKLG) * @notice Represents a contract where a token owner has put her tokens up for others to stake and earn said tokens. */ contract OKLGFaaSToken is ERC20 { using SafeMath for uint256; bool public contractIsRemoved = false; IERC20 private _rewardsToken; IERC20 private _stakedERC20; IERC721 private _stakedERC721; PoolInfo public pool; address private constant _burner = 0x000000000000000000000000000000000000dEaD; struct PoolInfo { address creator; // address of contract creator address tokenOwner; // address of original rewards token owner uint256 origTotSupply; // supply of rewards tokens put up to be rewarded by original owner uint256 curRewardsSupply; // current supply of rewards uint256 totalTokensStaked; // current amount of tokens staked uint256 creationBlock; // block this contract was created uint256 perBlockNum; // amount of rewards tokens rewarded per block uint256 lockedUntilDate; // unix timestamp of how long this contract is locked and can't be changed // uint256 allocPoint; // How many allocation points assigned to this pool. ERC20s to distribute per block. uint256 lastRewardBlock; // Last block number that ERC20s distribution occurs. uint256 accERC20PerShare; // Accumulated ERC20s per share, times 1e36. uint256 stakeTimeLockSec; // number of seconds after depositing the user is required to stake before unstaking bool isStakedNft; } struct StakerInfo { uint256 amountStaked; uint256 blockOriginallyStaked; // block the user originally staked uint256 timeOriginallyStaked; // unix timestamp in seconds that the user originally staked uint256 blockLastHarvested; // the block the user last claimed/harvested rewards uint256 rewardDebt; // Reward debt. See explanation below. uint256[] nftTokenIds; // if this is an NFT staking pool, make sure we store the token IDs here } struct BlockTokenTotal { uint256 blockNumber; uint256 totalTokens; } // mapping of userAddresses => tokenAddresses that can // can be evaluated to determine for a particular user which tokens // they are staking. mapping(address => StakerInfo) public stakers; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); /** * @notice The constructor for the Staking Token. * @param _name Name of the staking token * @param _symbol Name of the staking token symbol * @param _rewardSupply The amount of tokens to mint on construction, this should be the same as the tokens provided by the creating user. * @param _rewardsTokenAddy Contract address of token to be rewarded to users * @param _stakedTokenAddy Contract address of token to be staked by users * @param _originalTokenOwner Address of user putting up staking tokens to be staked * @param _perBlockAmount Amount of tokens to be rewarded per block * @param _lockedUntilDate Unix timestamp that the staked tokens will be locked. 0 means locked forever until all tokens are staked * @param _stakeTimeLockSec number of seconds a user is required to stake, or 0 if none * @param _isStakedNft is this an NFT staking pool */ constructor( string memory _name, string memory _symbol, uint256 _rewardSupply, address _rewardsTokenAddy, address _stakedTokenAddy, address _originalTokenOwner, uint256 _perBlockAmount, uint256 _lockedUntilDate, uint256 _stakeTimeLockSec, bool _isStakedNft ) ERC20(_name, _symbol) { require( _perBlockAmount > uint256(0) && _perBlockAmount <= uint256(_rewardSupply), 'per block amount must be more than 0 and less than supply' ); // A locked date of '0' corresponds to being locked forever until the supply has expired and been rewards to all stakers require( _lockedUntilDate > block.timestamp || _lockedUntilDate == 0, 'locked time must be after now or 0' ); _rewardsToken = IERC20(_rewardsTokenAddy); if (_isStakedNft) { _stakedERC721 = IERC721(_stakedTokenAddy); } else { _stakedERC20 = IERC20(_stakedTokenAddy); } pool = PoolInfo({ creator: msg.sender, tokenOwner: _originalTokenOwner, origTotSupply: _rewardSupply, curRewardsSupply: _rewardSupply, totalTokensStaked: 0, creationBlock: 0, perBlockNum: _perBlockAmount, lockedUntilDate: _lockedUntilDate, lastRewardBlock: block.number, accERC20PerShare: 0, stakeTimeLockSec: _stakeTimeLockSec, isStakedNft: _isStakedNft }); } // SHOULD ONLY BE CALLED AT CONTRACT CREATION and allows changing // the initial supply if tokenomics of token transfer causes // the original staking contract supply to be less than the original function updateSupply(uint256 _newSupply) external { require( msg.sender == pool.creator, 'only contract creator can update the supply' ); pool.origTotSupply = _newSupply; pool.curRewardsSupply = _newSupply; } function stakedTokenAddress() external view returns (address) { return pool.isStakedNft ? address(_stakedERC721) : address(_stakedERC20); } function rewardsTokenAddress() external view returns (address) { return address(_rewardsToken); } function tokenOwner() external view returns (address) { return pool.tokenOwner; } function getLockedUntilDate() external view returns (uint256) { return pool.lockedUntilDate; } function removeStakeableTokens() external { require( msg.sender == pool.creator || msg.sender == pool.tokenOwner, 'caller must be the contract creator or owner to remove stakable tokens' ); _rewardsToken.transfer(pool.tokenOwner, pool.curRewardsSupply); pool.curRewardsSupply = 0; contractIsRemoved = true; } // function updateTimestamp(uint256 _newTime) external { // require( // msg.sender == tokenOwner, // 'updateTimestamp user must be original token owner' // ); // require( // _newTime > lockedUntilDate || _newTime == 0, // 'you cannot change timestamp if it is before the locked time or was set to be locked forever' // ); // lockedUntilDate = _newTime; // } function stakeTokens(uint256 _amount, uint256[] memory _tokenIds) public { require( getLastStakableBlock() > block.number, 'this farm is expired and no more stakers can be added' ); _updatePool(); if (balanceOf(msg.sender) > 0) { _harvestTokens(msg.sender); } uint256 _finalAmountTransferred; if (pool.isStakedNft) { require( _tokenIds.length > 0, "you need to provide NFT token IDs you're staking" ); for (uint256 _i = 0; _i < _tokenIds.length; _i++) { _stakedERC721.transferFrom(msg.sender, address(this), _tokenIds[_i]); } _finalAmountTransferred = _tokenIds.length; } else { uint256 _contractBalanceBefore = _stakedERC20.balanceOf(address(this)); _stakedERC20.transferFrom(msg.sender, address(this), _amount); // in the event a token contract on transfer taxes, burns, etc. tokens // the contract might not get the entire amount that the user originally // transferred. Need to calculate from the previous contract balance // so we know how many were actually transferred. _finalAmountTransferred = _stakedERC20.balanceOf(address(this)).sub( _contractBalanceBefore ); } if (totalSupply() == 0) { pool.creationBlock = block.number; pool.lastRewardBlock = block.number; } _mint(msg.sender, _finalAmountTransferred); StakerInfo storage _staker = stakers[msg.sender]; _staker.amountStaked = _staker.amountStaked.add(_finalAmountTransferred); _staker.blockOriginallyStaked = block.number; _staker.timeOriginallyStaked = block.timestamp; _staker.blockLastHarvested = block.number; _staker.rewardDebt = _staker.amountStaked.mul(pool.accERC20PerShare).div( 1e36 ); for (uint256 _i = 0; _i < _tokenIds.length; _i++) { _staker.nftTokenIds.push(_tokenIds[_i]); } _updNumStaked(_finalAmountTransferred, 'add'); emit Deposit(msg.sender, _finalAmountTransferred); } // pass 'false' for _shouldHarvest for emergency unstaking without claiming rewards function unstakeTokens(uint256 _amount, bool _shouldHarvest) external { StakerInfo memory _staker = stakers[msg.sender]; uint256 _userBalance = _staker.amountStaked; require( pool.isStakedNft ? true : _amount <= _userBalance, 'user can only unstake amount they have currently staked or less' ); // allow unstaking if the user is emergency unstaking and not getting rewards or // if theres a time lock that it's past the time lock or // the contract rewards were removed by the original contract creator or // the contract is expired require( !_shouldHarvest || block.timestamp >= _staker.timeOriginallyStaked.add(pool.stakeTimeLockSec) || contractIsRemoved || block.number > getLastStakableBlock(), 'you have not staked for minimum time lock yet and the pool is not expired' ); _updatePool(); if (_shouldHarvest) { _harvestTokens(msg.sender); } uint256 _amountToRemoveFromStaked = pool.isStakedNft ? _userBalance : _amount; transfer( _burner, _amountToRemoveFromStaked > balanceOf(msg.sender) ? balanceOf(msg.sender) : _amountToRemoveFromStaked ); if (pool.isStakedNft) { for (uint256 _i = 0; _i < _staker.nftTokenIds.length; _i++) { _stakedERC721.transferFrom( address(this), msg.sender, _staker.nftTokenIds[_i] ); } } else { require( _stakedERC20.transfer(msg.sender, _amountToRemoveFromStaked), 'unable to send user original tokens' ); } if (balanceOf(msg.sender) <= 0) { delete stakers[msg.sender]; } else { _staker.amountStaked = _staker.amountStaked.sub( _amountToRemoveFromStaked ); } _updNumStaked(_amountToRemoveFromStaked, 'remove'); emit Withdraw(msg.sender, _amountToRemoveFromStaked); } function emergencyUnstake() external { StakerInfo memory _staker = stakers[msg.sender]; uint256 _amountToRemoveFromStaked = _staker.amountStaked; require( _amountToRemoveFromStaked > 0, 'user can only unstake if they have tokens in the pool' ); transfer( _burner, _amountToRemoveFromStaked > balanceOf(msg.sender) ? balanceOf(msg.sender) : _amountToRemoveFromStaked ); if (pool.isStakedNft) { for (uint256 _i = 0; _i < _staker.nftTokenIds.length; _i++) { _stakedERC721.transferFrom( address(this), msg.sender, _staker.nftTokenIds[_i] ); } } else { require( _stakedERC20.transfer(msg.sender, _amountToRemoveFromStaked), 'unable to send user original tokens' ); } delete stakers[msg.sender]; _updNumStaked(_amountToRemoveFromStaked, 'remove'); emit Withdraw(msg.sender, _amountToRemoveFromStaked); } function harvestForUser(address _userAddy, bool _autoCompound) external returns (uint256) { require( msg.sender == pool.creator || msg.sender == _userAddy, 'can only harvest tokens for someone else if this was the contract creator' ); _updatePool(); uint256 _tokensToUser = _harvestTokens(_userAddy); if ( _autoCompound && !pool.isStakedNft && address(_rewardsToken) == address(_stakedERC20) ) { uint256[] memory _placeholder; stakeTokens(_tokensToUser, _placeholder); } return _tokensToUser; } function getLastStakableBlock() public view returns (uint256) { uint256 _blockToAdd = pool.creationBlock == 0 ? block.number : pool.creationBlock; return pool.origTotSupply.div(pool.perBlockNum).add(_blockToAdd); } function calcHarvestTot(address _userAddy) public view returns (uint256) { StakerInfo memory _staker = stakers[_userAddy]; if ( _staker.blockLastHarvested >= block.number || _staker.blockOriginallyStaked == 0 || pool.totalTokensStaked == 0 ) { return uint256(0); } uint256 _accERC20PerShare = pool.accERC20PerShare; if (block.number > pool.lastRewardBlock && pool.totalTokensStaked != 0) { uint256 _endBlock = getLastStakableBlock(); uint256 _lastBlock = block.number < _endBlock ? block.number : _endBlock; uint256 _nrOfBlocks = _lastBlock.sub(pool.lastRewardBlock); uint256 _erc20Reward = _nrOfBlocks.mul(pool.perBlockNum); _accERC20PerShare = _accERC20PerShare.add( _erc20Reward.mul(1e36).div(pool.totalTokensStaked) ); } return _staker.amountStaked.mul(_accERC20PerShare).div(1e36).sub( _staker.rewardDebt ); } // Update reward variables of the given pool to be up-to-date. function _updatePool() private { uint256 _endBlock = getLastStakableBlock(); uint256 _lastBlock = block.number < _endBlock ? block.number : _endBlock; if (_lastBlock <= pool.lastRewardBlock) { return; } uint256 _stakedSupply = pool.totalTokensStaked; if (_stakedSupply == 0) { pool.lastRewardBlock = _lastBlock; return; } uint256 _nrOfBlocks = _lastBlock.sub(pool.lastRewardBlock); uint256 _erc20Reward = _nrOfBlocks.mul(pool.perBlockNum); pool.accERC20PerShare = pool.accERC20PerShare.add( _erc20Reward.mul(1e36).div(_stakedSupply) ); pool.lastRewardBlock = _lastBlock; } function _harvestTokens(address _userAddy) private returns (uint256) { StakerInfo storage _staker = stakers[_userAddy]; require(_staker.blockOriginallyStaked > 0, 'user must have tokens staked'); uint256 _num2Trans = calcHarvestTot(_userAddy); if (_num2Trans > 0) { require( _rewardsToken.transfer(_userAddy, _num2Trans), 'unable to send user their harvested tokens' ); pool.curRewardsSupply = pool.curRewardsSupply.sub(_num2Trans); } _staker.rewardDebt = _staker.amountStaked.mul(pool.accERC20PerShare).div( 1e36 ); _staker.blockLastHarvested = block.number; return _num2Trans; } // update the amount currently staked after a user harvests function _updNumStaked(uint256 _amount, string memory _operation) private { if (_compareStr(_operation, 'remove')) { pool.totalTokensStaked = pool.totalTokensStaked.sub(_amount); } else { pool.totalTokensStaked = pool.totalTokensStaked.add(_amount); } } function _compareStr(string memory a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/interfaces/IERC721.sol'; import './interfaces/IConditional.sol'; contract HasERC721Balance is IConditional, Ownable { address public nftContract; uint256 public minTokenBalance = 1; constructor(address _nftContract) { nftContract = _nftContract; } function passesTest(address wallet) external view override returns (bool) { return IERC721(nftContract).balanceOf(wallet) >= minTokenBalance; } function setTokenAddress(address _nftContract) external onlyOwner { nftContract = _nftContract; } function setMinTokenBalance(uint256 _newMin) external onlyOwner { minTokenBalance = _newMin; } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import './interfaces/IConditional.sol'; contract IsERC20HODLer is IConditional, Ownable { address public tokenContract; uint256 public numSecondsForBooster = 60 * 60 * 24 * 7; // 7 days mapping(address => uint256) public userBalances; mapping(address => uint256) public userBalTimestamp; constructor(address _tokenContract) { tokenContract = _tokenContract; } function passesTest(address wallet) external view override returns (bool) { uint256 userBal = IERC20(tokenContract).balanceOf(wallet); return userBal > 0 && userBalances[wallet] > 0 && userBalTimestamp[wallet] > 0 && userBal >= userBalances[wallet] && block.timestamp > userBalTimestamp[wallet] + numSecondsForBooster; } function setBalanceAndTimestamp() external { userBalances[msg.sender] = IERC20(tokenContract).balanceOf(msg.sender); userBalTimestamp[msg.sender] = block.timestamp; } function setTokenAddress(address _tokenContract) external onlyOwner { tokenContract = _tokenContract; } function setNumSecondsForBooster(uint256 _seconds) external onlyOwner { numSecondsForBooster = _seconds; } } /* ok.let's.go. ($OKLG) Website = https://oklg.io Telegram = https://t.me/ok_lg Twitter = https://twitter.com/oklgio */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol'; import './interfaces/IConditional.sol'; contract OKLG is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public treasuryWallet = payable(0xDb3AC91239b79Fae75c21E1f75a189b1D75dD906); address public constant deadAddress = 0x000000000000000000000000000000000000dEaD; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isSniper; address[] private _confirmedSnipers; uint256 public rewardsClaimTimeSeconds = 60 * 60 * 4; // 4 hours mapping(address => uint256) private _rewardsLastClaim; mapping(address => bool) private _isExcludedFee; mapping(address => bool) private _isExcludedReward; address[] private _excluded; string private constant _name = 'ok.lets.go.'; string private constant _symbol = 'OKLG'; uint8 private constant _decimals = 9; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 420690000000 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public reflectionFee = 2; uint256 private _previousReflectFee = reflectionFee; uint256 public treasuryFee = 4; uint256 private _previousTreasuryFee = treasuryFee; uint256 public ethRewardsFee = 2; uint256 private _previousETHRewardsFee = ethRewardsFee; uint256 public ethRewardsBalance; uint256 public buybackFee = 2; uint256 private _previousBuybackFee = buybackFee; address public buybackTokenAddress = address(this); address public buybackReceiver = deadAddress; uint256 public feeSellMultiplier = 1; uint256 public feeRate = 2; uint256 public launchTime; uint256 public boostRewardsPercent = 50; address public boostRewardsContract; address public feeExclusionContract; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; mapping(address => bool) private _isUniswapPair; // PancakeSwap: 0x10ED43C718714eb63d5aA57B78B54704E256024E // Uniswap V2: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D address private constant _uniswapRouterAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; bool private _inSwapAndLiquify; bool private _isSelling; bool private _tradingOpen = false; bool private _transferOpen = false; event SendETHRewards(address to, uint256 amountETH); event SendTokenRewards(address to, address token, uint256 amount); event SwapETHForTokens(address whereTo, uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SwapAndLiquify( uint256 tokensSwappedForEth, uint256 ethAddedForLp, uint256 tokensAddedForLp ); modifier lockTheSwap() { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function initContract() external onlyOwner { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( _uniswapRouterAddress ); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); uniswapV2Router = _uniswapV2Router; _isExcludedFee[owner()] = true; _isExcludedFee[address(this)] = true; } function openTrading() external onlyOwner { treasuryFee = _previousTreasuryFee; ethRewardsFee = _previousETHRewardsFee; reflectionFee = _previousReflectFee; buybackFee = _previousBuybackFee; _tradingOpen = true; _transferOpen = true; launchTime = block.timestamp; } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcludedReward[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), 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(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, 'ERC20: transfer amount exceeds allowance' ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function getLastETHRewardsClaim(address wallet) external view returns (uint256) { return _rewardsLastClaim[wallet]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) external { address sender = _msgSender(); require( !_isExcludedReward[sender], 'Excluded addresses cannot call this function' ); (uint256 rAmount, , , , , ) = _getValues(sender, tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, 'Amount must be less than supply'); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(address(0), tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(address(0), tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, 'Amount must be less than total reflections'); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) external onlyOwner { require(!_isExcludedReward[account], 'Account is already excluded'); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcludedReward[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcludedReward[account], 'Account is already included'); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcludedReward[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { 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); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), 'ERC20: transfer from the zero address'); require(to != address(0), 'ERC20: transfer to the zero address'); require(amount > 0, 'Transfer amount must be greater than zero'); require(!_isSniper[to], 'Stop sniping!'); require(!_isSniper[from], 'Stop sniping!'); require(!_isSniper[_msgSender()], 'Stop sniping!'); require( _transferOpen || from == owner(), 'transferring tokens is not currently allowed' ); // reset receiver's timer to prevent users buying and // immmediately transferring to buypass timer _rewardsLastClaim[to] = block.timestamp; bool excludedFromFee = false; // buy if ( (from == uniswapV2Pair || _isUniswapPair[from]) && to != address(uniswapV2Router) ) { // normal buy, check for snipers if (!isExcludedFromFee(to)) { require(_tradingOpen, 'Trading not yet enabled.'); // antibot if (block.timestamp == launchTime) { _isSniper[to] = true; _confirmedSnipers.push(to); } _rewardsLastClaim[from] = block.timestamp; } else { // set excluded flag for takeFee below since buyer is excluded excludedFromFee = true; } } // sell if ( !_inSwapAndLiquify && _tradingOpen && (to == uniswapV2Pair || _isUniswapPair[to]) ) { uint256 _contractTokenBalance = balanceOf(address(this)); if (_contractTokenBalance > 0) { if ( _contractTokenBalance > balanceOf(uniswapV2Pair).mul(feeRate).div(100) ) { _contractTokenBalance = balanceOf(uniswapV2Pair).mul(feeRate).div( 100 ); } _swapTokens(_contractTokenBalance); } _rewardsLastClaim[from] = block.timestamp; _isSelling = true; excludedFromFee = isExcludedFromFee(from); } bool takeFee = false; // take fee only on swaps if ( (from == uniswapV2Pair || to == uniswapV2Pair || _isUniswapPair[to] || _isUniswapPair[from]) && !excludedFromFee ) { takeFee = true; } _tokenTransfer(from, to, amount, takeFee); _isSelling = false; } function _swapTokens(uint256 _contractTokenBalance) private lockTheSwap { uint256 ethBalanceBefore = address(this).balance; _swapTokensForEth(_contractTokenBalance); uint256 ethBalanceAfter = address(this).balance; uint256 ethBalanceUpdate = ethBalanceAfter.sub(ethBalanceBefore); uint256 _liquidityFeeTotal = _liquidityFeeAggregate(address(0)); ethRewardsBalance += ethBalanceUpdate.mul(ethRewardsFee).div( _liquidityFeeTotal ); // send ETH to treasury address uint256 treasuryETHBalance = ethBalanceUpdate.mul(treasuryFee).div( _liquidityFeeTotal ); if (treasuryETHBalance > 0) { _sendETHToTreasury(treasuryETHBalance); } // buy back uint256 buybackETHBalance = ethBalanceUpdate.mul(buybackFee).div( _liquidityFeeTotal ); if (buybackETHBalance > 0) { _buyBackTokens(buybackETHBalance); } } function _sendETHToTreasury(uint256 amount) private { treasuryWallet.call{ value: amount }(''); } function _buyBackTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = buybackTokenAddress; // make the swap uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: amount }( 0, // accept any amount of tokens path, buybackReceiver, block.timestamp ); emit SwapETHForTokens(buybackReceiver, amount, path); } function _swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // the contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) _removeAllFee(); if (_isExcludedReward[sender] && !_isExcludedReward[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcludedReward[sender] && _isExcludedReward[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcludedReward[sender] && _isExcludedReward[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) _restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(sender, tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(sender, tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(sender, tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(sender, tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(address seller, uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues( seller, tAmount ); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(address seller, uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = _calculateReflectFee(tAmount); uint256 tLiquidity = _calculateLiquidityFee(seller, tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcludedReward[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _calculateReflectFee(uint256 _amount) private view returns (uint256) { return _amount.mul(reflectionFee).div(10**2); } function _liquidityFeeAggregate(address seller) private view returns (uint256) { uint256 feeMultiplier = _isSelling && !canClaimRewards(seller) ? feeSellMultiplier : 1; return (treasuryFee.add(ethRewardsFee).add(buybackFee)).mul(feeMultiplier); } function _calculateLiquidityFee(address seller, uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFeeAggregate(seller)).div(10**2); } function _removeAllFee() private { if ( reflectionFee == 0 && treasuryFee == 0 && ethRewardsFee == 0 && buybackFee == 0 ) return; _previousReflectFee = reflectionFee; _previousTreasuryFee = treasuryFee; _previousETHRewardsFee = ethRewardsFee; _previousBuybackFee = buybackFee; reflectionFee = 0; treasuryFee = 0; ethRewardsFee = 0; buybackFee = 0; } function _restoreAllFee() private { reflectionFee = _previousReflectFee; treasuryFee = _previousTreasuryFee; ethRewardsFee = _previousETHRewardsFee; buybackFee = _previousBuybackFee; } function getSellSlippage(address seller) external view returns (uint256) { uint256 feeAgg = reflectionFee.add(treasuryFee).add(ethRewardsFee).add( buybackFee ); return isExcludedFromFee(seller) ? 0 : !canClaimRewards(seller) ? feeAgg.mul(feeSellMultiplier) : feeAgg; } function isUniswapPair(address _pair) external view returns (bool) { if (_pair == uniswapV2Pair) return true; return _isUniswapPair[_pair]; } function eligibleForRewardBooster(address wallet) public view returns (bool) { return boostRewardsContract != address(0) && IConditional(boostRewardsContract).passesTest(wallet); } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFee[account] || (feeExclusionContract != address(0) && IConditional(feeExclusionContract).passesTest(account)); } function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedReward[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFee[account] = false; } function setRewardsClaimTimeSeconds(uint256 _seconds) external onlyOwner { rewardsClaimTimeSeconds = _seconds; } function setReflectionFeePercent(uint256 _newFee) external onlyOwner { require(_newFee <= 10, 'fee cannot exceed 10%'); reflectionFee = _newFee; } function setTreasuryFeePercent(uint256 _newFee) external onlyOwner { require(_newFee <= 10, 'fee cannot exceed 10%'); treasuryFee = _newFee; } function setETHRewardsFeeFeePercent(uint256 _newFee) external onlyOwner { require(_newFee <= 10, 'fee cannot exceed 10%'); ethRewardsFee = _newFee; } function setBuybackFeePercent(uint256 _newFee) external onlyOwner { require(_newFee <= 10, 'fee cannot exceed 10%'); buybackFee = _newFee; } function setFeeSellMultiplier(uint256 multiplier) external onlyOwner { require( multiplier > 0 && multiplier <= 5, 'must be greater than 0 and less than or equal to 5' ); require( _liquidityFeeAggregate(address(0)).mul(multiplier) < 40, 'multiplier should not make total fee more than 40%' ); feeSellMultiplier = multiplier; } function setTreasuryAddress(address _treasuryWallet) external onlyOwner { treasuryWallet = payable(_treasuryWallet); } function setBuybackTokenAddress(address _tokenAddress) external onlyOwner { buybackTokenAddress = _tokenAddress; } function setBuybackReceiver(address _receiver) external onlyOwner { buybackReceiver = _receiver; } function addUniswapPair(address _pair) external onlyOwner { _isUniswapPair[_pair] = true; } function removeUniswapPair(address _pair) external onlyOwner { _isUniswapPair[_pair] = false; } function setCanTransfer(bool _canTransfer) external onlyOwner { _transferOpen = _canTransfer; } function setBoostRewardsPercent(uint256 perc) external onlyOwner { boostRewardsPercent = perc; } function setBoostRewardsContract(address _contract) external onlyOwner { if (_contract != address(0)) { IConditional _contCheck = IConditional(_contract); // allow setting to zero address to effectively turn off check logic require( _contCheck.passesTest(address(0)) == true || _contCheck.passesTest(address(0)) == false, 'contract does not implement interface' ); } boostRewardsContract = _contract; } function setFeeExclusionContract(address _contract) external onlyOwner { if (_contract != address(0)) { IConditional _contCheck = IConditional(_contract); // allow setting to zero address to effectively turn off check logic require( _contCheck.passesTest(address(0)) == true || _contCheck.passesTest(address(0)) == false, 'contract does not implement interface' ); } feeExclusionContract = _contract; } function isRemovedSniper(address account) external view returns (bool) { return _isSniper[account]; } function removeSniper(address account) external onlyOwner { require(account != _uniswapRouterAddress, 'We can not blacklist Uniswap'); require(!_isSniper[account], 'Account is already blacklisted'); _isSniper[account] = true; _confirmedSnipers.push(account); } function amnestySniper(address account) external onlyOwner { require(_isSniper[account], 'Account is not blacklisted'); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function calculateETHRewards(address wallet) public view returns (uint256) { uint256 baseRewards = ethRewardsBalance.mul(balanceOf(wallet)).div( _tTotal.sub(balanceOf(deadAddress)) // circulating supply ); uint256 rewardsWithBooster = eligibleForRewardBooster(wallet) ? baseRewards.add(baseRewards.mul(boostRewardsPercent).div(10**2)) : baseRewards; return rewardsWithBooster > ethRewardsBalance ? baseRewards : rewardsWithBooster; } function calculateTokenRewards(address wallet, address tokenAddress) public view returns (uint256) { IERC20 token = IERC20(tokenAddress); uint256 contractTokenBalance = token.balanceOf(address(this)); uint256 baseRewards = contractTokenBalance.mul(balanceOf(wallet)).div( _tTotal.sub(balanceOf(deadAddress)) // circulating supply ); uint256 rewardsWithBooster = eligibleForRewardBooster(wallet) ? baseRewards.add(baseRewards.mul(boostRewardsPercent).div(10**2)) : baseRewards; return rewardsWithBooster > contractTokenBalance ? baseRewards : rewardsWithBooster; } function claimETHRewards() external { require( balanceOf(_msgSender()) > 0, 'You must have a balance to claim ETH rewards' ); require( canClaimRewards(_msgSender()), 'Must wait claim period before claiming rewards' ); _rewardsLastClaim[_msgSender()] = block.timestamp; uint256 rewardsSent = calculateETHRewards(_msgSender()); ethRewardsBalance -= rewardsSent; _msgSender().call{ value: rewardsSent }(''); emit SendETHRewards(_msgSender(), rewardsSent); } function canClaimRewards(address user) public view returns (bool) { return block.timestamp > _rewardsLastClaim[user].add(rewardsClaimTimeSeconds); } function claimTokenRewards(address token) external { require( balanceOf(_msgSender()) > 0, 'You must have a balance to claim rewards' ); require( IERC20(token).balanceOf(address(this)) > 0, 'We must have a token balance to claim rewards' ); require( canClaimRewards(_msgSender()), 'Must wait claim period before claiming rewards' ); _rewardsLastClaim[_msgSender()] = block.timestamp; uint256 rewardsSent = calculateTokenRewards(_msgSender(), token); IERC20(token).transfer(_msgSender(), rewardsSent); emit SendTokenRewards(_msgSender(), token, rewardsSent); } function setFeeRate(uint256 _rate) external onlyOwner { feeRate = _rate; } function emergencyWithdraw() external onlyOwner { payable(owner()).call{ value: address(this).balance }(''); } // to recieve ETH from uniswapV2Router when swaping receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol'; import './interfaces/IOKLGSpend.sol'; import './OKLGWithdrawable.sol'; /** * @title OKLGSpend * @dev Logic for spending OKLG on products in the product ecosystem. */ contract OKLGSpend is IOKLGSpend, OKLGWithdrawable { address payable private constant DEAD_WALLET = payable(0x000000000000000000000000000000000000dEaD); address payable public paymentWallet = payable(0x000000000000000000000000000000000000dEaD); AggregatorV3Interface internal priceFeed; uint256 public totalSpentWei = 0; mapping(uint8 => uint256) public defaultProductPriceUSD; mapping(address => uint256) public overrideProductPriceUSD; mapping(address => bool) public removeCost; event Spend(address indexed user, address indexed product, uint256 value); constructor(address _linkPriceFeedContract) { // https://docs.chain.link/docs/reference-contracts/ // https://github.com/pcaversaccio/chainlink-price-feed/blob/main/README.md priceFeed = AggregatorV3Interface(_linkPriceFeedContract); } function getProductCostWei(uint256 _productCostUSD) public view returns (uint256) { // Creates a USD balance with 18 decimals uint256 paymentUSD18 = 10**18 * _productCostUSD; // adding back 18 decimals to get returned value in wei return (10**18 * paymentUSD18) / getLatestETHPrice(); } /** * Returns the latest ETH/USD price with returned value at 18 decimals * https://docs.chain.link/docs/get-the-latest-price/ */ function getLatestETHPrice() public view returns (uint256) { uint8 decimals = priceFeed.decimals(); (, int256 price, , , ) = priceFeed.latestRoundData(); return uint256(price) * (10**18 / 10**decimals); } function setPriceFeed(address _feedContract) external onlyOwner { priceFeed = AggregatorV3Interface(_feedContract); } function setPaymentWallet(address _newPaymentWallet) external onlyOwner { paymentWallet = payable(_newPaymentWallet); } function setDefaultProductUSDPrice(uint8 _product, uint256 _priceUSD) external onlyOwner { defaultProductPriceUSD[_product] = _priceUSD; } function setDefaultProductPricesUSDBulk( uint8[] memory _productIds, uint256[] memory _pricesUSD ) external onlyOwner { require( _productIds.length == _pricesUSD.length, 'arrays need to be the same length' ); for (uint256 _i = 0; _i < _productIds.length; _i++) { defaultProductPriceUSD[_productIds[_i]] = _pricesUSD[_i]; } } function setOverrideProductPriceUSD(address _productCont, uint256 _priceUSD) external onlyOwner { overrideProductPriceUSD[_productCont] = _priceUSD; } function setOverrideProductPricesUSDBulk( address[] memory _contracts, uint256[] memory _pricesUSD ) external onlyOwner { require( _contracts.length == _pricesUSD.length, 'arrays need to be the same length' ); for (uint256 _i = 0; _i < _contracts.length; _i++) { overrideProductPriceUSD[_contracts[_i]] = _pricesUSD[_i]; } } function setRemoveCost(address _productCont, bool _isRemoved) external onlyOwner { removeCost[_productCont] = _isRemoved; } /** * spendOnProduct: used by an OKLG product for a user to spend native token on usage of a product */ function spendOnProduct(address _payor, uint8 _product) external payable override { if (removeCost[msg.sender]) return; uint256 _productCostUSD = overrideProductPriceUSD[msg.sender] > 0 ? overrideProductPriceUSD[msg.sender] : defaultProductPriceUSD[_product]; if (_productCostUSD == 0) return; uint256 _productCostWei = getProductCostWei(_productCostUSD); require( msg.value >= _productCostWei, 'not enough ETH sent to pay for product' ); address payable _paymentWallet = paymentWallet == DEAD_WALLET || paymentWallet == address(0) ? payable(owner()) : paymentWallet; _paymentWallet.call{ value: _productCostWei }(''); _refundExcessPayment(_productCostWei); totalSpentWei += _productCostWei; emit Spend(msg.sender, _payor, _productCostWei); } function _refundExcessPayment(uint256 _productCost) internal { uint256 excess = msg.value - _productCost; if (excess > 0) { payable(msg.sender).call{ value: excess }(''); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import '@openzeppelin/contracts/interfaces/IERC721.sol'; import './interfaces/IOKLGSpend.sol'; import './OKLGProduct.sol'; /** * @title OKLGAirdropper * @dev Allows sending ERC20 or ERC721 tokens to multiple addresses */ contract OKLGAirdropper is OKLGProduct { struct Receiver { address userAddress; uint256 amountOrTokenId; } constructor(address _tokenAddy, address _spendContractAddy) OKLGProduct(uint8(1), _tokenAddy, _spendContractAddy) {} function bulkSendMainTokens(Receiver[] memory _addressesAndAmounts) external payable returns (bool) { uint256 balanceBefore = address(this).balance; _payForService(0); uint256 _amountSent = 0; bool _wasSent = true; for (uint256 _i = 0; _i < _addressesAndAmounts.length; _i++) { Receiver memory _user = _addressesAndAmounts[_i]; _amountSent += _user.amountOrTokenId; (bool sent, ) = _user.userAddress.call{ value: _user.amountOrTokenId }( '' ); _wasSent = _wasSent == false ? false : sent; } require( msg.value >= _amountSent, 'ETH provided by user should accommodate amount being airdropped' ); require( address(this).balance >= balanceBefore, 'no native token in contract should be used' ); return _wasSent; } function bulkSendErc20Tokens( address _tokenAddress, Receiver[] memory _addressesAndAmounts ) external payable returns (bool) { _payForService(0); IERC20 _token = IERC20(_tokenAddress); for (uint256 _i = 0; _i < _addressesAndAmounts.length; _i++) { Receiver memory _user = _addressesAndAmounts[_i]; _token.transferFrom(msg.sender, _user.userAddress, _user.amountOrTokenId); } return true; } function bulkSendErc721Tokens( address _tokenAddress, Receiver[] memory _addressesAndAmounts ) external payable returns (bool) { _payForService(0); IERC721 _token = IERC721(_tokenAddress); for (uint256 _i = 0; _i < _addressesAndAmounts.length; _i++) { Receiver memory _user = _addressesAndAmounts[_i]; _token.transferFrom(msg.sender, _user.userAddress, _user.amountOrTokenId); } return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol'; import './OKLGAffiliate.sol'; /** * @title OKLGBuybot * @dev Logic for spending OKLG on products in the product ecosystem. */ contract OKLGBuybot is OKLGAffiliate { AggregatorV3Interface internal priceFeed; uint256 public totalSpentWei = 0; uint256 public paidPricePerDayUsd = 25; mapping(address => uint256) public overridePricePerDayUSD; mapping(address => bool) public removeCost; event SetupBot( address indexed user, address token, string client, string channel, uint256 expiration ); event SetupBotAdmin( address indexed user, address token, string client, string channel, uint256 expiration ); event DeleteBot( address indexed user, address token, string client, string channel ); struct Buybot { address token; string client; // telegram, discord, etc. string channel; bool isPaid; uint256 minThresholdUsd; // lpPairAltToken?: string; // if blank, assume the other token in the pair is native (ETH, BNB, etc.) uint256 expiration; // unix timestamp of expiration, or 0 if no expiration } mapping(bytes32 => Buybot) public buybotConfigs; bytes32[] public buybotConfigsList; constructor(address _linkPriceFeedContract) { // https://docs.chain.link/docs/reference-contracts/ // https://github.com/pcaversaccio/chainlink-price-feed/blob/main/README.md priceFeed = AggregatorV3Interface(_linkPriceFeedContract); } /** * Returns the latest ETH/USD price with returned value at 18 decimals * https://docs.chain.link/docs/get-the-latest-price/ */ function getLatestETHPrice() public view returns (uint256) { uint8 decimals = priceFeed.decimals(); (, int256 price, , , ) = priceFeed.latestRoundData(); return uint256(price) * (10**18 / 10**decimals); } function setPriceFeed(address _feedContract) external onlyOwner { priceFeed = AggregatorV3Interface(_feedContract); } function setOverridePricePerDayUSD(address _wallet, uint256 _priceUSD) external onlyOwner { overridePricePerDayUSD[_wallet] = _priceUSD; } function setOverridePricesPerDayUSDBulk( address[] memory _contracts, uint256[] memory _pricesUSD ) external onlyOwner { require( _contracts.length == _pricesUSD.length, 'arrays need to be the same length' ); for (uint256 _i = 0; _i < _contracts.length; _i++) { overridePricePerDayUSD[_contracts[_i]] = _pricesUSD[_i]; } } function setRemoveCost(address _wallet, bool _isRemoved) external onlyOwner { removeCost[_wallet] = _isRemoved; } function getId( address _token, string memory _client, string memory _channel ) public pure returns (bytes32) { return sha256(abi.encodePacked(_token, _client, _channel)); } function setupBot( address _token, string memory _client, string memory _channel, bool _isPaid, uint256 _minThresholdUsd, address _referrer ) external payable { require(msg.value >= 0, 'must send some ETH to pay for bot'); uint256 _costPerDayUSD = overridePricePerDayUSD[msg.sender] > 0 ? overridePricePerDayUSD[msg.sender] : paidPricePerDayUsd; if (_isPaid && !removeCost[msg.sender]) { pay(msg.sender, _referrer, msg.value); totalSpentWei += msg.value; _costPerDayUSD = 0; } uint256 _daysOfService18 = 30; if (_costPerDayUSD > 0) { uint256 _costPerDayUSD18 = _costPerDayUSD * 10**18; uint256 _ethPriceUSD18 = getLatestETHPrice(); _daysOfService18 = ((msg.value * 10**18) * _ethPriceUSD18) / _costPerDayUSD18; } uint256 _secondsOfService = (_daysOfService18 * 24 * 60 * 60) / 10**18; bytes32 _id = getId(_token, _client, _channel); Buybot storage _bot = buybotConfigs[_id]; if (_bot.expiration == 0) { buybotConfigsList.push(_id); } uint256 _start = _bot.expiration < block.timestamp ? block.timestamp : _bot.expiration; _bot.token = _token; _bot.isPaid = _isPaid; _bot.client = _client; _bot.channel = _channel; _bot.minThresholdUsd = _minThresholdUsd; _bot.expiration = _start + _secondsOfService; emit SetupBot(msg.sender, _token, _client, _channel, _bot.expiration); } function setupBotAdmin( address _token, string memory _client, string memory _channel, bool _isPaid, uint256 _minThresholdUsd, uint256 _expiration ) external onlyOwner { bytes32 _id = getId(_token, _client, _channel); Buybot storage _bot = buybotConfigs[_id]; if (_bot.expiration == 0) { buybotConfigsList.push(_id); } _bot.token = _token; _bot.isPaid = _isPaid; _bot.client = _client; _bot.channel = _channel; _bot.minThresholdUsd = _minThresholdUsd; _bot.expiration = _expiration; emit SetupBotAdmin(msg.sender, _token, _client, _channel, _bot.expiration); } function deleteBot( address _token, string memory _client, string memory _channel ) external onlyOwner { bytes32 _id = getId(_token, _client, _channel); delete buybotConfigs[_id]; for (uint256 _i = 0; _i < buybotConfigsList.length; _i++) { if (buybotConfigsList[_i] == _id) { buybotConfigsList[_i] = buybotConfigsList[buybotConfigsList.length - 1]; buybotConfigsList.pop(); } } emit DeleteBot(msg.sender, _token, _client, _channel); } } // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import './interfaces/IConditional.sol'; import './interfaces/IMultiplier.sol'; import './OKLGWithdrawable.sol'; interface IOKLG is IERC20 { function getLastETHRewardsClaim(address wallet) external view returns (uint256); } contract OKLGRewards is OKLGWithdrawable { using SafeMath for uint256; address public constant deadAddress = 0x000000000000000000000000000000000000dEaD; IOKLG private _oklg = IOKLG(0x5f67df361f568e185aA0304A57bdE4b8028d059E); uint256 public rewardsClaimTimeSeconds = 60 * 60 * 12; // 12 hours mapping(address => uint256) private _rewardsLastClaim; uint256 public boostRewardsPercent = 50; address public boostRewardsMultiplierContract; address public boostRewardsContract; event SendETHRewards(address to, uint256 amountETH); event SendTokenRewards(address to, address token, uint256 amount); function ethRewardsBalance() external view returns (uint256) { return address(this).balance; } function getLastETHRewardsClaim(address wallet) external view returns (uint256) { return _rewardsLastClaim[wallet] > _oklg.getLastETHRewardsClaim(wallet) ? _rewardsLastClaim[wallet] : _oklg.getLastETHRewardsClaim(wallet); } function setBoostMultiplierContract(address _contract) external onlyOwner { if (_contract != address(0)) { IMultiplier _contCheck = IMultiplier(_contract); // allow setting to zero address to effectively turn off check logic require( _contCheck.getMultiplier(address(0)) >= 0, 'contract does not implement interface' ); } boostRewardsMultiplierContract = _contract; } function setBoostRewardsContract(address _contract) external onlyOwner { if (_contract != address(0)) { IConditional _contCheck = IConditional(_contract); // allow setting to zero address to effectively turn off check logic require( _contCheck.passesTest(address(0)) == true || _contCheck.passesTest(address(0)) == false, 'contract does not implement interface' ); } boostRewardsContract = _contract; } function setBoostRewardsPercent(uint256 _perc) external onlyOwner { boostRewardsPercent = _perc; } function setRewardsClaimTimeSeconds(uint256 _seconds) external onlyOwner { rewardsClaimTimeSeconds = _seconds; } function setOklgContract(address cont) external onlyOwner { _oklg = IOKLG(cont); } function getOklgContract() external view returns (address) { return address(_oklg); } function getBoostMultiplier(address wallet) public view returns (uint256) { return boostRewardsMultiplierContract == address(0) ? boostRewardsPercent : IMultiplier(boostRewardsMultiplierContract).getMultiplier(wallet); } function calculateETHRewards(address wallet) public view returns (uint256) { uint256 baseRewards = address(this) .balance .mul(_oklg.balanceOf(wallet)) .div( _oklg.totalSupply().sub(_oklg.balanceOf(deadAddress)) // circulating supply ); uint256 rewardsWithBooster = eligibleForRewardBooster(wallet) ? baseRewards.add(baseRewards.mul(getBoostMultiplier(wallet)).div(10**2)) : baseRewards; return rewardsWithBooster > address(this).balance ? baseRewards : rewardsWithBooster; } function calculateTokenRewards(address wallet, address tokenAddress) public view returns (uint256) { IERC20 token = IERC20(tokenAddress); uint256 contractTokenBalance = token.balanceOf(address(this)); uint256 baseRewards = contractTokenBalance.mul(_oklg.balanceOf(wallet)).div( _oklg.totalSupply().sub(_oklg.balanceOf(deadAddress)) // circulating supply ); uint256 rewardsWithBooster = eligibleForRewardBooster(wallet) ? baseRewards.add(baseRewards.mul(getBoostMultiplier(wallet)).div(10**2)) : baseRewards; return rewardsWithBooster > contractTokenBalance ? baseRewards : rewardsWithBooster; } function canClaimRewards(address user) public view returns (bool) { return block.timestamp > _rewardsLastClaim[user].add(rewardsClaimTimeSeconds) && block.timestamp > _oklg.getLastETHRewardsClaim(user).add(rewardsClaimTimeSeconds); } function eligibleForRewardBooster(address wallet) public view returns (bool) { return boostRewardsContract != address(0) && IConditional(boostRewardsContract).passesTest(wallet); } function resetLastClaim(address _user) external onlyOwner { _rewardsLastClaim[_user] = 0; } function claimETHRewards() external { require( _oklg.balanceOf(_msgSender()) > 0, 'You must have a balance to claim ETH rewards' ); require( canClaimRewards(_msgSender()), 'Must wait claim period before claiming rewards' ); _rewardsLastClaim[_msgSender()] = block.timestamp; uint256 rewardsSent = calculateETHRewards(_msgSender()); payable(_msgSender()).call{ value: rewardsSent }(''); emit SendETHRewards(_msgSender(), rewardsSent); } function claimTokenRewards(address token) external { require( _oklg.balanceOf(_msgSender()) > 0, 'You must have a balance to claim rewards' ); require( IERC20(token).balanceOf(address(this)) > 0, 'We must have a token balance to claim rewards' ); require( canClaimRewards(_msgSender()), 'Must wait claim period before claiming rewards' ); _rewardsLastClaim[_msgSender()] = block.timestamp; uint256 rewardsSent = calculateTokenRewards(_msgSender(), token); IERC20(token).transfer(_msgSender(), rewardsSent); emit SendTokenRewards(_msgSender(), token, rewardsSent); } // to recieve ETH from uniswapV2Router when swaping receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import './OKLGProduct.sol'; /** * @title OKLGPasswordManager * @dev Logic for storing and retrieving account information from the blockchain. */ contract OKLGPasswordManager is OKLGProduct { using SafeMath for uint256; struct AccountInfo { string id; uint256 timestamp; string iv; string ciphertext; bool isDeleted; } mapping(address => mapping(string => uint256)) public userAccountIdIndexes; // the normal mapping of all accounts owned by a user mapping(address => AccountInfo[]) public userAccounts; constructor(address _tokenAddress, address _spendAddress) OKLGProduct(uint8(2), _tokenAddress, _spendAddress) {} function getAllAccounts(address _userAddy) external view returns (AccountInfo[] memory) { return userAccounts[_userAddy]; } function getAccountById(string memory _id) external view returns (AccountInfo memory) { AccountInfo[] memory _userInfo = userAccounts[msg.sender]; // SWC-DoS With Block Gas Limit: L47 - L51 for (uint256 _i = 0; _i < _userInfo.length; _i++) { if (_compareStr(_userInfo[_i].id, _id)) { return _userInfo[_i]; } } return AccountInfo({ id: '', timestamp: 0, iv: '', ciphertext: '', isDeleted: false }); } function updateAccountById( string memory _id, string memory _newIv, string memory _newAccountData ) external returns (bool) { AccountInfo[] memory _userInfo = userAccounts[msg.sender]; uint256 _idx = userAccountIdIndexes[msg.sender][_id]; require( _compareStr(_id, _userInfo[_idx].id), 'the ID provided does not match the account stored.' ); userAccounts[msg.sender][_idx].iv = _newIv; userAccounts[msg.sender][_idx].timestamp = block.timestamp; userAccounts[msg.sender][_idx].ciphertext = _newAccountData; return true; } function addAccount( string memory _id, string memory _iv, string memory _ciphertext ) external payable { _payForService(0); require( userAccountIdIndexes[msg.sender][_id] == 0, 'this ID is already being used, the account should be updated instead' ); userAccountIdIndexes[msg.sender][_id] = userAccounts[msg.sender].length; userAccounts[msg.sender].push( AccountInfo({ id: _id, timestamp: block.timestamp, iv: _iv, ciphertext: _ciphertext, isDeleted: false }) ); } function bulkAddAccounts(AccountInfo[] memory accounts) external payable { require( accounts.length >= 5, 'you need a minimum of 5 accounts to add in bulk at a 50% discount service cost' ); _payForService(0); for (uint256 _i = 0; _i < accounts.length; _i++) { AccountInfo memory _account = accounts[_i]; userAccounts[msg.sender].push( AccountInfo({ id: _account.id, timestamp: block.timestamp, iv: _account.iv, ciphertext: _account.ciphertext, isDeleted: false }) ); } } function deleteAccount(string memory _id) external returns (bool) { AccountInfo[] memory _userInfo = userAccounts[msg.sender]; uint256 _idx = userAccountIdIndexes[msg.sender][_id]; require( _compareStr(_id, _userInfo[_idx].id), 'the ID provided does not match the account stored.' ); userAccounts[msg.sender][_idx].timestamp = block.timestamp; userAccounts[msg.sender][_idx].isDeleted = true; return true; } function _compareStr(string memory a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/interfaces/IERC20.sol'; import './interfaces/IOKLGSpend.sol'; import './OKLGWithdrawable.sol'; /** * @title OKLGProduct * @dev Contract that every product developed in the OKLG ecosystem should implement */ contract OKLGProduct is OKLGWithdrawable { IERC20 private _token; // OKLG IOKLGSpend private _spend; uint8 public productID; constructor( uint8 _productID, address _tokenAddy, address _spendAddy ) { productID = _productID; _token = IERC20(_tokenAddy); _spend = IOKLGSpend(_spendAddy); } function setTokenAddy(address _tokenAddy) external onlyOwner { _token = IERC20(_tokenAddy); } function setSpendAddy(address _spendAddy) external onlyOwner { _spend = IOKLGSpend(_spendAddy); } function setProductID(uint8 _newId) external onlyOwner { productID = _newId; } function getTokenAddress() public view returns (address) { return address(_token); } function getSpendAddress() public view returns (address) { return address(_spend); } function _payForService(uint256 _weiToRemoveFromSpend) internal { _spend.spendOnProduct{ value: msg.value - _weiToRemoveFromSpend }( msg.sender, productID ); } }
SOLIDITY FINANCE OKLG - Smart Contract Audit Report AUDIT SUMMARY Ok.let's.go is creating a platform with tokens and various services that can be purchased by users, allowing them to easily create their own Token Lockers, Token Bridges, Raffles, Staking platforms, and more. For this audit, we reviewed the select contracts listed below at commit e167d0d742d21bcc62d7a5b770a1f0ed1cf31eca on the team's GitHub repository. AUDIT FINDINGS Please ensure trust in the team and users of the team's products prior to investing as they have substantial control in the ecosystem. Date: January 14th, 2022. Updated: February 4th, 2022 to reflect changes from commit 393190aee594178f2a9e7f8646cb9b3bb09507f9 to commit 28447bcbaf453737d430569313c2850d707ec79c . Updated: February 14th, 2022 to reflect changes from commit 28447bcbaf453737d430569313c2850d707ec79c to commit c09c970301bb91c8af21a3c177b220375e17480b . Updated: February 17th, 2022 to reflect changes from commit c09c970301bb91c8af21a3c177b220375e17480b to commit e167d0d742d21bcc62d7a5b770a1f0ed1cf31eca . OKLGTokenLocker - Finding #1 - High (Resolved) Description: In the withdrawLockedTokens() function, there is no check to confirm that the Locker's end time has passed when withdrawing NFTs, and improperly checks the amount to be withdrawn when withdrawing ERC20 tokens. if (_locker.isNft) { IERC721 _token = IERC721(_locker.token); _token.transferFrom(address(this), msg.sender, _amountOrTokenId); } else { uint256 _maxAmount = maxWithdrawableTokens(_idx); require( _amountOrTokenId > 0 && _maxAmount > 0 && _maxAmount <= _amountOrTokenId, As shown above, the amount to be withdrawn does not check that the amount is withdrawable when the token is an NFT. When the token is an ERC20, the amountOrTokenId variable is required to be greater than or equal to the maximum withdrawable amount. Risk/Impact: The core intended functionality of this contract does not work; authorized users can withdraw "locked" tokens at any time, and can additionally drain the contract of any tokens of the same type.Recommendation: The withdrawable amount should be checked when the token is an NFT. In addition, the require statement should be updated to ensure that the amountOrTokenId is less than or equal to the maximum withdrawable amount. Resolution: The team has implemented the above recommendation. OKLGTokenLocker - Finding #2 - High (Resolved) Description: The amount withdrawn from a locker is not properly updated when withdrawing tokens. Instead of adding to amountWithdrawn after a withdraw takes place, it is set to the amount that was withdrawn in that transaction only. In addition, this value is updated after the token transfer takes place, opening the door for reentrancy attacks if the token locked is an ERC-777 compliant token. _locker.amountWithdrawn = _locker.isNft ? 1 : _amountOrTokenId; Risk/Impact: Users will be able to withdraw an unlimited amount of tokens from the contract by dividing their withdraws into smaller amounts. Recommendation: Instead of setting the amountWithdrawn to the amount withdrawn in the single transaction, it should be increased by the amount that was withdrawn. The token transfer should also occur after the amountWithdrawn is updated. Resolution: The team has implemented the above recommendation. OKLetsApe - Finding #3 - High (Resolved) Description: The custom mint function can potentially cause issues with standard mints due to a token ID being reserved. Exploit Scenario: 1 . A token with an ID of 5 is custom minted. 2 . Standard mints occur until the _tokenIds counter reaches 5. 3 . Further minting will fail as the token ID of 5 already exists. Risk/Impact: Standard minting will no longer function once the token counter has reached a token ID that has already been custom minted. Recommendation: If the token ID counter reaches a token that already exists, it should be incremented. Disabling custom minting for specific token ids would also resolve this issue. Resolution: The team has added logic to prevent any custom mints for any token ID that is greater than the current token ID counter, preventing this scenario from occurring. OKLGAirdropper - Finding #4 - High (Resolved) Description: The bulkSendMainTokens() function does not check if any blockchain's native token was passed into it (apart from the product cost payment) before sending the blockchain's native token to the list of addresses. Risk/Impact: Any user has the ability to send the contract's native blockchain token balance to the list of addresses without providing funds. Recommendation: The function should ensure that the total amount to send does not exceed the amount provided minus the Product cost. Additional functionality in the OKLGSpend contract will be necessary in order to fetch theProduct cost in the blockchain's native token. Update: While the team has added logic to ensure that the user has sent enough funds to cover the total Airdrop amount, there is no check to ensure that they have sent enough funds for the Airdrop plus the Product cost. This allows the user to potentially use this contract's funds for the Airdrop. If the team does not wish to implement the above recommendation, they could also resolve this issue by requiring that the contract balance - msg.value before the Airdrop is less than or equal to the contract balance after the Airdrop. Update #2: The team has updated the code, however it does not make the correct balance checks to resolve this issue. The updated code will disable Airdrops in the blockchain's native token. The previous recommendation can be implemented to resolve the issue by updating the initialization of "balanceBefore" to the following: uint256 balanceBefore = address(this).balance - msg.value; Resolution: The team has implemented the above recommendation. AtomicSwap - Finding #5 - High (Resolved) Description: The setOracleAddress() function executes a function call for all of the contracts it manages. Risk/Impact: If the list of contracts that the AtomicSwap contract manages is too large, the gas usage may exceed its limit. As the size of the contract list increases as more users purchase the product, the setOracleAddress functionality may break. Recommendation: The number of contracts that the setOracleAddress() function calls should be limited. Update: The team has added "_start" and "_max" parameters along with the following code: uint256 _index = 0; uint256 _numLoops = _max > 0 ? _max : 50; while (_index + _start < _start + _numLoops) { OKLGAtomicSwapInstance _contract = OKLGAtomicSwapInstance( targetSwapContracts[_index].sourceContract ); _contract.setOracleAddress(oracleAddress); _index++; } As shown above, the contracts will always be updated from index 0. This will prevent contracts of larger indexes from being updated if the targetSwapContracts array becomes too large. The above while loop should instead begin at the passed "_start" index and continue until it has exceeded (_start + _numLoops). Update #2: The team has updated the code to where the beginning index is set to the passed "_start" index, however it is not incremented, resulting in the same contract being updated in each iteration. The team should update the following line inside the "while" loop to the following to resolve this issue: OKLGAtomicSwapInstance _contract = OKLGAtomicSwapInstance( targetSwapContracts[_start + _index].sourceContract Resolution: The team has implemented the above recommendation. OKLGFaasToken - Finding #6 - High (Resolved) Description: Rewards are calculated based on the user's OKLGFaasToken balance.Risk/Impact: A user can claim their rewards, transfer their funds to another address, then claim the rewards again. This can be repeated, allowing an unlimited amount of rewards to be claimed. Recommendation: Staked amounts should be stored in a mapping tied to a user's address. Rewards can then be calculated based on this amount. Resolution: Users staked amounts are now additionally tracked using a mapping which is updated only when a user leaves or enters staking, preventing this exploit from occurring. Users should now be careful to not transfer their OKLGFaaSTokens or they can risk losing their staked funds or rewards. OKLG - Finding #7 - Medium Description: While the setFeeSellMultiplier() function requires that the sum of the fees is below 40, the individual fee setters do not, which can be used to bypass the limit. Risk/Impact: Buy and sell fees can be set to an unlimited percentage, potentially resulting in a larger fee than expected. Reproduction Steps: 1 . Each individual fee is set to 0. 2 . The fee multiplier is set to 5. As the total fees will be less than 40% with this multiplier, this call is permitted. 3 . Each individual fee is then set to 10. The total fees with the fee multiplier of 5 is now over 100%. Recommendation: Each individual fee setter should check that the total resulting fees do not exceed 40%. OKLGPasswordManager - Finding #8 - Medium Description: The price for a single store and a bulk store are currently the same even though their prices are intended to be different. Risk/Impact: Users will be able to pay the same price for a single store or multiple stores. Recommendation: If functionality to fetch this Product's price is implemented, a check can be made to ensure the provided amount is at least the calculated price based on the number of Accounts they are storing. The intended 50% discount can be included in this calculation. OKLGPasswordManager - Finding #9 - Medium (Partially Resolved) Description: Users can store multiple Accounts with the same ID. Risk/Impact: If a second Account with the same ID is stored, users will not be able to update or delete the Account. In addition, users will not be able to fetch the second Account by its ID. Recommendation: Disallow users from storing an Account with an ID equal to one that they have already stored. Update: The team has implemented the following lines in the addAccount() function: require( userAccountIdIndexes[msg.sender][_id] == 0, 'this ID is already being used, the account should be updated instead' ); userAccountIdIndexes[msg.sender][_id] = userAccounts[msg.sender].length; While this partially resolves the issue, users will still be able to overwrite their first created Account. A user's first created Account will set userAccountIdIndexes[msg.sender][_id] to 0 as their Accounts length is 0. If a user tries tocreate another Account with this same ID, the above require statement will pass, and the user's first Account will be overwritten. OKLGRaffle - Finding #10 - Low Description: In the drawWinner() function, all the information used in the calculation to draw the winning ticket is on-chain, This is common, albeit not best practice. Miners and bots in the memory pool may be able to predict the results and may take action accordingly to secure profits; though the chance of this is extremely low. Risk/Impact: There is a chance that a user can wait to draw the winner until they have predicted the desired winning address. As a winning ticket cannot be drawn until the raffle has ended and anyone can call the function to draw the winner, the likelihood of this is extremely low, but is slightly higher in Raffles with a low number of participants. Recommendation: Chainlink can be used as a reliable and secure source of randomness that cannot be manipulated or predicted by miners. OKLGPasswordManager - Finding #11 - Low (Resolved) Description: In multiple instances, the _userInfo array must be looped through in order to find the Account corresponding to a specified ID. Risk/Impact: While this is not a major issue unless a user has stored a massive number of Accounts, it is a waste of gas. Recommendation: The userAccounts mapping should be converted into a mapping(address => mapping(ID => AccountInfo[])). An Account could then be found in O(1) time by using the ID as a key instead of looping through their Accounts array. Resolution: The team has implemented a second mapping to track the indexes of each user's Account IDs. While this is a less efficient solution than proposed, a user's Account list no longer has to be looped though to find a specific Account. OKLGSpend - Finding #12 - Low Description: Any excess funds sent to this contract as payment for a Product will not be returned to the user purchasing the Product. Risk/Impact: Users will lose any excess funds sent as payment. Recommendation: Excess funds should be transferred back to the corresponding OKLGProduct contract, where it should then be transferred back the the user. Update: Excess funds are now returned back to the OKLGProduct it was sent from; however, these funds are not subsequently returned to the user. KetherNFTLoaner - Finding #13 - Low Description: If a user removes a loan, any excess amount sent in the blockchain's native token sent is not returned to them after the loanee is paid. Excess funds are instead stored in the contract. Risk/Impact: Users will lose any excess funds sent as payment.Recommendation: Excess funds should be calculated and transferred back to the sender. OKLG - Finding #14 - Informational Description:. The current buyback amount is calculated based on a percentage the amount of tokens in the OKLG token's Uniswap Pair address. Risk/Impact: If the buyback token is not set to OKLG, it is possible that the buyback amount can cause the buyback token to be susceptible to frontrunning. Recommendation: The project team should ensure that the buyback amount is not too large to mitigate the risk of frontrunning. CONTRACTS OVERVIEW KetherNFTLoaner Contract: This contract allows users to loan their KetherNFTs to other users for a specified time and cost. Users can add a "plot" at any time, transferring their specified KetherNFT to this contract and allowing users to purchase it as a loan, given it is not currently loaned out. Users must pay a "loan service charge" in order to add a plot. When adding, a user can choose to specify a loan price per day in the blockchain's native token and a max loan duration for their KetherNFT. The user can update these values to any amount at any time. If the values are not specified, they will default to the contract's default prices and max durations. After a plot has been added, users can borrow the plot for any amount of time less than or equal to the loan's maximum loan duration by paying the appropriate amount. A percentage fee is taken from the total payment amount and transferred to the owner of this contract; the remainder is transferred to the plot owner. After payment is sent, the KetherNFT's publish() function is called using the loanee's specified publish parameters. The loanee can republish the KetherNFT with different publish parameters at any time while their loan is still active. If a plot's loan is inactive, the plot owner can publish the KetherNFT. As the KetherNFT contract was not in the scope of this audit, we cannot verify the security or functionality of this contract's interactions with it. Once a loan has ended, the plot owner must remove the loan. If a plot owner wishes to cancel a loan early, they can pay the original loan price back to the loanee. The loan service charge, default loan price per day, default max loan duration, and loan percentage fee values can be updated by the owner at any time. Once a KetherNFT has been transferred to this contract, it cannot be transferred back to its original owner. MTGYOKLGSwap Contract: This contract allows users to swap The Moontography Project token ($MTGY) for $OKLG at a defined exchange ratio. The owner can update the exchange ratio of $MTGY to $OKLG at any time. The owner can withdraw any tokens from this address at any time.This contract must be funded with OKLG tokens in order to complete swaps. OKLetsApe Contract: The maximum supply of the ok.lets.ape. NFT ($OKLApe) is 10,000. Users can choose to burn their tokens in order to reduce the total supply, if desired. Users can pay a specified price in the blockchain's native token in order to mint tokens. The minting price is then forwarded to a payment address, which can be updated by the owner at any time. Any extra of the blockchain's native token sent to the contract when minting will be returned to the user. Users can hold up to a "maximum wallet amount" of tokens in their address at any time. Users can only mint tokens if a public sale is active, or if a presale is active and they have been added to the whitelist. In each public or presale round, only a limited amount of tokens can be minted. The owner can reset the round's mint counter or update the maximum mints per round at any time. If a "mint cost contract" is set, the price to mint a token will be fetched from that contract address. If the mint cost contract is not set, the price will be set to this contract's specified mint cost. The owner can update the mint cost contract address or this contract's mint cost amount at any time. This contract also supports the EIP-2981 NFT royalty standard. The owner can update the royalty address and the royalty percentage at any time. The owner can start and stop a presale or public sale round at at any time. The owner and authorized users can mint any amount of tokens for free, as long as it does not result in the token supply exceeding the maximum supply. The owner and authorized users can also mint using any token ID that has been previously burned. The owner and authorized users are exempt from the maximum wallet amount limitation. The owner can add or remove any address from the presale whitelist at any time. The owner can grant or revoke authorization to any address at any time. The owner can update the maximum wallet amount and the base URI for tokens at any time. The owner can pause the contract at any time, disallowing token transfers. OKLG Contract: OKLG is a community-driven ERC20 token with a total supply of 420690000000. All tokens are sent to the owner upon deployment. Trading begins as disabled, preventing buys and sells for non-excluded addresses. Excluded addresses are only permitted to buy tokens during this time. Once trading is enabled by the owner, it cannot be disabled. In addition to the trading limitation, the owner can disable transfers of any kind for every address except transfers from themselves at any time. Excluded addresses can still purchase tokens while trading is disabled. When buying or selling, a percentage tax fee and project fee are taken. The tokens collected through the tax fee are removed from the circulating supply; this serves as a frictionless fee redistribution which automatically benefits all token holders at the time of each transaction. On each sell, a capped amount of accumulated project fees are swapped for the blockchain's native token. Percentages of this amount are then sent to a treasury address, used for the blockchain's native token rewards, and used to buy a specified "buyback token" which is then sent to a buyback address. The capped amount to swap is calculated using a percentage of the Uniswap Pair's token balance. This percentage can be updated by the owner to any amount at any time. The project team exercise caution when setting this percentage to a large amount due to risk of frontrunning. The owner can update the tax fee to maximum of 10% at any time.The owner can update the project fee to any percentage at any time. The owner can update the distribution of the project fee to any percentages at any time. The owner can exclude any address from transfer fees and dividends at any time. Users can also be excluded from fees through an owner-specified Fee Exclusion contract. The Fee Exclusion contract, treasury address, buyback token address, buyback receiver address, can be updated by the owner at any time. Users can claim rewards in the blockchain's native token or other token rewards based on the users OKLG balance. Other tokens sent to this contract can also be claimed as rewards based on the user's OKLG balance. When claiming, a user can earn additional rewards if they are determined to be eligible for a reward booster by a Boost Rewards contract. The rewards booster percentage can be updated by the owner at any time. Both the Fee Exclusion and Boost Rewards contract were not included in the scope of this audit, so we are unable to provide an assessment of this contract with regards to security. If a user either claims rewards or buys, sells, or receives tokens, a claim wait period must pass before they can claim rewards again. The owner can update the claim wait to any amount at any time. The owner can withdraw any of the blockchain's native token from the contract at any time. The owner can add or remove any address from the list of Uniswap Pair addresses at any time. The owner can add or remove any address from the blacklist at any time, disabling any transfers to or from the address. Any address that purchases tokens in the same block that trading is enabled will be automatically added to the blacklist. OKLGSpend Contract: This contract is used to manage Product prices and ensure that payments for Products are sufficient. When payment for a Product is sent to this contract, it ensures that the required amount has been sent according to the Product's price. The Product price is then sent to a payment wallet. Any excess payment sent will be returned to the user. Prices are converted from the blockchain's native token to USD using a PriceFeed contract. The PriceFeed contract was not provided in the scope of this audit, so we are unable to provide an assessment of this contract with regards to security. The owner can override product prices for specified addresses at any time. The owner can update the paymentWallet and PriceFeed contract at any time. The owner can also update the price of a Product at any time. The owner can withdraw any of the blockchain's native token or other tokens from this contract at any time. OKLGProduct Contract: This contract is inherited by the specified contracts below. When Products are paid for, the amount is sent to the OKLGSpend contract where the Product's price is calculated and subsequently sent to a payment address. The owner can update the OKLGSpend contract address, the Product's ID, and a referenced token address at any time. The owner can withdraw any of the blockchain's native token or other tokens from this contract at any time. OKLGAirDropper Contract:This contract is an OKLGProduct that allows users to send any ERC20, ERC721, or the blockchain's native token amounts to a list of addresses. To send an airdrop, users must pay a product fee in the blockchain's native token along with providing the tokens to be airdropped. Airdrops of the blockchain's native token currently do not work as intended; users will not be able to send these Airdrops. OKLGAtomicSwapInstance Contract: This contract is an OKLGProduct that allows users to swap a specified token between chains using an instance of this contract on each chain. To swap, users must pay a product fee in the blockchain's native token to create the contract; this amount is then sent to the OKLGSpend contract. If a max swap amount has been set, users cannot exceed it in a single swap. A gas amount is then sent from this contract to an Oracle address; users should ensure that this contract has a sufficient balance before initiating a swap. A swap ID will be created using a hash of the user, current timestamp, and the amount passed. The user must then pass the generated swap ID, swap timestamp, swap amount, and an additional gas fee to the instance of this contract on chain they are swapping to. The gas fee is then transferred to the Oracle address. Users cannot receive funds from the swap until the owner of the contract triggers the function to either refund the user on the original chain, or send the user tokens on the desired chain. If a token has a different number of decimals on each chain, the converted amount will be properly calculated using "target decimals" value, which should be set to the token's decimals on the other chain. The owner can update the target decimals to any amount at any time. As a fake swap ID and parameters can be passed into the contract, the owner must ensure that the user had actually initiated the swap on the original chain. In addition, the owner should be sure to remove the user's swap or mark it as complete on the chain which was not used to send tokens to the user. As these owner responsibilities require the use of off-chain logic, we are unable to provide an assessment of this contract with regards to security or proper functionality. The owner can update the gas fee to any amount at any time. The owner or a specified "token owner" address can set the contact to Active or Inactive at any time, enabling or disabling users from initiating a swap, receiving refunds, or completing a swap. Note that if a user has deposited their funds into an AtomicSwapInstance, and the instance on the chain to withdraw from is either Deactivated or set to Deactivated after the funds are deposited, users will not be able to complete their swap. The token owner can withdraw any of the contract's supported token at any time. The token owner address can update itself at any time. The owner can mark any swap as complete or incomplete at any time, either allowing a user to receive tokens multiple times or preventing them from receiving their tokens. The owner can update the oracle address, minimum gas for operation value, and decimals used to account for decimal differences when swapping. This contract should not be used with ERC-777 tokens. OKLGAtomicSwap Contract: This contract is an OKLGProduct that is used to manage and create new OKLGAtomicSwapInstance contractswith specified attributes, including an amount of the specified token to be transferred to the contract. Users must pay a product fee in the blockchain's native token to create the contract, which is sent to the OKLGSpend contract. When creating an OKLGAtomicSwapInstance, the user should ensure that a significant percentage of the total supply is stored in the contract so that funds exist when swapping occurs. Users should exercise caution when using fee-on-transfer tokens (unless the proper exemptions are made). The token owner of the newly created OKLGAtomicSwapInstance is set to the creator, and ownership is transferred to an Oracle address. Attributes of the OKLGAtomicSwapInstance to be deployed on the target chain are also stored in this contract. OKLGAtomicSwapInstances created through this contract can have their attributes updated by the owner, creator, or the oracle address at any time. The owner can update the product fee to any amount at any time. The owner can update the oracle address for each created AtomicSwapInstance at any time. As the Oracle address was not included in the scope of this audit, we are unable to provide an assessment of this contract with regards to security or proper functionality. OKLGFaasToken Contract: Any user may stake a specified ERC20 or ERC721 token into this contract's pool to earn rewards in a specified reward token. Staked tokens will be locked in this contract until their stake time has passed or the contract's unlock date has passed. Upon staking, an equivalent amount of OKLGFaaSTokens will be minted to the user. Their amount staked will also be stored in the contract. Users should not transfer their OKLGFaaSTokens to different addresses or they can potentially lose their staked funds and rewards. Users will earn a reward amount on each block based on the amount staked and the pool's reward rate. When unstaking, the user's OKLGFaaSTokens are transferred from them to the 0x..dead address. An emergency unstake function also exists, which will send the user all of their deposited tokens without claiming any rewards. Rewards are claimed when both staking and unstaking. Users can also harvest rewards without a deposit or withdrawal. If the reward token is equal to the stake token, users can choose to automatically stake earned rewards back into this contract when harvesting. Automatic compounding functionality is only supported for ERC20 tokens. Users will not be able to stake tokens or earn further rewards after the pool's end block has been reached. The end block is calculated using the pool's reward token's base supply divided by the pool's rewards per block. The creator of the pool has the ability to update the pool's base supply or current supply at any time. The creator should ensure that the contract's reward token balance is sufficient to distribute rewards. The creator or token owner address of the contract can withdraw the contract's reward token balance to the token owner address at any time. If this occurs, users will be able to withdraw their staked tokens from the contract. The team should avoid using ERC-777 tokens as the contract's reward token. The token owner can withdraw all rewards from the contract at any time. If this occurs, users will be able to withdraw their staked tokens. OKLGFaaS Contract:This contract is an OKLGProduct that allows users to create an OKLGFaasToken contract with specified attributes. Users must pay a product fee in the blockchain's native token to create the contract, which is sent to the OKLGSpend contract. When a new OKLGFaaSToken contract is created, the creator address is set to this contract and the token owner address is set to the user. If an OKLGFaaSToken contract is created using this contract, its pool's base supply and current supply cannot be updated after contract creation. The user can "remove" their contract if the contract's lock time has passed, which will withdraw the contract's reward balance to them and set the contract's reward supply to 0. OKLGRaffle Contract: This contract is an OKLGProduct that allows users to create Raffles with a reward token and amount/id, ticket token and price, start and end time, and maximum number of entries. Users must pay a product fee in the blockchain's native token to create a Raffle, which is sent to the OKLGSpend contract. Users can offer either an ERC20 token reward or an NFT as the Raffle's reward. Raffle participants can purchase tickets by passing in the ID of the raffle and the number of tickets to purchase. Participants can only purchase tickets for a Raffle between its start and end times. The total tickets a participant can purchase cannot exceed a specified maximum ticket amount per address unless this limit has not been set. Once the Raffle end time has passed, any address can trigger the function to draw the winner. A percentage administration fee is taken from the accumulated tokens from ticket sales and sent to this contract's owner; the remainder will be sent to the Raffle's owner. A random number corresponding to a ticket is then drawn by hashing the number of tickets and current block attributes. As all the information used in the calculation is from chain, miners and bots in the memory pool may be able to predict the results and may take action accordingly to secure profits; though the chance of this is extremely low. Chainlink can be used as a source of randomness that cannot be manipulated or predicted by miners. The ERC20 tokens or NFT is then transferred to the owner of the winning ticket, and the Raffle is marked as complete. If a Raffle has not been completed, its owner can choose to close and refund it, transferring the appropriate funds back to each user. If a Raffle is refunded, it will be marked as Completed. The owner of the contract can update the administration fee to any amount at any time. The owner of a Raffle should make sure they set an end date or else the winner can be drawn at any time. The owner of a Raffle can update the Raffle's end time and transfer its ownership as long as the Raffle has not been completed. This contract should not be used with ERC-777 tokens. OKLGPasswordManager Contract: This contract is an OKLGProduct which allows users to store information in Accounts. Users must pay a product fee in the blockchain's native token to create an Account, which is sent to the OKLGSpend contract. Users can also pay the same product fee to create multiple accounts at once. When creating an Account, a user will specify three strings: an "id", "iv", and "ciphertext".Users should be careful to not create an Account with the same id as their first created Account, as users will not be able to update or delete the first Account or fetch the Account by ID. A corresponding Account will be created which simply stores these strings along with its created timestamp and a marker to check if it has been marked as deleted. A user can update an account's iv and ciphertext data at any time at no cost. A user can "delete" any of their Accounts at any time, which will update the Account's timestamp and mark it as deleted. Users will not be able to create another Account with the same ID as a deleted Account (unless it was their first Account created). The Account will still remain stored in the contract if "deleted". MTGYTokenLocker Contract: This contract is an OKLGProduct that allows users to create Token Lockers. Users must pay a product fee in the blockchain's native token to create a Token Locker, which is sent to the OKLGSpend contract. When creating a Token Locker, users will specify the token to be locked, an end time, vesting periods, and authorized addresses that can withdraw the vested tokens. The number of vests will be distributed evenly across the total vesting period, where a linear amount of vested tokens can be withdrawn. The specified tokens will be transferred from the locker owner to this contract. If the number of vests is set to 1, all tokens will not be withdrawable until the end of the lock time. If an NFT is used as the locked token, it will also not be withdrawable until the end of the lock time. The owner of a locker can transfer its locker ownership at any time. The owner of a locker can update the locker's end time at any time. OKLGRewards Contract: OKLG token holders can use this contract to claim rewards in the blockchain's native token or in reward tokens, based on the amount of OKLG they hold. Users must wait until both this contract's claim wait has expired, and their OKLG claim wait has expired before claiming rewards. If a user is determined to be eligible by an associated Booster contract, users can earn additional rewards based on an associated BoostRewardsMultiplier contract's multiplier. If there is no BoostRewardsMultiplier contract set, this contract's multiplier will be used. The owner can reset any user's last claim time at any time, allowing them to be eligible to receive rewards instantly. The owner can update the OKLG contract, Booster contract, BoosterRewardsMultiplier contract, claim wait, and reward multiplier at any time. The owner can withdraw any of the blockchain's native token or any other token from this contract at any time. OKLGTrustedTimestamping Contract: This contract is an OKLGProduct that allows users to store Data Hashes. Users must pay a product fee in the blockchain's native token to store a hash, which is sent to the OKLGSpend contract. When storing a hash, users will specify a hash, file name, and file size in bytes, which are stored in the Data Hash. The DataHash will then be created, which consists of the specified attributes with the user attributes, along withthe current timestamp. Users can pass an address into this contract in order to fetch its stored DataHashes. Users can also fetch what address a DataHash belongs to by passing in its hash. EXTERNAL THREAT RESULTS Vulnerability Category Notes Result Arbitrary Storage Write N/A PASS Arbitrary Jump N/A PASS Centralization of Control The owner has the permissions listed above. The owner of any contract that is an OKLGProduct can withdraw any funds from it at any time. The owner or an Admin can withdraw any amount of funds from the AssetManager contract. The OKLGAtomicSwapInstance contract requires the use of off-chain logic to function properly. The owner of the OKLetsApe contract can mint tokens for free at any time. WARNING Delegate Call to Untrusted Contract N/A PASS Dependence on Predictable Variables It is possible for the Raffle winner to be predicted; however, the likelihood of this along with its use for exploitation is very low. PASS Deprecated Opcodes N/A PASS Ether Thief N/A PASS Exceptions N/A PASS External Calls N/A PASS Flash Loans N/A PASS Frontrunning If the buyback token is not set OKLG token in the OKLG Contract, and the buyback token may be susceptible to frontrunning. WARNING Integer Over/Underflow N/A PASS Logical Issues Issues mentioned above. WARNING Multiple Sends N/A PASS Oracles N/A PASSSuicide N/A PASS State Change External Calls N/A PASS Unbounded Loop N/A PASS Unchecked Retval N/A PASS User Supplied Assertion N/A PASS Critical Solidity Compiler N/A PASS Overall Contract Safety WARNING Vulnerability Category Notes Result CONTRACT SOURCE SUMMARY AND VISUALIZATIONS Name Address/Source Code Visualized (Hover-Zoom Recommended) HasERC20Balance ​ GitHub ​ Function Graph. Inheritance Chart. HasERC721Balance ​ GitHub ​ Function Graph. Inheritance Chart. IsERC20HODLer ​ GitHub ​ Function Graph. Inheritance Chart. KetherNFTLoaner ​ GitHub ​ Function Graph. Inheritance Chart. MTGYOKLGSwap ​ GitHub ​ Function Graph. Inheritance Chart. OKLetsApe ​ GitHub ​ Function Graph. Inheritance Chart. OKLG ​ GitHub ​ Function Graph. Inheritance Chart. OKLGAirdropper ​ GitHub ​ Function Graph. Inheritance Chart.OKLGAtomicSwap ​ GitHub ​ Function Graph. Inheritance Chart. OKLGAtomicSwapInstHash ​ GitHub ​ Function Graph. Inheritance Chart. OKLGFaaS ​ GitHub ​ Function Graph. Inheritance Chart. OKLGPasswordManager ​ GitHub ​ Function Graph. Inheritance Chart. OKLGRaffle ​ GitHub ​ Function Graph. Inheritance Chart. OKLGRewards ​ GitHub ​ Function Graph. Inheritance Chart. OKLGSpend ​ GitHub ​ Function Graph. Inheritance Chart. OKLGTokenLocker ​ GitHub ​ Function Graph. Inheritance Chart. OKLGTrustedTimestamping ​ GitHub ​ Function Graph. Inheritance Chart. GO HOME Copyright © Solidity Finance LLC. All rights reserved. Please review our Terms & Conditions, Privacy Policy, and other legal information here .
Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: 2.a Problem: In the withdrawLockedTokens() function, there is no check to confirm that the Locker's end time has passed when withdrawing NFTs. 2.b Fix: The withdrawable amount should be checked when the token is an NFT. Critical: 5.a Problem: The amount withdrawn from a locker is not properly updated when withdrawing tokens. 5.b Fix: Instead of adding to amountWithdrawn after a withdraw takes place, it should be set to the amount that was withdrawn in that transaction only. Observations: The team has implemented the recommended fixes. Conclusion: The audit of the OKLG Smart Contract has been completed and all issues have been resolved. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 1 Minor Issues: 2.a Problem: In addition, this value is updated after the token transfer takes place, opening the door for reentrancy attacks if the token locked is an ERC-777 compliant token. 2.b Fix: The team has implemented the recommendation to set the amountWithdrawn to the amount withdrawn in the single transaction and to occur after the amountWithdrawn is updated. Moderate Issues: 3.a Problem: The custom mint function can potentially cause issues with standard mints due to a token ID being reserved. 3.b Fix: The team has added logic to prevent any custom mints for any token ID that is greater than the current token ID counter, preventing this scenario from occurring. Critical Issues: 5.a Problem: The bulkSendMainTokens() function does not check if any blockchain's native token was passed into it (apart from the product cost payment) before sending the blockchain's native token to the list of addresses. 5.b Fix: The team has updated the code, however it does not make the Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: Problem: The setOracleAddress() function executes a function call for all of the contracts it manages. Fix: Added "_start" and "_max" parameters along with the while loop to limit the number of contracts that the setOracleAddress() function calls. Moderate Issues: Problem: A user can claim their rewards, transfer their funds to another address, then claim the rewards again. Fix: Staked amounts are now additionally tracked using a mapping which is updated only when a user leaves or enters staking, preventing this exploit from occurring. Major Issues: None Critical Issues: None Observations: The team has implemented the recommendations to resolve the issues. Conclusion: The team has successfully implemented the recommendations to resolve the minor and moderate issues. No major or critical issues were found.
pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is Initializable, ERC721, ERC721Enumerable, ERC721Metadata { uint256[50] private ______gap; } pragma solidity ^0.5.12; // functions needed from the v1 contract contract V1Token { function isApprovedForAll(address owner, address operator) public view returns (bool) {} function transferFrom(address from, address to, uint256 tokenId) public {} } // functions needed from v2 contract contract V2Token { function upgradeV1Token(uint256 tokenId, address v1Address, bool isControlToken, address to, uint256 platformFirstPercentageForToken, uint256 platformSecondPercentageForToken, bool hasTokenHadFirstSale, address payable[] calldata uniqueTokenCreatorsForToken) external {} } // Copyright (C) 2020 Asynchronous Art, Inc. // GNU General Public License v3.0 contract TokenUpgrader { event TokenUpgraded( uint256 tokenId, address v1TokenAddress, address v2TokenAddress ); // the address of the v1 token V1Token public v1TokenAddress; // the address of the v2 token V2Token public v2TokenAddress; // the admin address of who can setup descriptors for the tokens address public adminAddress; mapping(uint256 => bool) public isTokenReadyForUpgrade; mapping(uint256 => bool) public isControlTokenMapping; mapping(uint256 => bool) public hasTokenHadFirstSale; mapping(uint256 => uint256) public platformFirstPercentageForToken; mapping(uint256 => uint256) public platformSecondPercentageForToken; mapping(uint256 => address payable[]) public uniqueTokenCreatorMapping; constructor(V1Token _v1TokenAddress) public { adminAddress = msg.sender; v1TokenAddress = _v1TokenAddress; } // modifier for only allowing the admin to call modifier onlyAdmin() { require(msg.sender == adminAddress); _; } function setupV2Address(V2Token _v2TokenAddress) public onlyAdmin { require(address(v2TokenAddress) == address(0), "V2 address has already been initialized."); v2TokenAddress = _v2TokenAddress; } function prepareTokenForUpgrade(uint256 tokenId, bool isControlToken, uint256 platformFirstSalePercentage, uint256 platformSecondSalePercentage, bool hasHadFirstSale, address payable[] memory uniqueTokenCreators) public onlyAdmin { isTokenReadyForUpgrade[tokenId] = true; isControlTokenMapping[tokenId] = isControlToken; hasTokenHadFirstSale[tokenId] = hasHadFirstSale; uniqueTokenCreatorMapping[tokenId] = uniqueTokenCreators; platformFirstPercentageForToken[tokenId] = platformFirstSalePercentage; platformSecondPercentageForToken[tokenId] = platformSecondSalePercentage; } function upgradeTokenList(uint256[] memory tokenIds, address tokenOwner) public { for (uint256 i = 0; i < tokenIds.length; i++) { upgradeToken(tokenIds[i], tokenOwner); } } function upgradeToken(uint256 tokenId, address tokenOwner) public { // token must be ready to be upgraded require(isTokenReadyForUpgrade[tokenId], "Token not ready for upgrade."); // require the caller of this function to be the token owner or approved to transfer all of the owner's tokens require((tokenOwner == msg.sender) || v1TokenAddress.isApprovedForAll(tokenOwner, msg.sender), "Not owner or approved."); // transfer the v1 token to be owned by this contract (effectively burning it since this contract can't send it back out) v1TokenAddress.transferFrom(tokenOwner, address(this), tokenId); // call upgradeV1Token on the v2 contract -- this will mint the same token and send to the original owner v2TokenAddress.upgradeV1Token(tokenId, address(v1TokenAddress), isControlTokenMapping[tokenId], tokenOwner, platformFirstPercentageForToken[tokenId], platformSecondPercentageForToken[tokenId], hasTokenHadFirstSale[tokenId], uniqueTokenCreatorMapping[tokenId]); // emit an upgrade event emit TokenUpgraded(tokenId, address(v1TokenAddress), address(v2TokenAddress)); } }pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; import "./ERC721.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Metadata.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol"; contract ERC721Metadata is Initializable, Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ function initialize(string memory name, string memory symbol) public initializer { require(ERC721._hasBeenInitialized()); _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } // * // * @dev Internal function to burn a specific token. // * Reverts if the token does not exist. // * Deprecated, use _burn(uint256) instead. // * @param owner owner of the token to burn // * @param tokenId uint256 ID of the token being burned by the msg.sender // function _burn(address owner, uint256 tokenId) internal { // super._burn(owner, tokenId); // // Clear metadata (if any) // if (bytes(_tokenURIs[tokenId]).length != 0) { // delete _tokenURIs[tokenId]; // } // } uint256[50] private ______gap; } pragma solidity ^0.5.12; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; // interface for the v1 contract interface AsyncArtwork_v1 { function getControlToken(uint256 controlTokenId) external view returns (int256[] memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // Copyright (C) 2020 Asynchronous Art, Inc. // GNU General Public License v3.0 // Full notice https://github.com/asyncart/async-contracts/blob/master/LICENSE contract AsyncArtwork_v2 is Initializable, ERC721, ERC721Enumerable, ERC721Metadata { // An event whenever the platform address is updated event PlatformAddressUpdated( address platformAddress ); event PermissionUpdated( uint256 tokenId, address tokenOwner, address permissioned ); // An event whenever a creator is whitelisted with the token id and the layer count event CreatorWhitelisted( uint256 tokenId, uint256 layerCount, address creator ); // An event whenever royalty amount for a token is updated event PlatformSalePercentageUpdated ( uint256 tokenId, uint256 platformFirstPercentage, uint256 platformSecondPercentage ); // An event whenever artist secondary sale percentage is updated event ArtistSecondSalePercentUpdated ( uint256 artistSecondPercentage ); // An event whenever a bid is proposed event BidProposed( uint256 tokenId, uint256 bidAmount, address bidder ); // An event whenever an bid is withdrawn event BidWithdrawn( uint256 tokenId ); // An event whenever a buy now price has been set event BuyPriceSet( uint256 tokenId, uint256 price ); // An event when a token has been sold event TokenSale( // the id of the token uint256 tokenId, // the price that the token was sold for uint256 salePrice, // the address of the buyer address buyer ); // An event whenever a control token has been updated event ControlLeverUpdated( // the id of the token uint256 tokenId, // an optional amount that the updater sent to boost priority of the rendering uint256 priorityTip, // the number of times this control lever can now be updated int256 numRemainingUpdates, // the ids of the levers that were updated uint256[] leverIds, // the previous values that the levers had before this update (for clients who want to animate the change) int256[] previousValues, // the new updated value int256[] updatedValues ); // struct for a token that controls part of the artwork struct ControlToken { // number that tracks how many levers there are uint256 numControlLevers; // The number of update calls this token has (-1 for infinite) int256 numRemainingUpdates; // false by default, true once instantiated bool exists; // false by default, true once setup by the artist bool isSetup; // the levers that this control token can use mapping(uint256 => ControlLever) levers; } // struct for a lever on a control token that can be changed struct ControlLever { // // The minimum value this token can have (inclusive) int256 minValue; // The maximum value this token can have (inclusive) int256 maxValue; // The current value for this token int256 currentValue; // false by default, true once instantiated bool exists; } // struct for a pending bid struct PendingBid { // the address of the bidder address payable bidder; // the amount that they bid uint256 amount; // false by default, true once instantiated bool exists; } struct WhitelistReservation { // the address of the creator address creator; // the amount of layers they're expected to mint uint256 layerCount; } // track whether this token was sold the first time or not (used for determining whether to use first or secondary sale percentage) mapping(uint256 => bool) public tokenDidHaveFirstSale; // if a token's URI has been locked or not mapping(uint256 => bool) public tokenURILocked; // map control token ID to its buy price mapping(uint256 => uint256) public buyPrices; // mapping of addresses to credits for failed transfers mapping(address => uint256) public failedTransferCredits; // mapping of tokenId to percentage of sale that the platform gets on first sales mapping(uint256 => uint256) public platformFirstSalePercentages; // mapping of tokenId to percentage of sale that the platform gets on secondary sales mapping(uint256 => uint256) public platformSecondSalePercentages; // what tokenId creators are allowed to mint (and how many layers) mapping(uint256 => WhitelistReservation) public creatorWhitelist; // for each token, holds an array of the creator collaborators. For layer tokens it will likely just be [artist], for master tokens it may hold multiples mapping(uint256 => address payable[]) public uniqueTokenCreators; // map a control token ID to its highest bid mapping(uint256 => PendingBid) public pendingBids; // map a control token id to a control token struct // SWC-State Variable Default Visibility: L156 mapping(uint256 => ControlToken) controlTokenMapping; // mapping of addresses that are allowed to control tokens on your behalf mapping(address => mapping(uint256 => address)) public permissionedControllers; // the percentage of sale that an artist gets on secondary sales uint256 public artistSecondSalePercentage; // gets incremented to placehold for tokens not minted yet uint256 public expectedTokenSupply; // the minimum % increase for new bids coming uint256 public minBidIncreasePercent; // the address of the platform (for receving commissions and royalties) address payable public platformAddress; // the address of the contract that can upgrade from v1 to v2 tokens address public upgraderAddress; function initialize(string memory name, string memory symbol, uint256 initialExpectedTokenSupply, address _upgraderAddress) public initializer { ERC721.initialize(); ERC721Enumerable.initialize(); ERC721Metadata.initialize(name, symbol); // starting royalty amounts artistSecondSalePercentage = 10; // intitialize the minimum bid increase percent minBidIncreasePercent = 1; // by default, the platformAddress is the address that mints this contract platformAddress = msg.sender; // set the upgrader address upgraderAddress = _upgraderAddress; // set the initial expected token supply expectedTokenSupply = initialExpectedTokenSupply; require(expectedTokenSupply > 0); } // modifier for only allowing the platform to make a call modifier onlyPlatform() { require(msg.sender == platformAddress); _; } modifier onlyWhitelistedCreator(uint256 masterTokenId, uint256 layerCount) { require(creatorWhitelist[masterTokenId].creator == msg.sender); require(creatorWhitelist[masterTokenId].layerCount == layerCount); _; } // reserve a tokenID and layer count for a creator. Define a platform royalty percentage per art piece (some pieces have higher or lower amount) function whitelistTokenForCreator(address creator, uint256 masterTokenId, uint256 layerCount, uint256 platformFirstSalePercentage, uint256 platformSecondSalePercentage) external onlyPlatform { // the tokenID we're reserving must be the current expected token supply require(masterTokenId == expectedTokenSupply); // Async pieces must have at least 1 layer require (layerCount > 0); // reserve the tokenID for this creator creatorWhitelist[masterTokenId] = WhitelistReservation(creator, layerCount); // increase the expected token supply expectedTokenSupply = masterTokenId.add(layerCount).add(1); // define the platform percentages for this token here platformFirstSalePercentages[masterTokenId] = platformFirstSalePercentage; platformSecondSalePercentages[masterTokenId] = platformSecondSalePercentage; emit CreatorWhitelisted(masterTokenId, layerCount, creator); } // Allows the current platform address to update to something different function updatePlatformAddress(address payable newPlatformAddress) external onlyPlatform { platformAddress = newPlatformAddress; emit PlatformAddressUpdated(newPlatformAddress); } // Allows platform to waive the first sale requirement for a token (for charity events, special cases, etc) function waiveFirstSaleRequirement(uint256 tokenId) external onlyPlatform { // This allows the token sale proceeds to go to the current owner (rather than be distributed amongst the token's creators) tokenDidHaveFirstSale[tokenId] = true; } // Allows platform to change the royalty percentage for a specific token function updatePlatformSalePercentage(uint256 tokenId, uint256 platformFirstSalePercentage, uint256 platformSecondSalePercentage) external onlyPlatform { // set the percentages for this token platformFirstSalePercentages[tokenId] = platformFirstSalePercentage; platformSecondSalePercentages[tokenId] = platformSecondSalePercentage; // emit an event to notify that the platform percent for this token has changed emit PlatformSalePercentageUpdated(tokenId, platformFirstSalePercentage, platformSecondSalePercentage); } // Allows the platform to change the minimum percent increase for incoming bids function updateMinimumBidIncreasePercent(uint256 _minBidIncreasePercent) external onlyPlatform { require((_minBidIncreasePercent > 0) && (_minBidIncreasePercent <= 50), "Bid increases must be within 0-50%"); // set the new bid increase percent minBidIncreasePercent = _minBidIncreasePercent; } // Allow the platform to update a token's URI if it's not locked yet (for fixing tokens post mint process) function updateTokenURI(uint256 tokenId, string calldata tokenURI) external onlyPlatform { // ensure that this token exists require(_exists(tokenId)); // ensure that the URI for this token is not locked yet require(tokenURILocked[tokenId] == false); // update the token URI super._setTokenURI(tokenId, tokenURI); } // Locks a token's URI from being updated function lockTokenURI(uint256 tokenId) external onlyPlatform { // ensure that this token exists require(_exists(tokenId)); // lock this token's URI from being changed tokenURILocked[tokenId] = true; } // Allows platform to change the percentage that artists receive on secondary sales function updateArtistSecondSalePercentage(uint256 _artistSecondSalePercentage) external onlyPlatform { // update the percentage that artists get on secondary sales artistSecondSalePercentage = _artistSecondSalePercentage; // emit an event to notify that the artist second sale percent has updated emit ArtistSecondSalePercentUpdated(artistSecondSalePercentage); } function setupControlToken(uint256 controlTokenId, string calldata controlTokenURI, int256[] calldata leverMinValues, int256[] calldata leverMaxValues, int256[] calldata leverStartValues, int256 numAllowedUpdates, address payable[] calldata additionalCollaborators ) external { // Hard cap the number of levers a single control token can have require (leverMinValues.length <= 500, "Too many control levers."); // Hard cap the number of collaborators a single control token can have require (additionalCollaborators.length <= 50, "Too many collaborators."); // check that a control token exists for this token id require(controlTokenMapping[controlTokenId].exists, "No control token found"); // ensure that this token is not setup yet require(controlTokenMapping[controlTokenId].isSetup == false, "Already setup"); // ensure that only the control token artist is attempting this mint require(uniqueTokenCreators[controlTokenId][0] == msg.sender, "Must be control token artist"); // enforce that the length of all the array lengths are equal require((leverMinValues.length == leverMaxValues.length) && (leverMaxValues.length == leverStartValues.length), "Values array mismatch"); // require the number of allowed updates to be infinite (-1) or some finite number require((numAllowedUpdates == -1) || (numAllowedUpdates > 0), "Invalid allowed updates"); // mint the control token here super._safeMint(msg.sender, controlTokenId); // set token URI super._setTokenURI(controlTokenId, controlTokenURI); // create the control token controlTokenMapping[controlTokenId] = ControlToken(leverStartValues.length, numAllowedUpdates, true, true); // create the control token levers now for (uint256 k = 0; k < leverStartValues.length; k++) { // enforce that maxValue is greater than or equal to minValue require(leverMaxValues[k] >= leverMinValues[k], "Max val must >= min"); // enforce that currentValue is valid require((leverStartValues[k] >= leverMinValues[k]) && (leverStartValues[k] <= leverMaxValues[k]), "Invalid start val"); // add the lever to this token controlTokenMapping[controlTokenId].levers[k] = ControlLever(leverMinValues[k], leverMaxValues[k], leverStartValues[k], true); } // the control token artist can optionally specify additional collaborators on this layer for (uint256 i = 0; i < additionalCollaborators.length; i++) { // can't provide burn address as collaborator require(additionalCollaborators[i] != address(0)); uniqueTokenCreators[controlTokenId].push(additionalCollaborators[i]); } } // upgrade a token from the v1 contract to this v2 version function upgradeV1Token(uint256 tokenId, address v1Address, bool isControlToken, address to, uint256 platformFirstPercentageForToken, uint256 platformSecondPercentageForToken, bool hasTokenHadFirstSale, address payable[] calldata uniqueTokenCreatorsForToken) external { // get reference to v1 token contract AsyncArtwork_v1 v1Token = AsyncArtwork_v1(v1Address); // require that only the upgrader address is calling this method require(msg.sender == upgraderAddress, "Only upgrader can call."); // preserve the unique token creators uniqueTokenCreators[tokenId] = uniqueTokenCreatorsForToken; if (isControlToken) { // preserve the control token details if it's a control token int256[] memory controlToken = v1Token.getControlToken(tokenId); // Require control token to be a valid size (multiple of 3) require(controlToken.length % 3 == 0, "Invalid control token."); // Require control token to have at least 1 lever require(controlToken.length > 0, "Control token must have levers"); // Setup the control token // Use -1 for numRemainingUpdates since v1 tokens were infinite use controlTokenMapping[tokenId] = ControlToken(controlToken.length / 3, -1, true, true); // set each lever for the control token. getControlToken returns levers like: // [minValue, maxValue, curValue, minValue, maxValue, curValue, ...] so they always come in groups of 3 for (uint256 k = 0; k < controlToken.length; k+=3) { controlTokenMapping[tokenId].levers[k / 3] = ControlLever(controlToken[k], controlToken[k + 1], controlToken[k + 2], true); } } // Set the royalty percentage for this token platformFirstSalePercentages[tokenId] = platformFirstPercentageForToken; platformSecondSalePercentages[tokenId] = platformSecondPercentageForToken; // whether this token has already had its first sale tokenDidHaveFirstSale[tokenId] = hasTokenHadFirstSale; // Mint and transfer the token to the original v1 token owner super._safeMint(to, tokenId); // set the same token URI super._setTokenURI(tokenId, v1Token.tokenURI(tokenId)); } function mintArtwork(uint256 masterTokenId, string calldata artworkTokenURI, address payable[] calldata controlTokenArtists) external onlyWhitelistedCreator(masterTokenId, controlTokenArtists.length) { // Can't mint a token with ID 0 anymore require(masterTokenId > 0); // Mint the token that represents ownership of the entire artwork super._safeMint(msg.sender, masterTokenId); // set the token URI for this art super._setTokenURI(masterTokenId, artworkTokenURI); // track the msg.sender address as the artist address for future royalties uniqueTokenCreators[masterTokenId].push(msg.sender); // iterate through all control token URIs (1 for each control token) for (uint256 i = 0; i < controlTokenArtists.length; i++) { // can't provide burn address as artist require(controlTokenArtists[i] != address(0)); // determine the tokenID for this control token uint256 controlTokenId = masterTokenId + i + 1; // add this control token artist to the unique creator list for that control token uniqueTokenCreators[controlTokenId].push(controlTokenArtists[i]); // stub in an existing control token so exists is true controlTokenMapping[controlTokenId] = ControlToken(0, 0, true, false); // Layer control tokens use the same royalty percentage as the master token platformFirstSalePercentages[controlTokenId] = platformFirstSalePercentages[masterTokenId]; platformSecondSalePercentages[controlTokenId] = platformSecondSalePercentages[masterTokenId]; if (controlTokenArtists[i] != msg.sender) { bool containsControlTokenArtist = false; for (uint256 k = 0; k < uniqueTokenCreators[masterTokenId].length; k++) { if (uniqueTokenCreators[masterTokenId][k] == controlTokenArtists[i]) { containsControlTokenArtist = true; break; } } if (containsControlTokenArtist == false) { uniqueTokenCreators[masterTokenId].push(controlTokenArtists[i]); } } } } // Bidder functions function bid(uint256 tokenId) external payable { // don't allow bids of 0 require(msg.value > 0); // don't let owners/approved bid on their own tokens require(_isApprovedOrOwner(msg.sender, tokenId) == false); // check if there's a high bid if (pendingBids[tokenId].exists) { // enforce that this bid is higher by at least the minimum required percent increase require(msg.value >= (pendingBids[tokenId].amount.mul(minBidIncreasePercent.add(100)).div(100)), "Bid must increase by min %"); // Return bid amount back to bidder safeFundsTransfer(pendingBids[tokenId].bidder, pendingBids[tokenId].amount); } // set the new highest bid pendingBids[tokenId] = PendingBid(msg.sender, msg.value, true); // Emit event for the bid proposal emit BidProposed(tokenId, msg.value, msg.sender); } // allows an address with a pending bid to withdraw it function withdrawBid(uint256 tokenId) external { // check that there is a bid from the sender to withdraw (also allows platform address to withdraw a bid on someone's behalf) require((pendingBids[tokenId].bidder == msg.sender) || (msg.sender == platformAddress)); // attempt to withdraw the bid _withdrawBid(tokenId); } function _withdrawBid(uint256 tokenId) internal { require(pendingBids[tokenId].exists); // Return bid amount back to bidder safeFundsTransfer(pendingBids[tokenId].bidder, pendingBids[tokenId].amount); // clear highest bid pendingBids[tokenId] = PendingBid(address(0), 0, false); // emit an event when the highest bid is withdrawn emit BidWithdrawn(tokenId); } // Buy the artwork for the currently set price // Allows the buyer to specify a minimum remaining uses they'll accept function takeBuyPrice(uint256 tokenId, int256 expectedRemainingUpdates) external payable { // don't let owners/approved buy their own tokens require(_isApprovedOrOwner(msg.sender, tokenId) == false); // get the sale amount uint256 saleAmount = buyPrices[tokenId]; // check that there is a buy price require(saleAmount > 0); // check that the buyer sent exact amount to purchase require(msg.value == saleAmount); // if this is a control token if (controlTokenMapping[tokenId].exists) { // ensure that the remaining uses on the token is equal to what buyer expects require(controlTokenMapping[tokenId].numRemainingUpdates == expectedRemainingUpdates); } // Return all highest bidder's money if (pendingBids[tokenId].exists) { // Return bid amount back to bidder safeFundsTransfer(pendingBids[tokenId].bidder, pendingBids[tokenId].amount); // clear highest bid pendingBids[tokenId] = PendingBid(address(0), 0, false); } onTokenSold(tokenId, saleAmount, msg.sender); } // Take an amount and distribute it evenly amongst a list of creator addresses function distributeFundsToCreators(uint256 amount, address payable[] memory creators) private { uint256 creatorShare = amount.div(creators.length); for (uint256 i = 0; i < creators.length; i++) { safeFundsTransfer(creators[i], creatorShare); } } // When a token is sold via list price or bid. Distributes the sale amount to the unique token creators and transfer // the token to the new owner function onTokenSold(uint256 tokenId, uint256 saleAmount, address to) private { // if the first sale already happened, then give the artist + platform the secondary royalty percentage if (tokenDidHaveFirstSale[tokenId]) { // give platform its secondary sale percentage uint256 platformAmount = saleAmount.mul(platformSecondSalePercentages[tokenId]).div(100); safeFundsTransfer(platformAddress, platformAmount); // distribute the creator royalty amongst the creators (all artists involved for a base token, sole artist creator for layer ) uint256 creatorAmount = saleAmount.mul(artistSecondSalePercentage).div(100); distributeFundsToCreators(creatorAmount, uniqueTokenCreators[tokenId]); // cast the owner to a payable address address payable payableOwner = address(uint160(ownerOf(tokenId))); // transfer the remaining amount to the owner of the token safeFundsTransfer(payableOwner, saleAmount.sub(platformAmount).sub(creatorAmount)); } else { tokenDidHaveFirstSale[tokenId] = true; // give platform its first sale percentage uint256 platformAmount = saleAmount.mul(platformFirstSalePercentages[tokenId]).div(100); safeFundsTransfer(platformAddress, platformAmount); // this is a token first sale, so distribute the remaining funds to the unique token creators of this token // (if it's a base token it will be all the unique creators, if it's a control token it will be that single artist) distributeFundsToCreators(saleAmount.sub(platformAmount), uniqueTokenCreators[tokenId]); } // clear highest bid pendingBids[tokenId] = PendingBid(address(0), 0, false); // Transfer token to msg.sender _transferFrom(ownerOf(tokenId), to, tokenId); // Emit event emit TokenSale(tokenId, saleAmount, to); } // Owner functions // Allow owner to accept the highest bid for a token function acceptBid(uint256 tokenId, uint256 minAcceptedAmount) external { // check if sender is owner/approved of token require(_isApprovedOrOwner(msg.sender, tokenId)); // check if there's a bid to accept require(pendingBids[tokenId].exists); // check that the current pending bid amount is at least what the accepting owner expects require(pendingBids[tokenId].amount >= minAcceptedAmount); // process the sale onTokenSold(tokenId, pendingBids[tokenId].amount, pendingBids[tokenId].bidder); } // Allows owner of a control token to set an immediate buy price. Set to 0 to reset. function makeBuyPrice(uint256 tokenId, uint256 amount) external { // check if sender is owner/approved of token require(_isApprovedOrOwner(msg.sender, tokenId)); // set the buy price buyPrices[tokenId] = amount; // emit event emit BuyPriceSet(tokenId, amount); } // return the number of times that a control token can be used function getNumRemainingControlUpdates(uint256 controlTokenId) external view returns (int256) { require(controlTokenMapping[controlTokenId].exists, "Token does not exist."); return controlTokenMapping[controlTokenId].numRemainingUpdates; } // return the min, max, and current value of a control lever function getControlToken(uint256 controlTokenId) external view returns(int256[] memory) { require(controlTokenMapping[controlTokenId].exists, "Token does not exist."); ControlToken storage controlToken = controlTokenMapping[controlTokenId]; int256[] memory returnValues = new int256[](controlToken.numControlLevers.mul(3)); uint256 returnValIndex = 0; // iterate through all the control levers for this control token for (uint256 i = 0; i < controlToken.numControlLevers; i++) { returnValues[returnValIndex] = controlToken.levers[i].minValue; returnValIndex = returnValIndex.add(1); returnValues[returnValIndex] = controlToken.levers[i].maxValue; returnValIndex = returnValIndex.add(1); returnValues[returnValIndex] = controlToken.levers[i].currentValue; returnValIndex = returnValIndex.add(1); } return returnValues; } // anyone can grant permission to another address to control a specific token on their behalf. Set to Address(0) to reset. function grantControlPermission(uint256 tokenId, address permissioned) external { permissionedControllers[msg.sender][tokenId] = permissioned; emit PermissionUpdated(tokenId, msg.sender, permissioned); } // Allows owner (or permissioned user) of a control token to update its lever values // Optionally accept a payment to increase speed of rendering priority function useControlToken(uint256 controlTokenId, uint256[] calldata leverIds, int256[] calldata newValues) external payable { // check if sender is owner/approved of token OR if they're a permissioned controller for the token owner require(_isApprovedOrOwner(msg.sender, controlTokenId) || (permissionedControllers[ownerOf(controlTokenId)][controlTokenId] == msg.sender), "Owner or permissioned only"); // check if control exists require(controlTokenMapping[controlTokenId].exists, "Token does not exist."); // get the control token reference ControlToken storage controlToken = controlTokenMapping[controlTokenId]; // check that number of uses for control token is either infinite or is positive require((controlToken.numRemainingUpdates == -1) || (controlToken.numRemainingUpdates > 0), "No more updates allowed"); // collect the previous lever values for the event emit below int256[] memory previousValues = new int256[](newValues.length); for (uint256 i = 0; i < leverIds.length; i++) { // get the control lever ControlLever storage lever = controlTokenMapping[controlTokenId].levers[leverIds[i]]; // Enforce that the new value is valid require((newValues[i] >= lever.minValue) && (newValues[i] <= lever.maxValue), "Invalid val"); // Enforce that the new value is different require(newValues[i] != lever.currentValue, "Must provide different val"); // grab previous value for the event emit // SWC-Presence of unused variables: L600 int256 previousValue = lever.currentValue; // Update token current value lever.currentValue = newValues[i]; // collect the previous lever values for the event emit below previousValues[i] = previousValue; } // if there's a payment then send it to the platform (for higher priority updates) if (msg.value > 0) { safeFundsTransfer(platformAddress, msg.value); } // if this control token is finite in its uses if (controlToken.numRemainingUpdates > 0) { // decrease it down by 1 controlToken.numRemainingUpdates = controlToken.numRemainingUpdates - 1; // since we used one of those updates, withdraw any existing bid for this token if exists if (pendingBids[controlTokenId].exists) { _withdrawBid(controlTokenId); } } // emit event emit ControlLeverUpdated(controlTokenId, msg.value, controlToken.numRemainingUpdates, leverIds, previousValues, newValues); } // Allows a user to withdraw all failed transaction credits function withdrawAllFailedCredits() external { uint256 amount = failedTransferCredits[msg.sender]; require(amount != 0); require(address(this).balance >= amount); failedTransferCredits[msg.sender] = 0; (bool successfulWithdraw, ) = msg.sender.call.value(amount)(""); require(successfulWithdraw); } // Safely transfer funds and if fail then store that amount as credits for a later pull function safeFundsTransfer(address payable recipient, uint256 amount) internal { // attempt to send the funds to the recipient // SWC-Reentrancy: L647 (bool success, ) = recipient.call.value(amount).gas(2300)(""); // if it failed, update their credit balance so they can pull it later if (success == false) { failedTransferCredits[recipient] = failedTransferCredits[recipient].add(amount); } } // override the default transfer function _transferFrom(address from, address to, uint256 tokenId) internal { // clear a buy now price buyPrices[tokenId] = 0; // transfer the token super._transferFrom(from, to, tokenId); } }pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/drafts/Counters.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Initializable, Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // 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; function initialize() public initializer { ERC165.initialize(); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_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(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(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 != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), 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(_msgSender(), 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 _msgSender() 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 { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `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 _msgSender() 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) internal { _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 safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `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. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `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. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @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 Transfer(address(0), to, 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 Transfer(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 is an internal detail of the `ERC721` contract and its use 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; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); 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); } } uint256[50] private ______gap; } pragma solidity >=0.4.21 <0.7.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; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Enumerable.sol"; import "./ERC721.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Initializable, Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ function initialize() public initializer { require(ERC721._hasBeenInitialized()); // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @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 { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } // /** // * @dev Internal function to burn a specific token. // * Reverts if the token does not exist. // * Deprecated, use {ERC721-_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 { // super._burn(owner, tokenId); // _removeTokenFromOwnerEnumeration(owner, tokenId); // // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund // _ownedTokensIndex[tokenId] = 0; // // _removeTokenFromAllTokensEnumeration(tokenId); // } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's 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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ // function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // // To prevent a gap in the 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 = _allTokens.length.sub(1); // uint256 tokenIndex = _allTokensIndex[tokenId]; // // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // // an 'if' statement (like in _removeTokenFromOwnerEnumeration) // uint256 lastTokenId = _allTokens[lastTokenIndex]; // _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token // _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // // This also deletes the contents at the last position of the array // _allTokens.length--; // _allTokensIndex[tokenId] = 0; // } uint256[50] private ______gap; }
AsyncArt v2 May 26, 2020 1. Preface The team of AsyncArt contracted us to conduct a software audit of their developed smart contracts written in Solidity. AsyncArt is a project asking “what does art look like when it can be programmed?” while exploring new ways of visualizing and implementing the idea of art. They are separating the art into “master” and “layer”. While the “master” is the piece of art itself, a “layer” represents a single part of the artwork. Masters as well as layers are tokenized on the Ethereum blockchain and can be bought and sold using Ether. The team of AsyncArt is planning to upgrade their current version of the deployed contracts with an upgrade. These new, updated contracts are what is being reviewed. 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 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/asyncart/async- contracts/tree/upgrade/contracts . The state of the code that has been reviewed was last changed on the 20th of May 2020 at 02:52 AM CEST (commit hash 1bbca6bfe1a171f1bb8369ff129d5aac234a6664 ). 2. Manual Code Review We conducted a manual code review, where we focussed on the two main smart contracts as instructed by the AsyncArt team: ” AsyncArtwork_v2.sol ” and “ TokenUpgrader.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 AsyncArt 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 critical bugs or flaws . We did however find seven flaws with none or low severity that we listed below. An additional double-check with two automated reviewing tools (one of them being the paid version of MythX ) also did not find any bugs. The automated tools merely noted that there are loops within the code that could lead to excess gas usage if the underlying data structures were growing unbounded. We assume that the developers are aware of this. 2.1. Bugs and Flaws (AsyncArtwork_v2.sol) A) Line 314-319 [LOW SEVERITY] A) Line 314-319 [LOW SEVERITY] for (uint256 i = 0; i < additionalCollaborators.length; i++) { // can't provide burn address as collaborator require(additionalCollaborators[i] != address(0)); uniqueTokenCreators[controlTokenId].push(additionalCollaborators[i]); } This section from “setupControlToken()” does not contain the same checks that are applied during the “mintArtwork()” function. The “uniqueTokenCreators” array will contain double entries of the same address if it is called in a specific way. As this can and probably will be prevented from the frontend, we only would suggest fixing this if that is not the case. B) Line 446 [NO SEVERITY] B) Line 446 [NO SEVERITY] // Allows the buyer to specify a minimum remaining uses they'll accept function takeBuyPrice(uint256 tokenId, int256 expectedRemainingUpdates) external payable { The comment states that the amount of minimum remaining uses can be specified by the user, however, the function only executed if the remaining amount is exactly as stated. require(controlTokenMapping[tokenId].numRemainingUpdates == expectedRemainingUpdates); We suggest to either change the comment if this behavior is desired - or the require if this is not desired. C) Line 599 [NO SEVERITY] C) Line 599 [NO SEVERITY] int256 previousValue = lever.currentValue; The variable “previousValue” is not necessary since it is never used again outside of this scope. Instead, it could be replaced with a modified version of line 605 like this: previousValues[i] = lever.currentValue; D) Line 155 [NO SEVERITY] D) Line 155 [NO SEVERITY] mapping(uint256 => ControlToken) controlTokenMapping; There is no visibility set, such that it will default to internal. We suggest to either declare it as private or public. E) Line 20-134 [NO SEVERITY] E) Line 20-134 [NO SEVERITY] All of the events don’t contain any indexed properties. It’s up to the team of AsyncArt whether this is okay or not, but it might lead to problems in the future if certain filtered web3 calls need to be made. F) Line 472-478 [LOW SEVERITY] F) Line 472-478 [LOW SEVERITY] The function “distributeFunds()” is dividing a provided amount of Ether into equal parts and transfers it to the provided addresses. In the case of a division with a remainder this remainder will remain inaccessible in the contract. This could, for example, happen if the result of the division in line 473 would result in 33,3, but since integers are used, the used value will be 33, leaving a remainder of 0,3. Since ETH is denominated in 10^18 Wei, the impact of this remainder will be negligible, since it will be in the area of (at current ETH price of about 200 USD) 10-16 USD. We’re just noting it for the sake of completeness. It could be mitigated by returning “creatorShare.mul(creators.length)” at the end of “distributeFunds()” and then use this to calculate the “real” remaining amount to be sent in “safeFundsTransfer()”. G) Line 644 [LOW SEVERITY] G) Line 644 [LOW SEVERITY] Currently it is not recommended to specify a fixed gas-amount in a “call.value” since it won’t allow smart contract wallets to receive ether. Instead, the currently recommended way to send ether is to use (bool success, ) = msg.sender.call.value(amount)() Using this method, it is very important to do this as late as possible within the execution of the contract to prevent reentrancy attacks. Since you allow users to manually claim their failed transfers with a special function, no user funds will be locked due to this, and users using smart contract wallets can use this function to receive their ether. As the current implementation might be annoying for certain users, it might be worth thinking about changing the current implementation to the proposed solution stated above (or also used in line 637). In that case it has to be of utmost importance to ensure not allowing any reentrancy attacks while doing so. Since we are sure that the decision to include the 2300-gas-call was done on purpose and has been well-thought- out, we won’t recommend any changes here. We just want to state the current recommended way to transfer ether for completeness. 2.2. Bugs and Flaws (TokenUpgrader.sol) We did not find any bugs or flaws in TokenUpgrader.sol and the corresponding “upgradeV1Token()” function inAsyncArtwork_v2.sol. 3. Protocol/Logic Review Part of the audit was also an analysis of the protocol and its’ logic, together with an analysis of whether this protocol works as intended or contains any logical bugs. Starting with the description of the functionality of the protocol in section 3.1 and 3.2, ending with a breakdown of our findings in section 3.3. 3.1. Functionality Descriptions Generally, the functionalities of the contracts can be divided into three sections: Platform-only functions Buy-Sell-related functions Token-related functions While the platform-only functions can only be called from the platforms’ address, the other functions may be called by anyone. We omit a detailed list of all functions and only list those that we consider relevant for the purpose of the protocol analysis. Platform-only functions WhiteListTokenForCreator Allows an address to mint one master token and X layer tokens (where X can be defined by the platform) WaiveFirstSaleRequirement Waive the right of the platform to receive their 10% fee for the first sale, instead, they’ll immediately switch to receiving just 1%. The artist receives 99% of the first sale. Update Fees (updatePlatformSalePercentage) Set new minimum bid percentage (updateMinimumBidIncreasePercent, updateArtistSecondSalePercentage) Change a token URI (updateTokenURI) We assume that this function only exists in order to help artists to fix/set a proper URI, without intending to abuse it in any way. If that is not it’s intended use-case, we might need to reevaluate. Lock a token URI (lockTokenURI) Transfer a v1 token to v2 (upgradeV1Token) Buy-Sell-related functions Bid Places a bid of a certain amount on a certain token WithdrawBid Removes a users’ bid from a token AcceptBid Accepts a users’ bid on a token (as the owner of the token) MakeBuyPrice Set a fixed buy price that anyone can immediately buy the token for (as the owner of the token) AcceptBuyPrice Buy a token for a fixed buy price Token-related functions MintArtwork Mints a master token as a whitelisted artist, also allocates the layers (can also directly be given to other addresses) MintControlTokenMints a layer token and sets its’ levers (options to control it), together with a list of artists that might have collaborated with the minting artist Also allows an artist to limit the number of uses UseControlToken Change the levers/values of a layer token as the owner or someone who was given permission by the owner GrantControlPermission Give someone else permission over the control of the users owned layer token 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. Buy mechanism There are two ways for a token to be sold: either through an auction-like mechanism where users bid a price that the owner can accept after it has reached the desired amount. The other option for the owner is to set a price that the token can instantly be bought at by anyone. Fee System At the time of this audit, the current fee system is implemented (but can be changed by the platform at any time): 3.3. Vulnerabilities and Flaws During our analysis of the protocol and its logic we did not find any bugs or flaws . Functions involving monetary aspects (like transferring Ether) have been separated from other art- or control-based functions which further reduces the risks of the involved funds. During our tests, we were not able to maliciously game the protocol. 4. Summary During our code review (which was done manual as well as automated) we found 7 bugs and/or flaws, with none of them being critical . All of the found flaws were of low or no severity. Since none of these bugs pose any risks to the use of the protocol or the funds of the users, we will leave it to the AsyncArt team to decide whether they want to address them or not. In our analysis of the protocol and the logic of the architecture, we did not find any bugs or flaws and we were not able to maliciously game the protocol through the tests that we did. Overall we see that the developers adhered to the best practices of Solidity and did a good job implementing their idea. 5. Update on the 04th of June 2020 Since we sent our report to the AsyncArt team, the findings have been discussed in a bi-lateral meeting. All of our found flaws have been addressed: A) Line 314-319 [LOW SEVERITY] A) Line 314-319 [LOW SEVERITY] The developers are aware of this and it is an intended feature. The naming of the variable might not be ideal, but given that the idea of the developers is, that the percentage of the paid amount can be changed through this mechanism to favor certain collaborators, we don't consider this a flaw anymore. B) Line 446 [NO SEVERITY] B) Line 446 [NO SEVERITY] The wording has been changed in GitHub commit b9ca792c07d85d8dba7cdc3940485b997f128b7c. Before // Allows the buyer to specify a minimum remaining uses they'll acceptAfter // Allows the buyer to specify an expected remaining uses they'll accept C) Line 599 [NO SEVERITY] C) Line 599 [NO SEVERITY] This flaw has been adresses in GitHub commit b9ca792c07d85d8dba7cdc3940485b997f128b7c . Before // grab previous value for the event emit int256 previousValue = lever.currentValue; // Update token current value lever.currentValue = newValues[i]; // collect the previous lever values for the event emit below previousValues[i] = previousValue; After // grab previous value for the event emit previousValues[i] = lever.currentValue; // Update token current value lever.currentValue = newValues[i]; We don’t think that this change has introduced any new risks or flaws. D) Line 155 [NO SEVERITY] This flaw has been adresses in GitHub commit 9bf3dd685c871d76fa47cbb32c51585d8e611035 . Before mapping(uint256 => ControlToken) controlTokenMapping; After mapping(uint256 => ControlToken) public controlTokenMapping; We don’t think that this change has introduced any new risks or flaws. E) Line 20-134 [NO SEVERITY] E) Line 20-134 [NO SEVERITY] The developers explained that they intend to use "The Graph" to query data from the blockchain, such that indexed events are not needed in this case. F) Line 472-478 [LOW SEVERITY] F) Line 472-478 [LOW SEVERITY] The developers acknowledge that our findings are true, but we both agree that changing this does not provide any benefits as the remainders value is negligble. G) Line 644 [LOW SEVERITY] G) Line 644 [LOW SEVERITY] The developers explained, that this is an intended behavior by the smart contract. They want to make the automated transfer functionality to be as safe as possible, without introducing any risks through a possible abuse of the gas system. They keep the current implementation, which is perfectly fine since they allow smart contract wallet users to withdraw their funds manually in case of any problems. No user funds are in danger, such that we don't consider our finding a flaw anymore. LEGAL Imprint Terms & Conditions Privacy Policy Contact © 2022 byterocket GmbH Download the Report Download the Report Stored on IPFS 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 Signed On-Chain The IPFS Hash, a unique identiOer 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: 7 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unused variables in the code (line 5, line 8, line 11, line 14, line 17, line 20, line 23). 2.b Fix: Remove the unused variables. Major/Moderate/Critical: None. Observations: The code of the 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 AsyncArt project is a decentralized and open-source project, these are important factors. Conclusion: The code review of the AsyncArt v2 contracts did not find any critical bugs or flaws. We did however find seven minor flaws which can be fixed by removing the unused variables. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem (Line 314-319): UniqueTokenCreators array will contain double entries of the same address if it is called in a specific way. 2.b Fix (Line 314-319): Prevent from the frontend or fix the require. 3.a Problem (Line 446): Comment states that the amount of minimum remaining uses can be specified by the user, however, the function only executed if the remaining amount is exactly as stated. 3.b Fix (Line 446): Change the comment if this behavior is desired - or the require if this is not desired. 4.a Problem (Line 599): Variable “previousValue” is not necessary since it is never used again outside of this scope. 4.b Fix (Line 599): Replace with a modified version of line 605. 5.a Problem (Line 155): No visibility set, such that it will default to internal. 5.b Fix (Line 155): Declare it as private or public. 6. Issues Count of Minor/Moderate/Major/Critical: None Observations: - Platform-only functions include WhiteListTokenForCreator, WaiveFirstSaleRequirement, Update Fees, and Change a token URI. - No bugs or flaws were found in TokenUpgrader.sol and the corresponding “upgradeV1Token()” function inAsyncArtwork_v2.sol. - It is not recommended to specify a fixed gas-amount in a “call.value” since it won’t allow smart contract wallets to receive ether. - It is important to do this as late as possible within the execution of the contract to prevent reentrancy attacks. Conclusion: No bugs or flaws were found in the report.
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.7.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title The PoolTogether Pod specification interface IPod is IERC20Upgradeable { /// @notice Returns the address of the prize pool that the pod is bound to /// @return The address of the prize pool function prizePool() external view returns (address); /// @notice Allows a user to deposit into the Pod /// @param to The address that shall receive the Pod shares /// @param tokenAmount The amount of tokens to deposit. These are the same tokens used to deposit into the underlying prize pool. /// @return The number of Pod shares minted. function depositTo(address to, uint256 tokenAmount) external returns (uint256); /// @notice Withdraws a users share of the prize pool. /// @dev The function should first withdraw from the 'float'; i.e. the funds that have not yet been deposited. /// if the withdraw is for more funds that can be covered by the float, then a withdrawal is made against the underlying /// prize pool. The user will be charged the prize pool's exit fee on the underlying funds. The fee can be calculated using PrizePool#calculateEarlyExitFee() /// @param shareAmount The number of Pod shares to redeem /// @return The actual amount of tokens that were transferred to the user. This is the same as the deposit token. function withdraw(uint256 shareAmount) external returns (uint256); /// @notice Calculates the token value per Pod share. /// @dev This is useful for those who wish to calculate their balance. /// @return The token value per Pod share. function getPricePerShare() external view returns (uint256); /// @notice Allows someone to batch deposit funds into the underlying prize pool. This should be called periodically. /// @dev This function should deposit the float into the prize pool, and claim any POOL tokens and distribute to users (possibly via adaptation of Token Faucet) function batch(uint256 batchAmount) external returns (bool); /// @notice Allows the owner of the Pod or the asset manager to withdraw tokens from the Pod. /// @dev This function should disallow the withdrawal of tickets or POOL to prevent users from being rugged. /// @param token The ERC20 token to withdraw. Must not be prize pool tickets or POOL tokens. function withdrawERC20(IERC20Upgradeable token, uint256 amount) external returns (bool); /// @notice Allows the owner of the Pod or the asset manager to withdraw tokens from the Pod. /// @dev This is mainly for Loot Boxes; so Loot Boxes that are won can be transferred out. /// @param token The address of the ERC721 to withdraw /// @param tokenId The token id to withdraw function withdrawERC721(IERC721 token, uint256 tokenId) external returns (bool); /// @notice Allows a user to claim POOL tokens for an address. The user will be transferred their share of POOL tokens. function claim(address user, address token) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; // Libraries import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; // Interfaces import "./IPod.sol"; import "./IPodManager.sol"; import "./interfaces/uniswap/IUniswapV2Router02.sol"; /** * @title PodManager Prototype (Ownable, IPodManager) - Liquidates a Pod non-core Assets * @notice Manages the liqudiation of a Pods "bonus" winnings i.e. tokens earned from LOOT boxes and other unexpected assets transfered to the Pod * @dev Liquidates non-core tokens (deposit token, PrizePool tickets and the POOL goverance) token for fair distribution Pod winners. * @author Kames Geraghty */ contract PodManager is Ownable, IPodManager { /***********************************| | Libraries | |__________________________________*/ using SafeMath for uint256; /***********************************| | Constants | |__________________________________*/ // Uniswap Router IUniswapV2Router02 public uniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); /***********************************| | Events | |__________________________________*/ /** * @dev Log Emitted when PodManager liquidates a Pod ERC20 token */ event LogLiquidatedERC20( address token, uint256 amountIn, uint256 amountOut ); /** * @dev Log Emitted when PodManager withdraws a Pod ERC20 token */ event LogLiquidatedERC721(address token, uint256 tokenId); /***********************************| | Public/External | |__________________________________*/ /** * @notice Liqudiates an ERC20 from a Pod by withdrawin the non-core token, executing a swap and returning the token. * @dev Liqudiates an ERC20 from a Pod by withdrawin the non-core token, executing a swap and returning the token. * @param _pod Pod reference * @param target ERC20 token reference. * @param amountIn Exact token amount transfered * @param amountOutMin Minimum token receieved * @param path Uniswap token path */ function liquidate( address _pod, IERC20Upgradeable target, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external override returns (bool) { IPod pod = IPod(_pod); // Withdraw target token from Pod pod.withdrawERC20(target, amountIn); // Approve Uniswap Router Swap target.approve(address(uniswapRouter), amountIn); // Swap Tokens and Send Winnings to PrizePool Pod uniswapRouter.swapExactTokensForTokens( amountIn, amountOutMin, path, address(pod), block.timestamp ); // Emit LogLiquidatedERC20 emit LogLiquidatedERC20(address(target), amountIn, amountOutMin); return true; } /** * @notice liquidate * @return uint256 Amount liquidated */ function withdrawCollectible( address _pod, IERC721 target, uint256 tokenId ) external override returns (bool) { IPod pod = IPod(_pod); // Withdraw target ERC721 from Pod pod.withdrawERC721(target, tokenId); // Transfer Collectible to Owner target.transferFrom(address(this), owner(), tokenId); // Emit LogLiquidatedERC721 emit LogLiquidatedERC721(address(target), tokenId); return true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; // Libraries import "./external/ProxyFactory.sol"; // Clone Contracts import "./Pod.sol"; import "./TokenDrop.sol"; /** * @title TokenDropFactory (ProxyFactory) - Clones a TokenDrop Instance * @notice Create a TokenDrop smart contract, which is associated with Pod smart contract for distribution of an asset token (i.e. POOL). * @dev The PodFactory creates/initializes TokenDrop smart contract. The factory will generally be called from the PodFactory smart contract directly. * @author Kames Geraghty */ contract TokenDropFactory is ProxyFactory { /***********************************| | Constants | |__________________________________*/ /** * @notice Contract template for deploying proxied Comptrollers */ TokenDrop public tokenDropInstance; /***********************************| | Constructor | |__________________________________*/ /** * @notice Initializes the TokenDropFactory. * @dev Initializes the Factory with a TokenDrop instance. */ constructor() { // TokenDrop Instance tokenDropInstance = new TokenDrop(); } /** * @notice Create a TokenDrop smart contract */ function create(address _measure, address _asset) external returns (TokenDrop) { // TokenDrop Deployed TokenDrop tokenDrop = TokenDrop(deployMinimal(address(tokenDropInstance), "")); // TokenDrop Initialize tokenDrop.initialize(_measure, _asset); // Return TokenDrop addresses return tokenDrop; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; // External Interfaces import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; // External Libraries import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; // Local Interfaces // import "./interfaces/TokenListenerInterface.sol"; // Local Libraries import "./libraries/ExtendedSafeCast.sol"; /** * @title TokenDrop - Calculates Asset Distribution using Measure Token * @notice Calculates distribution of POOL rewards for users deposting into PoolTogether PrizePools using the Pod smart contract. * @dev A simplified version of the PoolTogether TokenFaucet that simplifies an asset token distribution using totalSupply calculations. * @author Kames Cox-Geraghty */ contract TokenDrop is Initializable { /***********************************| | Libraries | |__________________________________*/ using SafeMath for uint256; using ExtendedSafeCast for uint256; /***********************************| | Constants | |__________________________________*/ /// @notice The token that is being disbursed IERC20Upgradeable public asset; /// @notice The token that is user to measure a user's portion of disbursed tokens IERC20Upgradeable public measure; /// @notice The cumulative exchange rate of measure token supply : dripped tokens uint112 public exchangeRateMantissa; /// @notice The total amount of tokens that have been dripped but not claimed uint112 public totalUnclaimed; /// @notice The timestamp at which the tokens were last dripped uint32 public lastDripTimestamp; // Factory address public factory; /***********************************| | Events | |__________________________________*/ event Dripped(uint256 newTokens); event Deposited(address indexed user, uint256 amount); event Claimed(address indexed user, uint256 newTokens); /***********************************| | Structs | |__________________________________*/ struct UserState { uint128 lastExchangeRateMantissa; uint256 balance; } /** * @notice The data structure that tracks when a user last received tokens */ mapping(address => UserState) public userStates; /***********************************| | Initialize | |__________________________________*/ /** * @notice Initialize TokenDrop Smart Contract */ // SWC-Unprotected Ether Withdrawal: L82-88 function initialize(address _measure, address _asset) external { measure = IERC20Upgradeable(_measure); asset = IERC20Upgradeable(_asset); // Set Factory Deployer factory = msg.sender; } /***********************************| | Public/External | |__________________________________*/ /** * @notice Should be called before "measure" tokens are transferred or burned * @param from The user who is sending the tokens * @param to The user who is receiving the tokens *@param token The token token they are burning */ function beforeTokenTransfer( address from, address to, address token ) external { // must be measure and not be minting if (token == address(measure)) { drop(); // Calcuate to tokens balance _captureNewTokensForUser(to); // If NOT minting calcuate from tokens balance if (from != address(0)) { _captureNewTokensForUser(from); } } } /** * @notice Add Asset to TokenDrop and update with drop() * @dev Add Asset to TokenDrop and update with drop() * @param amount User account */ function addAssetToken(uint256 amount) external returns (bool) { // Transfer asset/reward token from msg.sender to TokenDrop asset.transferFrom(msg.sender, address(this), amount); // Update TokenDrop asset balance drop(); // Return BOOL for transaction gas savings return true; } /** * @notice Claim asset rewards * @dev Claim asset rewards * @param user User account */ // SWC-Reentrancy: L141-155 function claim(address user) external returns (uint256) { drop(); _captureNewTokensForUser(user); uint256 balance = userStates[user].balance; userStates[user].balance = 0; totalUnclaimed = uint256(totalUnclaimed).sub(balance).toUint112(); // Transfer asset/reward token to user asset.transfer(user, balance); // Emit Claimed emit Claimed(user, balance); return balance; } /** * @notice Drips new tokens. * @dev Should be called immediately before any measure token mints/transfers/burns * @return The number of new tokens dripped. */ // change to drop function drop() public returns (uint256) { uint256 assetTotalSupply = asset.balanceOf(address(this)); uint256 newTokens = assetTotalSupply.sub(totalUnclaimed); // if(newTokens > 0) if (newTokens > 0) { // Check measure token totalSupply() uint256 measureTotalSupply = measure.totalSupply(); // Check measure supply exists if (measureTotalSupply > 0) { uint256 indexDeltaMantissa = FixedPoint.calculateMantissa(newTokens, measureTotalSupply); uint256 nextExchangeRateMantissa = uint256(exchangeRateMantissa).add(indexDeltaMantissa); exchangeRateMantissa = nextExchangeRateMantissa.toUint112(); totalUnclaimed = uint256(totalUnclaimed) .add(newTokens) .toUint112(); } // Emit Dripped emit Dripped(newTokens); } return newTokens; } /***********************************| | Private/Internal | |__________________________________*/ /** * @notice Captures new tokens for a user * @dev This must be called before changes to the user's balance (i.e. before mint, transfer or burns) * @param user The user to capture tokens for * @return The number of new tokens */ function _captureNewTokensForUser(address user) private returns (uint128) { UserState storage userState = userStates[user]; if (exchangeRateMantissa == userState.lastExchangeRateMantissa) { // ignore if exchange rate is same return 0; } uint256 deltaExchangeRateMantissa = uint256(exchangeRateMantissa).sub( userState.lastExchangeRateMantissa ); uint256 userMeasureBalance = measure.balanceOf(user); uint128 newTokens = FixedPoint .multiplyUintByMantissa( userMeasureBalance, deltaExchangeRateMantissa ) .toUint128(); userStates[user] = UserState({ lastExchangeRateMantissa: exchangeRateMantissa, balance: uint256(userState.balance).add(newTokens).toUint128() }); return newTokens; } function supportsInterface(bytes4 interfaceId) external view returns (bool) { return true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; // Libraries import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; // External Interfaces import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; // Ineritance // import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; // Internal Interfaces import "./IPod.sol"; import "./TokenDrop.sol"; import "./IPodManager.sol"; // External Interfaces import "./interfaces/TokenFaucet.sol"; import "./interfaces/IPrizePool.sol"; import "./interfaces/IPrizeStrategyMinimal.sol"; /** * @title Pod (Initialize, ERC20Upgradeable, OwnableUpgradeable, IPod) - Reduce User Gas Costs and Increase Odds of Winning via Collective Deposits. * @notice Pods turn PoolTogether deposits into shares and enable batched deposits, reudcing gas costs and collectively increasing odds winning. * @dev Pods is a ERC20 token with features like shares, batched deposits and distributing mechanisms for distiubuting "bonus" tokens to users. * @author Kames Geraghty */ contract Pod is Initializable, ERC20Upgradeable, OwnableUpgradeable, IPod { /***********************************| | Libraries | |__________________________________*/ using SafeMath for uint256; /***********************************| | Constants | |__________________________________*/ IERC20Upgradeable public token; IERC20Upgradeable public ticket; IERC20Upgradeable public pool; // Initialized Contracts TokenFaucet public faucet; TokenDrop public drop; // Private IPrizePool private _prizePool; // Manager IPodManager public manager; // Factory address public factory; /** * @dev Pods can include token drops for multiple assets and not just the standard POOL. * Generally a Pod will only inlude a TokenDrop for POOL, but it's possible that a Pod * may add additional TokenDrops in the future. The Pod includes a `claimPodPool` method * to claim POOL, but other TokenDrops would require an external method for adding an * "asset" token to the TokenDrop smart contract, before calling the `claim` method. */ mapping(address => TokenDrop) public drops; /***********************************| | Events | |__________________________________*/ /** * @dev Emitted when user deposits into batch backlog */ event Deposited(address user, uint256 amount, uint256 shares); /** * @dev Emitted when user withdraws */ event Withdrawl(address user, uint256 amount, uint256 shares); /** * @dev Emitted when batch deposit is executed */ event Batch(uint256 amount, uint256 timestamp); /** * @dev Emitted when account sponsers pod. */ event Sponsored(address sponsor, uint256 amount); /** * @dev Emitted when POOl is claimed for a user. */ event Claimed(address user, uint256 balance); /** * @dev Emitted when POOl is claimed for the POD */ event PodClaimed(uint256 amount); /** * @dev Emitted when a ERC20 is withdrawn */ event ERC20Withdrawn(address target, uint256 tokenId); /** * @dev Emitted when a ERC721 is withdrawn */ event ERC721Withdrawn(address target, uint256 tokenId); /** * @dev Emitted when account triggers drop calculation. */ event DripCalculate(address account, uint256 amount); /** * @dev Emitted when liquidty manager is transfered. */ event ManagementTransferred( address indexed previousmanager, address indexed newmanager ); /***********************************| | Modifiers | |__________________________________*/ /** * @dev Checks is the caller is an active PodManager */ modifier onlyManager() { require( address(manager) == _msgSender(), "Manager: caller is not the manager" ); _; } /** * @dev Pause deposits during aware period. Prevents "frontrunning" for deposits into a winning Pod. */ modifier pauseDepositsDuringAwarding() { require( !IPrizeStrategyMinimal(_prizePool.prizeStrategy()).isRngRequested(), "Cannot deposit while prize is being awarded" ); _; } /***********************************| | Constructor | |__________________________________*/ /** * @notice Initialize the Pod Smart Contact with the target PrizePool configuration. * @dev The Pod Smart Contact is created and initialized using the PodFactory. * @param _prizePoolTarget Target PrizePool for deposits and withdraws * @param _ticket Non-sponsored PrizePool ticket - is verified during initialization. * @param _pool PoolTogether Goverance token - distributed for users with active deposits. * @param _faucet TokenFaucet reference that distributes POOL token for deposits * @param _manager Liquidates the Pod's "bonus" tokens for the Pod's token. */ function initialize( address _prizePoolTarget, address _ticket, address _pool, address _faucet, address _manager ) external initializer { // Prize Pool _prizePool = IPrizePool(_prizePoolTarget); // Initialize ERC20Token __ERC20_init_unchained( string( abi.encodePacked( "Pod ", ERC20Upgradeable(_prizePool.token()).name() ) ), string( abi.encodePacked( "p", ERC20Upgradeable(_prizePool.token()).symbol() ) ) ); // Initialize Owner __Ownable_init_unchained(); // Request PrizePool Tickets address[] memory tickets = _prizePool.tokens(); // Check if ticket matches existing PrizePool Ticket require( address(_ticket) == address(tickets[0]) || address(_ticket) == address(tickets[1]), "Pod:initialize-invalid-ticket" ); // Initialize Core ERC20 Tokens token = IERC20Upgradeable(_prizePool.token()); ticket = IERC20Upgradeable(tickets[1]); pool = IERC20Upgradeable(_pool); faucet = TokenFaucet(_faucet); // Pod Liquidation Manager manager = IPodManager(_manager); // Factory factory = msg.sender; } /***********************************| | Public/External | |__________________________________*/ /** * @notice The Pod manager address. * @dev Returns the address of the current Pod manager. * @return address manager */ function podManager() external view returns (address) { return address(manager); } /** * @notice Update the Pod Mangeer * @dev Update the Pod Manger responsible for handling liquidations. * @return bool true */ function setManager(IPodManager newManager) public virtual onlyOwner returns (bool) { // Require Valid Address require(address(manager) != address(0), "Pod:invalid-manager-address"); // Emit ManagementTransferred emit ManagementTransferred(address(manager), address(newManager)); // Update Manager manager = newManager; return true; } /** * @notice The Pod PrizePool reference * @dev Returns the address of the Pod prizepool * @return address The Pod prizepool */ function prizePool() external view override returns (address) { return address(_prizePool); } /** * @notice Deposit assets into the Pod in exchange for share tokens * @param to The address that shall receive the Pod shares * @param tokenAmount The amount of tokens to deposit. These are the same tokens used to deposit into the underlying prize pool. * @return The number of Pod shares minted. */ function depositTo(address to, uint256 tokenAmount) external override returns (uint256) { require(tokenAmount > 0, "Pod:invalid-amount"); // Allocate Shares from Deposit To Amount // SWC-Reentrancy: L275-282 uint256 shares = _deposit(to, tokenAmount); // Transfer Token Transfer Message Sender // SWC-Unchecked Call Return Value: L279 IERC20Upgradeable(token).transferFrom( msg.sender, address(this), tokenAmount ); // Emit Deposited emit Deposited(to, tokenAmount, shares); // Return Shares Minted return shares; } /** * @notice Withdraws a users share of the prize pool. * @dev The function should first withdraw from the 'float'; i.e. the funds that have not yet been deposited. * @param shareAmount The number of Pod shares to redeem. * @return The actual amount of tokens that were transferred to the user. This is the same as the deposit token. */ function withdraw(uint256 shareAmount) external override returns (uint256) { // Check User Balance require( balanceOf(msg.sender) >= shareAmount, "Pod:insufficient-shares" ); // Burn Shares and Return Tokens uint256 tokens = _burnShares(shareAmount); // Emit Withdrawl emit Withdrawl(msg.sender, tokens, shareAmount); return tokens; } /** * @notice Deposit Pod float into PrizePool. * @dev Deposits the current float amount into the PrizePool and claims current POOL rewards. * @param batchAmount Amount to deposit in PoolTogether PrizePool. */ function batch(uint256 batchAmount) external override returns (bool) { uint256 tokenBalance = vaultTokenBalance(); // Pod has a float above 0 require(tokenBalance > 0, "Pod:zero-float-balance"); // Batch Amount is EQUAL or LESS than vault token float balance.. // batchAmount can be below tokenBalance to keep a withdrawble float amount. require(batchAmount <= tokenBalance, "Pod:insufficient-float-balance"); // Claim POOL drop backlog. uint256 poolAmount = claimPodPool(); // Emit PodClaimed emit PodClaimed(poolAmount); // Approve Prize Pool token.approve(address(_prizePool), tokenBalance); // PrizePool Deposit _prizePool.depositTo( address(this), batchAmount, address(ticket), address(this) ); // Emit Batch emit Batch(tokenBalance, block.timestamp); return true; } /** * @notice Withdraw non-core (token/ticket/pool) ERC20 to Pod manager. * @dev Withdraws an ERC20 token amount from the Pod to the PodManager for liquidation to the token and back to the Pod. * @param _target ERC20 token to withdraw. * @param amount Amount of ERC20 to transfer/withdraw. * @return bool true */ function withdrawERC20(IERC20Upgradeable _target, uint256 amount) external override onlyManager returns (bool) { // Lock token/ticket/pool ERC20 transfers require( address(_target) != address(token) && address(_target) != address(ticket) && address(_target) != address(pool), "Pod:invalid-target-token" ); // Transfer Token _target.transfer(msg.sender, amount); emit ERC20Withdrawn(address(_target), amount); return true; } /** * @dev Withdraw ER721 reward tokens */ /** * @notice Withdraw ER721 token to the Pod owner. * @dev Withdraw ER721 token to the Pod owner, which is responsible for deciding what/how to manage the collectible. * @param _target ERC721 token to withdraw. * @param tokenId The tokenId of the ERC721 collectible. * @return bool true */ function withdrawERC721(IERC721 _target, uint256 tokenId) external override onlyManager returns (bool) { // Transfer ERC721 _target.transferFrom(address(this), msg.sender, tokenId); // Emit ERC721Withdrawn emit ERC721Withdrawn(address(_target), tokenId); return true; } /** * @notice Allows a user to claim POOL tokens for an address. The user will be transferred their share of POOL tokens. * @dev Allows a user to claim POOL tokens for an address. The user will be transferred their share of POOL tokens. * @param user User account * @param _token The target token * @return uint256 Amount claimed. */ function claim(address user, address _token) external override returns (uint256) { // Get token<>tokenDrop mapping require( drops[_token] != TokenDrop(address(0)), "Pod:invalid-token-drop" ); // Claim POOL rewards uint256 _balance = drops[_token].claim(user); emit Claimed(user, _balance); return _balance; } /** * @notice Claims POOL for PrizePool Pod deposits * @dev Claim POOL for PrizePool Pod and adds/transfers those token to the Pod TokenDrop smart contract. * @return uint256 claimed amount */ function claimPodPool() public returns (uint256) { uint256 _claimedAmount = faucet.claim(address(this)); // Approve POOL transfer. pool.approve(address(drop), _claimedAmount); // Add POOl to TokenDrop balance drop.addAssetToken(_claimedAmount); // Claimed Amount return _claimedAmount; } /** * @notice Setup TokenDrop reference * @dev Initialize the Pod Smart Contact * @param _token IERC20Upgradeable * @param _tokenDrop TokenDrop address * @return bool true */ function setTokenDrop(address _token, address _tokenDrop) external returns (bool) { require( msg.sender == factory || msg.sender == owner(), "Pod:unauthorized-set-token-drop" ); // Check if target<>tokenDrop mapping exists require( drops[_token] == TokenDrop(0), "Pod:target-tokendrop-mapping-exists" ); // Set TokenDrop Referance drop = TokenDrop(_tokenDrop); // Set target<>tokenDrop mapping drops[_token] = drop; return true; } /***********************************| | Internal | |__________________________________*/ /** * @dev The internal function for the public depositTo function, which calculates a user's allocated shares from deposited amoint. * @param user User's address. * @param amount Amount of "token" deposited into the Pod. * @return uint256 The share allocation amount. */ function _deposit(address user, uint256 amount) internal returns (uint256) { uint256 allocation = 0; // Calculate Allocation if (totalSupply() == 0) { allocation = amount; } else { allocation = (amount.mul(totalSupply())).div(balance()); } // Mint User Shares _mint(user, allocation); // Return Allocation Amount return allocation; } /** * @dev The internal function for the public withdraw function, which calculates a user's token allocation from burned shares. * @param shares Amount of "token" deposited into the Pod. * @return uint256 The token amount returned for the burned shares. */ function _burnShares(uint256 shares) internal returns (uint256) { // Calculate Percentage Returned from Burned Shares uint256 amount = (balance().mul(shares)).div(totalSupply()); // Burn Shares _burn(msg.sender, shares); // Check balance IERC20Upgradeable _token = IERC20Upgradeable(token); uint256 currentBalance = _token.balanceOf(address(this)); // Withdrawl Exceeds Current Token Balance if (amount > currentBalance) { // Calculate Withdrawl Amount uint256 _withdraw = amount.sub(currentBalance); // Withdraw from Prize Pool uint256 exitFee = _withdrawFromPool(_withdraw); // Add Exit Fee to Withdrawl Amount amount = amount.sub(exitFee); } // Transfer Deposit Token to Message Sender _token.transfer(msg.sender, amount); // Return Token Withdrawl Amount return amount; } /** * @dev Withdraws from Pod prizePool if the float balance can cover the total withdraw amount. * @param _amount Amount of tokens to withdraw in exchange for the tickets transfered. * @return uint256 The exit fee paid for withdraw from the prizePool instant withdraw method. */ function _withdrawFromPool(uint256 _amount) internal returns (uint256) { IPrizePool _pool = IPrizePool(_prizePool); // Calculate Early Exit Fee (uint256 exitFee, ) = _pool.calculateEarlyExitFee( address(this), address(ticket), _amount ); // Withdraw from Prize Pool uint256 exitFeePaid = _pool.withdrawInstantlyFrom( address(this), _amount, address(ticket), exitFee ); // Exact Exit Fee return exitFeePaid; } /***********************************| | Views | |__________________________________*/ /** * @notice Calculate the cost of the Pod's token price per share. Until a Pod has won or been "airdropped" tokens it's 1. * @dev Based of the Pod's total token/ticket balance and totalSupply it calculates the pricePerShare. */ function getPricePerShare() external view override returns (uint256) { // Check totalSupply to prevent SafeMath: division by zero if (totalSupply() > 0) { return balance().mul(1e18).div(totalSupply()); } else { return 0; } } /** * @notice Calculate the cost of the user's price per share based on a Pod's token/ticket balance. * @dev Calculates the cost of the user's price per share based on a Pod's token/ticket balance. */ function getUserPricePerShare(address user) external view returns (uint256) { // Check totalSupply to prevent SafeMath: division by zero if (totalSupply() > 0) { return balanceOf(user).mul(1e18).div(balance()); } else { return 0; } } /** * @notice Pod current token balance. * @dev Request's the Pod's current token balance by calling balanceOf(address(this)). * @return uint256 Pod's current token balance. */ function vaultTokenBalance() public view returns (uint256) { return token.balanceOf(address(this)); } /** * @notice Pod current ticket balance. * @dev Request's the Pod's current ticket balance by calling balanceOf(address(this)). * @return uint256 Pod's current ticket balance. */ function vaultTicketBalance() public view returns (uint256) { return ticket.balanceOf(address(this)); } /** * @notice Pod current POOL balance. * @dev Request's the Pod's current POOL balance by calling balanceOf(address(this)). * @return uint256 Pod's current POOL balance. */ function vaultPoolBalance() public view returns (uint256) { return pool.balanceOf(address(this)); } /** * @notice Measure's the Pod's total balance by adding the vaultTokenBalance and vaultTicketBalance * @dev The Pod's token and ticket balance are equal in terms of "value" and thus are used to calculate's a Pod's true balance. * @return uint256 Pod's token and ticket balance. */ function balance() public view returns (uint256) { return vaultTokenBalance().add(vaultTicketBalance()); } /***********************************| | ERC20 Overrides | |__________________________________*/ /** * @notice Add TokenDrop to mint() * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * @param from Account sending tokens * @param to Account recieving tokens * @param amount Amount of tokens sent */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { // Call _beforeTokenTransfer from contract inheritance super._beforeTokenTransfer(from, to, amount); // Update TokenDrop internals drop.beforeTokenTransfer(from, to, address(this)); // Emit DripCalculate emit DripCalculate(from, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; // Libraries import "./external/ProxyFactory.sol"; // Internal Interfaces import "./TokenDropFactory.sol"; // Clone Contracts import "./Pod.sol"; import "./TokenDrop.sol"; /** * @title PodFactory (ProxyFactory) - Clones a Pod Instance * @notice Reduces gas costs and collectively increases that chances winning for PoolTogether users, while keeping user POOL distributions to users. * @dev The PodFactory creates/initializes connected Pod and TokenDrop smart contracts. Pods stores tokens, tickets, prizePool and other essential references. * @author Kames Geraghty */ contract PodFactory is ProxyFactory { /** * @notice TokenDropFactory reference */ TokenDropFactory public tokenDropFactory; /** * @notice Contract template for deploying proxied Pods */ Pod public podInstance; /** * @notice Contract template for deploying proxied TokenDrop */ TokenDrop public tokenDropInstance; /***********************************| | Events | |__________________________________*/ /** * @dev Emitted when use deposits into batch backlog */ event LogCreatedPodAndTokenDrop(address pod, address tokenDrop); /***********************************| | Constructor | |__________________________________*/ /** * @notice Initializes the Pod Factory with an instance of the Pod and TokenDropFactory reference. * @dev Initializes the Pod Factory with an instance of the Pod and TokenDropFactory reference. * @param _tokenDropFactory Target PrizePool for deposits and withdraws */ constructor(TokenDropFactory _tokenDropFactory) { // Pod Instance podInstance = new Pod(); // Reference TokenDropFactory tokenDropFactory = _tokenDropFactory; } /** * @notice Create a new Pod Clone using the Pod instance. * @dev The Pod Smart Contact is created and initialized using the PodFactory. * @param _prizePoolTarget Target PrizePool for deposits and withdraws * @param _ticket Non-sponsored PrizePool ticket - is verified during initialization. * @param _pool PoolTogether Goverance token - distributed for users with active deposits. * @param _faucet TokenFaucet reference that distributes POOL token for deposits * @param _manager Liquidates the Pod's "bonus" tokens for the Pod's token. * @return (address, address) Pod and TokenDrop addresses */ function create( address _prizePoolTarget, address _ticket, address _pool, address _faucet, address _manager ) external returns (address, address) { // Pod Deploy Pod pod = Pod(deployMinimal(address(podInstance), "")); // Pod Initialize pod.initialize(_prizePoolTarget, _ticket, _pool, _faucet, _manager); // Update Owner pod.transferOwnership(msg.sender); TokenDrop tokenDrop = tokenDropFactory.create(address(pod), _pool); // TokenDrop Pod Initialize - Add Pod.token() to TokenDrop pod.setTokenDrop(address(pod.token()), address(tokenDrop)); // Emit LogCreatedPodAndTokenDrop emit LogCreatedPodAndTokenDrop(address(pod), address(tokenDrop)); // Return Pod/TokenDrop addresses return (address(pod), address(tokenDrop)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; // Interface import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface IPodManager { /** * @notice liquidate * @return uint256 Amount liquidated */ function liquidate( address _pod, IERC20Upgradeable target, uint256 amountIn, uint256 amountOutMin, address[] calldata path ) external returns (bool); /** * @notice withdrawCollectible * @return uint256 Amount liquidated */ function withdrawCollectible( address _pod, IERC721 target, uint256 tokenId ) external returns (bool); }
PoolTogether - Pods PoolTogether - Pods Date Date March 2021 1 Executive Summary 1 Executive Summary This report presents the results of our engagement with PoolTogether to review the Pods V3 contracts. The review was conducted by Sergii Kravchenko and Nicholas Ward over the course of ten person-days between March 29 and April 2 , 2021. 2 Scope 2 Scope Our review focused on commit hash 879dc8b911fc506dd6bead1f36eade919ccfea57 and was limited to the Pod and TokenDrop contracts along with their respective factory contracts. The list of files in scope can be found in the Appendix . 3 Findings 3 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. 3.1 Winning pods can be frontrun with large deposits 3.1 Winning pods can be frontrun with large deposits Critical Description Pod.depositTo() grants users shares of the pod pool in exchange for tokenAmount of token . code/pods-v3-contracts/contracts/Pod.sol:L266-L288 code/pods-v3-contracts/contracts/Pod.sol:L266-L288 th ndfunction depositTo ( address to , uint256 tokenAmount ) external override returns ( uint256 ) { require ( tokenAmount > 0 , "Pod:invalid-amount" ); // Allocate Shares from Deposit To Amount // Allocate Shares from Deposit To Amount uint256 shares = _deposit ( to , tokenAmount ); // Transfer Token Transfer Message Sender // Transfer Token Transfer Message Sender IERC20Upgradeable ( token ). transferFrom ( msg . sender , address ( this ), tokenAmount ); // Emit Deposited // Emit Deposited emit Deposited ( to , tokenAmount , shares ); // Return Shares Minted // Return Shares Minted return shares ; } The winner of a prize pool is typically determined by an off-chain random number generator, which requires a request to first be made on-chain. The result of this RNG request can be seen in the mempool and frontrun. In this case, an attacker could identify a winning Pod contract and make a large deposit, diluting existing user shares and claiming the entire prize. Recommendation The modifier pauseDepositsDuringAwarding is included in the Pod contract but is unused. code/pods-v3-contracts/contracts/Pod.sol:L142-L148 code/pods-v3-contracts/contracts/Pod.sol:L142-L148 modifier pauseDepositsDuringAwarding () { require ( ! IPrizeStrategyMinimal ( _prizePool . prizeStrategy ()). isRngRequested (), "Cannot deposit while prize is being awarded" ); _ ; } Add this modifier to the depositTo() function along with corresponding test cases. 3.2 Token transfers may return 3.2 Token transfers may return false Critical Description There are a lot of token transfers in the code, and most of them are just calling transfer or transferFrom without checking the return value. Ideally, due to the ERC-20 token standard, these functions should always return True or False (or revert). If a token returns False , the code will process the transfer as if it succeeds.Recommendation Use the safeTransfer and the safeTransferFrom versions of transfers from OZ. 3.3 3.3 TokenDrop : Unprotected : Unprotected initialize() function function Critical Description The TokenDrop.initialize() function is unprotected and can be called multiple times. code/pods-v3-contracts/contracts/TokenDrop.sol:L81-L87 code/pods-v3-contracts/contracts/TokenDrop.sol:L81-L87 function initialize ( address _measure , address _asset ) external { measure = IERC20Upgradeable ( _measure ); asset = IERC20Upgradeable ( _asset ); // Set Factory Deployer // Set Factory Deployer factory = msg . sender ; } Among other attacks, this would allow an attacker to re-initialize any TokenDrop with the same asset and a malicious measure token. By manipulating the balance of a user in this malicious measure token, the entire asset token balance of the TokenDrop contract could be drained. Recommendation Add the initializer modifier to the initialize() function and include an explicit test that every initialization function in the system can be called once and only once. 3.4 Pod: Re-entrancy during deposit or withdrawal can lead to 3.4 Pod: Re-entrancy during deposit or withdrawal can lead to stealing funds stealing funds Critical Description During the deposit, the token transfer is made after the Pod shares are minted: code/pods-v3-contracts/contracts/Pod.sol:L274-L281 code/pods-v3-contracts/contracts/Pod.sol:L274-L281 uint256 shares = _deposit ( to , tokenAmount ); // Transfer Token Transfer Message Sender // Transfer Token Transfer Message Sender IERC20Upgradeable ( token ). transferFrom ( msg . sender , address ( this ), tokenAmount ); That means that if the token allows re-entrancy, the attacker can deposit one more time inside the token transfer. If that happens, the second call will mint more tokens than it is supposed to, because the first token transfer will still not be finished. By doing so with big amounts, it’s possible to drain the pod.Recommendation Add re-entrancy guard to the external functions. 3.5 TokenDrop: Re-entrancy in the 3.5 TokenDrop: Re-entrancy in the claim function can cause to function can cause to draining funds draining funds Major Description If the asset token is making a call before the transfer to the receiver or to any other 3-d party contract (like it’s happening in the Pod token using the _beforeTokenTransfer function), the attacker can call the drop function inside the transfer call here: code/pods-v3-contracts/contracts/TokenDrop.sol:L139-L153 code/pods-v3-contracts/contracts/TokenDrop.sol:L139-L153 function claim ( address user ) external returns ( uint256 ) { drop (); _captureNewTokensForUser ( user ); uint256 balance = userStates [ user ]. balance ; userStates [ user ]. balance = 0 ; totalUnclaimed = uint256 ( totalUnclaimed ). sub ( balance ). toUint112 (); // Transfer asset/reward token to user // Transfer asset/reward token to user asset . transfer ( user , balance ); // Emit Claimed // Emit Claimed emit Claimed ( user , balance ); return balance ; } Because the totalUnclaimed is already changed, but the current balance is not, the drop function will consider the funds from the unfinished transfer as the new tokens. These tokens will be virtually redistributed to everyone. After that, the transfer will still happen, and further calls of the drop() function will fail because the following line will revert: uint256 newTokens = assetTotalSupply.sub(totalUnclaimed); That also means that any transfers of the Pod token will fail because they all are calling the drop function. The TokenDrop will “unfreeze” only if someone transfers enough tokens to the TokenDrop contract. The severity of this issue is hard to evaluate because, at the moment, there’s not a lot of tokens that allow this kind of re-entrancy. Recommendation Simply adding re-entrancy guard to the drop and the claim function won’t help because the drop function is called from the claim . For that, the transfer can be moved to a separate function, and this function can have the re-entrancy guard as well as the drop function. Also, it’s better to make sure that _beforeTokenTransfer will not revert to prevent the tokenfrom being frozen. 3.6 Pod: Having multiple token drops is inconsistent 3.6 Pod: Having multiple token drops is inconsistent Medium Description The Pod contract had the drop storage field and mapping of different TokenDrop s (token => TokenDrop) . When adding a new TokenDrop in the mapping, the drop field is also changed to the added _tokenDrop : code/pods-v3-contracts/contracts/Pod.sol:L455-L477 code/pods-v3-contracts/contracts/Pod.sol:L455-L477 function setTokenDrop ( address _token , address _tokenDrop ) external returns ( bool ) { require ( msg . sender == factory || msg . sender == owner (), "Pod:unauthorized-set-token-drop" ); // Check if target<>tokenDrop mapping exists // Check if target<>tokenDrop mapping exists require ( drops [ _token ] == TokenDrop ( 0 ), "Pod:target-tokendrop-mapping-exists" ); // Set TokenDrop Referance // Set TokenDrop Referance drop = TokenDrop ( _tokenDrop ); // Set target<>tokenDrop mapping // Set target<>tokenDrop mapping drops [ _token ] = drop ; return true ; } On the other hand, the measure token and the asset token of the drop are strictly defined by the Pod contract. They cannot be changed, so all TokenDrop s are supposed to have the same asset and measure tokens. So it is useless to have different TokenDrops . Recommendation The mapping seems to be unused, and only one TokenDrop will normally be in the system. If that code is not used, it should be deleted. 3.7 Pod: Fees are not limited by a user during the withdrawal 3.7 Pod: Fees are not limited by a user during the withdrawal Medium Description When withdrawing from the Pod, the shares are burned, and the deposit is removed from the Pod. If there are not enough deposit tokens in the contract, the remaining tokens are withdrawn from the pool contract: code/pods-v3-contracts/contracts/Pod.sol:L523-L532 code/pods-v3-contracts/contracts/Pod.sol:L523-L532if ( amount > currentBalance ) { // Calculate Withdrawl Amount // Calculate Withdrawl Amount uint256 _withdraw = amount . sub ( currentBalance ); // Withdraw from Prize Pool // Withdraw from Prize Pool uint256 exitFee = _withdrawFromPool ( _withdraw ); // Add Exit Fee to Withdrawl Amount // Add Exit Fee to Withdrawl Amount amount = amount . sub ( exitFee ); } These tokens are withdrawn with a fee from the pool, which is not controlled or limited by the user. Recommendation Allow users to pass a maxFee parameter to control fees. 3.8 3.8 ProxyFactory.deployMinimal() does not check for contract does not check for contract creation failure creation failure Minor Description The function ProxyFactory.deployMinimal() is used by both the PodFactory and the TokenDropFactory to deploy minimal proxy contracts. This function uses inline assembly to inline a target address into the minimal proxy and deploys the resulting bytecode. It then emits an event containing the resulting address and optionally makes a low-level call to the resulting address with user-provided data. The result of a create() operation in assembly will be the zero address in the event that a revert or an exceptional halting state is encountered during contract creation. If execution of the contract initialization code succeeds but returns no runtime bytecode, it is also possible for the create() operation to return a nonzero address that contains no code. code/pods-v3-contracts/contracts/external/ProxyFactory.sol:L9-L35 code/pods-v3-contracts/contracts/external/ProxyFactory.sol:L9-L35function deployMinimal ( address _logic , bytes memory _data ) public returns ( address proxy ) { // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol bytes20 targetBytes = bytes20 ( _logic ); assembly { let clone := mload ( 0x40 ) mstore ( clone , 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore ( add ( clone , 0x14 ), targetBytes ) mstore ( add ( clone , 0x28 ), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) proxy := create ( 0 , clone , 0x37 ) } emit ProxyCreated ( address ( proxy )) ; if ( _data . length > 0 ) { ( bool success , ) = proxy . call ( _data ) ; require ( success , "ProxyFactory/constructor-call-failed" ) ; } } Recommendation At a minimum, add a check that the resulting proxy address is nonzero before emitting the ProxyCreated event and performing the low-level call. Consider also checking the extcodesize of the proxy address is greater than zero. Also note that the bytecode in the deployed “Clone” contract was not reviewed due to time constraints. 3.9 3.9 Pod.setManager() checks validity of wrong address checks validity of wrong address Minor Description The function Pod.setManager() allows the owner of the Pod contract to change the Pod’s manager . It checks that the value of the existing manager in storage is nonzero. This is presumably intended to ensure that the owner has provided a valid newManager parameter in calldata. The current check will always pass once the contract is initialized with a nonzero manager . But, the contract can currently be initialized with a manager of IPodManager(address(0)) . In this case, the check would prevent the manager from ever being updated. code/pods-v3-contracts/contracts/Pod.sol:L233-L240 code/pods-v3-contracts/contracts/Pod.sol:L233-L240function setManager ( IPodManager newManager ) public virtual onlyOwner returns ( bool ) { // Require Valid Address // Require Valid Address require ( address ( manager ) != address ( 0 ), "Pod:invalid-manager-address" ); Recommendation Change the check to: require ( address ( newManager ) != address ( 0 ), "Pod:invalid-manager-address" ); More generally, attempt to define validity criteria for all input values that are as strict as possible. Consider preventing zero inputs or inputs that might conflict with other addresses in the smart contract system altogether, including in contract initialization functions. 4 Recommendations 4 Recommendations 4.1 Rename 4.1 Rename Withdrawl event to event to Withdrawal Description The Pod contract contains an event Withdrawl(address, uint256, uint256) : code/pods-v3-contracts/contracts/Pod.sol:L76-L79 code/pods-v3-contracts/contracts/Pod.sol:L76-L79 /** /** * @dev Emitted when user withdraws * @dev Emitted when user withdraws */ */ event Withdrawl ( address user , uint256 amount , uint256 shares ); This appears to be a misspelling of the word Withdrawal . This is of course not a problem given it’s consistent use, but could cause confusion for users or issues in future contract updates. Appendix 1 - Files in Scope Appendix 1 - Files in Scope File File SHA-1 hash SHA-1 hash Pod.sol 641689b5f218fca0efdb5bbdd341188b28330d06 PodFactory.sol 222481a98d4e43cb7ecea718c9c128fac1e0ac57 TokenDrop.sol ab9713b77031662e16ce9e4b6b7766b1d2f6ff44 TokenDropFactory.sol eab23cdc4b779bb062de96a2a4dba0973556a895Appendix 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 other 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.Request 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. 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
Fix Fix The depositTo() function should be modified to require a minimum deposit amount. This amount should be large enough to make frontrunning economically infeasible. Answer: Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 1 Critical: 5.a Problem: Winning pods can be frontrun with large deposits 5.b Fix: The depositTo() function should be modified to require a minimum deposit amount. This amount should be large enough to make frontrunning economically infeasible. Observations: None Conclusion: The review was conducted by Sergii Kravchenko and Nicholas Ward over the course of ten person-days between March 29 and April 2, 2021. The review focused on commit hash 879dc8b911fc506dd6bead1f36eade919ccfea57 and was limited to the Pod and TokenDrop contracts along with their respective factory contracts. The review found one critical issue which should be addressed by modifying the depositTo() function to require a minimum deposit amount. Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 0 Critical: 3 Critical 1. Token transfers may return false Problem: There are a lot of token transfers in the code, and most of them are just calling transfer or transferFrom without checking the return value. Fix: Use the safeTransfer and the safeTransferFrom versions of transfers from OZ. 2. TokenDrop: Unprotected initialize() function Problem: The TokenDrop.initialize() function is unprotected and can be called multiple times. Fix: Add the initializer modifier to the initialize() function and include an explicit test that every initialization function in the system can be called once and only once. 3. Pod: Re-entrancy during deposit or withdrawal can lead to stealing funds Problem: During the deposit, the token transfer is made after the Pod shares are minted. Fix: Make sure that the token transfer is made before the Pod shares are minted. Observations: An attacker could identify a winning Pod contract and make a large deposit, diluting existing user shares and claiming the entire prize. Conclusion: The modifier pauseDeposits Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 1 Major: 1 Critical: 0 Minor Issues: None Moderate Issues: 3.6 Pod: Having multiple token drops is inconsistent Problem: The Pod contract had the drop storage field and mapping of different TokenDrops (token => TokenDrop). Fix: Remove the drop storage field and mapping of different TokenDrops (token => TokenDrop). Major Issues: 3.5 TokenDrop: Re-entrancy in the claim function can cause to draining funds Problem: If the asset token is making a call before the transfer to the receiver or to any other 3-d party contract (like it’s happening in the Pod token using the _beforeTokenTransfer function), the attacker can call the drop function inside the transfer call. Fix: Simply adding re-entrancy guard to the drop and the claim function won’t help because the drop function is called from the claim. For that, the transfer can be moved to a separate function, and this function can have the re-entrancy guard as well as the drop function. Also, it
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); } } pragma solidity 0.4.24; contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract UsingOraclize { byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if ((address(OAR) == 0)||(getCodeSize(address(OAR)) == 0)) oraclize_setNetwork(networkID_auto); if (address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } 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_cbAddress() internal oraclizeAPI returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) internal oraclizeAPI { return oraclize.setProofType(proofP); } function getCodeSize(address _addr) internal view returns(uint _size) { assembly { _size := extcodesize(_addr) } } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure 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; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ 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 a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } function pow(uint256 a, uint256 power) internal pure returns (uint256 result) { assert(a >= 0); result = 1; for (uint256 i = 0; i < power; i++){ result *= a; assert(result >= a); } } } /** * @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; address public pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } constructor() public { owner = msg.sender; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @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 make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { uint256 public decimals; function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function mint( address _to, uint256 _amountusingOraclize ) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) public onlyOwner returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) public onlyOwner returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) public onlyOwner returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) public onlyOwner returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } contract PriceChecker is UsingOraclize { uint256 public priceETHUSD; //price in cents uint256 public centsInDollar = 100; uint256 public lastPriceUpdate; //timestamp of the last price updating uint256 public minUpdatePeriod = 3300; // min timestamp for update in sec event NewOraclizeQuery(string description); event PriceUpdated(uint256 price); constructor() public { oraclize_setProof(proofType_Android | proofStorage_IPFS); _update(0); } /** * @dev Reverts if the timestamp of the last price updating * @dev is older than one hour two minutes. */ modifier onlyActualPrice { require(lastPriceUpdate > now - 3720); _; } /** * @dev Receives the response from oraclize. */ function __callback(bytes32 myid, string result, bytes proof) public { require((lastPriceUpdate + minUpdatePeriod) < now); require(msg.sender == oraclize_cbAddress()); priceETHUSD = parseInt(result, 2); lastPriceUpdate = now; emit PriceUpdated(priceETHUSD); _update(3600); return; proof; myid; //to silence the compiler warning } /** * @dev Cyclic query to update ETHUSD price. Period is one hour. */ function _update(uint256 _timeout) internal { if (oraclize_getPrice("URL") > address(this).balance) { emit NewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit NewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); oraclize_query(_timeout, "URL", "json(https://api.coinmarketcap.com/v1/ticker/ethereum/).0.price_usd"); } } } /** * @title BeamCrowdsale * @dev BeamCrowdsale is a contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the surface of crowdsales. */ contract BeamCrowdsale is Whitelist, PriceChecker, Pausable { using SafeMath for uint256; // Investors to invested amount mapping(address => uint256) public funds; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; // the percent of discount for seed round uint256 public discountSeed = 20; // the percent of discount for private round uint256 public discountPrivate = 15; // the percent of discount for public round uint256 public discountPublic = 10; // Decimals of the using token uint256 public decimals; // Amount of bonuses uint256 public bonuses; // Whether the public round is active bool public publicRound; // Whether the seed round has finished bool public seedFinished; // Whether the crowdsale has finished bool public crowdsaleFinished; // Whether the soft cap has reached bool public softCapReached; // Increasing of the token price in units with each token emission uint256 public increasing = 10 ** 9; // Amount of tokens for seed round uint256 public tokensForSeed = 100 * 10 ** 6 * 10 ** 18; // Soft cap in USD units uint256 public softCap = 2 * 10 ** 6 * 10 ** 18; // Amount of USD raised in units uint256 public usdRaised; uint256 public unitsToInt = 10 ** 18; /** * Event for token purchase logging * @param purchaser who paid and got for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, uint256 value, uint256 amount ); /** * Event for logging of the seed round finish */ event SeedRoundFinished(); /** * Event for logging of the private round finish */ event PrivateRoundFinished(); /** * Event for logging of the private round start */ event StartPrivateRound(); /** * Event for logging of the public round start */ event StartPublicRound(); /** * Event for logging of the public round finish */ event PublicRoundFinished(); /** * Event for logging of the crowdsale finish * @param weiRaised Amount of wei raised during the crowdsale * @param usdRaised Amount of usd raised during the crowdsale (in units) */ event CrowdsaleFinished(uint256 weiRaised, uint256 usdRaised); /** * Event for logging of reaching the soft cap */ event SoftCapReached(); /** * @dev Reverts if crowdsale has finished. */ modifier onlyWhileOpen { require(!crowdsaleFinished); _; } /** * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(address _wallet, ERC20 _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; decimals = token.decimals(); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function */ function () external payable onlyActualPrice onlyWhileOpen onlyWhitelisted whenNotPaused { buyTokens(); } /** * @dev Allows owner to send ETH to the contarct for paying fees or refund. */ function payToContract() external payable onlyOwner {} /** * @dev Allows owner to withdraw ETH from the contract balance. */ function withdrawFunds(address _beneficiary, uint256 _weiAmount) external onlyOwner { require(address(this).balance > _weiAmount); _beneficiary.transfer(_weiAmount); } /** * @dev Alows owner to finish the crowdsale */ function finishCrowdsale() external onlyOwner onlyWhileOpen { crowdsaleFinished = true; uint256 _soldAmount = token.totalSupply().sub(bonuses); token.mint(address(this), _soldAmount); emit TokenPurchase(address(this), 0, _soldAmount); emit CrowdsaleFinished(weiRaised, usdRaised); } /** * @dev Overriden inherited method to prevent calling from third persons */ function update(uint256 _timeout) external payable onlyOwner { _update(_timeout); } /** * @dev Transfers fund to contributor if the crowdsale fails */ function claimFunds() external { require(crowdsaleFinished); require(!softCapReached); require(funds[msg.sender] > 0); require(address(this).balance >= funds[msg.sender]); uint256 toSend = funds[msg.sender]; delete funds[msg.sender]; msg.sender.transfer(toSend); } /** * @dev Allows owner to transfer BEAM tokens * @dev from the crowdsale smart contract balance */ function transferTokens( address _beneficiary, uint256 _tokenAmount ) external onlyOwner { require(token.balanceOf(address(this)) >= _tokenAmount); token.transfer(_beneficiary, _tokenAmount); } /** * @dev Allows owner to add raising fund manually * @param _beneficiary Address performing the token purchase * @param _usdUnits Value in USD units involved in the purchase */ function buyForFiat(address _beneficiary, uint256 _usdUnits) external onlyOwner onlyWhileOpen onlyActualPrice { uint256 _weiAmount = _usdUnits.mul(centsInDollar).div(priceETHUSD); _preValidatePurchase(_beneficiary, _weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( _beneficiary, _weiAmount, tokens ); _postValidatePurchase(); } /** * @dev Mints bonuses by admin * @param _beneficiary Address performing the token purchase * @param _tokenUnits Amount of the tokens to mint */ function mintBonus(address _beneficiary, uint256 _tokenUnits) external onlyOwner onlyWhileOpen { _processPurchase(_beneficiary, _tokenUnits); emit TokenPurchase(_beneficiary, 0, _tokenUnits); bonuses = bonuses.add(_tokenUnits); _postValidatePurchase(); } /** * @dev Allows owner to finish the seed round */ function finishSeedRound() external onlyOwner onlyWhileOpen { require(!seedFinished); seedFinished = true; emit SeedRoundFinished(); emit StartPrivateRound(); } /** * @dev Allows owner to change the discount for seed round */ function setDiscountSeed(uint256 _discountSeed) external onlyOwner onlyWhileOpen { discountSeed = _discountSeed; } /** * @dev Allows owner to change the discount for private round */ function setDiscountPrivate(uint256 _discountPrivate) external onlyOwner onlyWhileOpen { discountPrivate = _discountPrivate; } /** * @dev Allows owner to change the discount for public round */ function setDiscountPublic(uint256 _discountPublic) external onlyOwner onlyWhileOpen { discountPublic = _discountPublic; } /** * @dev Allows owner to start or renew public round * @dev Function accesable only after the end of the seed round * @dev If _enable is true, private round ends and public round starts * @dev If _enable is false, public round ends and private round starts * @param _enable Whether the public round is open */ function setPublicRound(bool _enable) external onlyOwner onlyWhileOpen { require(seedFinished); publicRound = _enable; if (_enable) { emit PrivateRoundFinished(); emit StartPublicRound(); } else { emit PublicRoundFinished(); emit StartPrivateRound(); } } /** * @dev low level token purchase */ function buyTokens() public payable onlyWhileOpen onlyWhitelisted whenNotPaused onlyActualPrice { address _beneficiary = msg.sender; uint256 _weiAmount = msg.value; _preValidatePurchase(_beneficiary, _weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(_weiAmount); _weiAmount = _weiAmount.sub(_applyDiscount(_weiAmount)); funds[_beneficiary] = funds[_beneficiary].add(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(_beneficiary, _weiAmount, tokens); _forwardFunds(_weiAmount); _postValidatePurchase(); } /** * @return Actual token price in USD units */ function tokenPrice() public view returns(uint256) { uint256 _supplyInt = token.totalSupply().div(10 ** decimals); return uint256(10 ** 18).add(_supplyInt.mul(increasing)); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements * @dev to revert state when conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal pure { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @return The square root of 'x' */ function sqrt(uint256 x) internal pure returns (uint256) { uint256 z = (x.add(1)).div(2); uint256 y = x; while (z < y) { y = z; z = ((x.div(z)).add(z)).div(2); } return y; } /** * @return The amount of tokens (without decimals) for specified _usdUnits accounting the price increasing */ function tokenIntAmount(uint256 _startPrice, uint256 _usdUnits) internal view returns(uint256) { uint256 sqrtVal = sqrt(((_startPrice.mul(2).sub(increasing)).pow(2)).add(_usdUnits.mul(8).mul(increasing))); return (increasing.add(sqrtVal).sub(_startPrice.mul(2))).div(increasing.mul(2)); } /** * @dev Calculates the remainder USD amount. * @param _startPrice Address performing the token purchase * @param _usdUnits Value involved in the purchase * @param _tokenIntAmount Value of tokens without decimals * @return Number of USD units to process purchase */ function _remainderAmount( uint256 _startPrice, uint256 _usdUnits, uint256 _tokenIntAmount ) internal view returns(uint256) { uint256 _summ = (_startPrice.mul(2).add(increasing.mul(_tokenIntAmount.sub(1))).mul(_tokenIntAmount)).div(2); return _usdUnits.sub(_summ); } /** * @dev Validation of an executed purchase. Observes state. */ function _postValidatePurchase() internal { if (!seedFinished) _checkSeed(); if (!softCapReached) _checkSoftCap(); } /** * @dev Source of tokens. The way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.mint(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev The way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) { uint256 _usdUnits = _weiAmount.mul(priceETHUSD).div(centsInDollar); usdRaised = usdRaised.add(_usdUnits); uint256 _tokenPrice = tokenPrice(); uint256 _tokenIntAmount = tokenIntAmount(_tokenPrice, _usdUnits); uint256 _tokenUnitAmount = _tokenIntAmount.mul(10 ** decimals); uint256 _newPrice = tokenPrice().add(_tokenIntAmount.mul(increasing)); uint256 _usdRemainder; if (_tokenIntAmount == 0) _usdRemainder = _usdUnits; else _usdRemainder = _remainderAmount(_tokenPrice, _usdUnits, _tokenIntAmount); _tokenUnitAmount = _tokenUnitAmount.add(_usdRemainder.mul(10 ** decimals).div(_newPrice)); return _tokenUnitAmount; } /** * @dev Checks the amount of sold tokens to finish seed round. */ function _checkSeed() internal { if (token.totalSupply() >= tokensForSeed) { seedFinished = true; emit SeedRoundFinished(); emit StartPrivateRound(); } } /** * @dev Checks the USD raised to hit the sodt cap. */ function _checkSoftCap() internal { if (usdRaised >= softCap) { softCapReached = true; emit SoftCapReached(); } } /** * @dev Applys the reward according to bonus system. * @param _weiAmount Value in wei to applying bonus system */ function _applyDiscount(uint256 _weiAmount) internal returns (uint256) { address _payer = msg.sender; uint256 _refundAmount; if (!seedFinished) { _refundAmount = _weiAmount.mul(discountSeed).div(100); } else if (!publicRound) { _refundAmount = _weiAmount.mul(discountPrivate).div(100); } else { _refundAmount = _weiAmount.mul(discountPublic).div(100); } _payer.transfer(_refundAmount); return _refundAmount; } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds(uint256 _weiAmount) internal { wallet.transfer(_weiAmount); } } pragma solidity 0.4.24; /** * @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; address public pendingOwner; address public manager; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // SWC-Typographical Error: L17 event ManagerUpdated(address newManager); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Modifier throws if called by any account other than the manager. */ modifier onlyManager() { require(msg.sender == manager); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } constructor() public { owner = msg.sender; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } /** * @dev Sets the manager address. * @param _manager The manager address. */ function setManager(address _manager) public onlyOwner { require(_manager != address(0)); manager = _manager; // SWC-Typographical Error: L72 emit ManagerUpdated(manager); } } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) public onlyOwner returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) public onlyOwner returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) public onlyOwner returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) public onlyOwner returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Whitelist { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require((!paused) || (whitelist[msg.sender])); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ 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 a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public balances; uint256 public totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @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) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal 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 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); emit 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; emit Approval(msg.sender, _spender, _value); return true; } /** * @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 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, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit 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, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint256 _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint256 _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is PausableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive 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, uint256 _amount ) public onlyManager canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract BeamToken is MintableToken { string public constant name = "Beams"; // solium-disable-line uppercase string public constant symbol = "BEAM"; // solBeamCrowdsaleContractium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase mapping (address => bool) public isLocked; uint256 public constant INITIAL_SUPPLY = 0; constructor() public { totalSupply_ = INITIAL_SUPPLY; } function setLock(address _who, bool _lock) public onlyOwner { require(isLocked[_who] != _lock); isLocked[_who] = _lock; } /** * @dev Modifier to make a function callable only when the caller is not in locklist. */ modifier whenNotLocked() { require(!isLocked[msg.sender]); _; } function transfer( address _to, uint256 _value ) public whenNotLocked returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotLocked returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotLocked returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint256 _addedValue ) public whenNotLocked returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint256 _subtractedValue ) public whenNotLocked returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ 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 a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } function pow(uint256 a, uint256 power) internal pure returns (uint256 result) { assert(a >= 0); result = 1; for (uint256 i = 0; i < power; i++) { result *= a; assert(result >= a); } } } /** * @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; address public pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } constructor() public { owner = msg.sender; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @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 make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { uint256 public decimals; function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); function mint( address _to, uint256 _amountusingOraclize ) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) public onlyOwner returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) public onlyOwner returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) public onlyOwner returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) public onlyOwner returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } contract PriceChecker { uint256 public priceETHUSD; //price in cents uint256 public centsInDollar = 100; uint256 public lastPriceUpdate; //timestamp of the last price updating uint256 public minUpdatePeriod = 3300; // min timestamp for update in sec event NewOraclizeQuery(string description); event PriceUpdated(uint256 price); constructor() public { } /** * @dev Reverts if the timestamp of the last price updating * is older than one hour two minutes. */ modifier onlyActualPrice { require(lastPriceUpdate > now - 3720); _; } function __callback(uint256 result) external { require((lastPriceUpdate + minUpdatePeriod) < now); priceETHUSD = result; lastPriceUpdate = now; emit PriceUpdated(priceETHUSD); return; } } /** * @title BeamCrowdsale * @dev BeamCrowdsale is a contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the surface of crowdsales. */ contract BeamCrowdsale_TEST_ONLY is Whitelist, PriceChecker, Pausable { using SafeMath for uint256; // Investors to invested amount mapping(address => uint256) public funds; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; // the percent of discount for seed round uint256 public discountSeed = 20; // the percent of discount for private round uint256 public discountPrivate = 15; // the percent of discount for public round uint256 public discountPublic = 10; // Decimals of the using token uint256 public decimals; // Amount of bonuses uint256 public bonuses; // Whether the public round is active bool public publicRound; // Whether the seed round has finished bool public seedFinished; // Whether the crowdsale has finished bool public crowdsaleFinished; // Whether the soft cap has reached bool public softCapReached; // Increasing of the token price in units with each token emission uint256 public increasing = 10 ** 9; // Amount of tokens for seed round uint256 public tokensForSeed = 100 * 10 ** 6 * 10 ** 18; // Soft cap in USD units uint256 public softCap = 2 * 10 ** 6 * 10 ** 18; // Amount of USD raised in units uint256 public usdRaised; uint256 public unitsToInt = 10 ** 18; /** * Event for token purchase logging * @param purchaser who paid and got for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, uint256 value, uint256 amount ); /** * Event for logging of the seed round finish */ event SeedRoundFinished(); /** * Event for logging of the private round finish */ event PrivateRoundFinished(); /** * Event for logging of the private round start */ event StartPrivateRound(); /** * Event for logging of the public round start */ event StartPublicRound(); /** * Event for logging of the public round finish */ event PublicRoundFinished(); /** * Event for logging of the crowdsale finish * @param weiRaised Amount of wei raised during the crowdsale * @param usdRaised Amount of usd raised during the crowdsale (in units) */ event CrowdsaleFinished(uint256 weiRaised, uint256 usdRaised); /** * Event for logging of reaching the soft cap */ event SoftCapReached(); /** * @dev Reverts if crowdsale has finished. */ modifier onlyWhileOpen { require(!crowdsaleFinished); _; } /** * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(address _wallet, ERC20 _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; decimals = token.decimals(); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function */ function () external payable onlyActualPrice onlyWhileOpen onlyWhitelisted whenNotPaused { buyTokens(); } /** * @dev Allows owner to send ETH to the contarct for paying fees or refund. */ function payToContract() external payable onlyOwner {} /** * @dev Allows owner to withdraw ETH from the contract balance. */ function withdrawFunds(address _beneficiary, uint256 _weiAmount) external onlyOwner { require(address(this).balance > _weiAmount); _beneficiary.transfer(_weiAmount); } /** * @dev Alows owner to finish the crowdsale */ function finishCrowdsale() external onlyOwner onlyWhileOpen { crowdsaleFinished = true; uint256 _soldAmount = token.totalSupply().sub(bonuses); token.mint(address(this), _soldAmount); emit TokenPurchase(address(this), 0, _soldAmount); emit CrowdsaleFinished(weiRaised, usdRaised); } /** * @dev Transfers fund to contributor if the crowdsale fails */ function claimFunds() external { require(crowdsaleFinished); require(!softCapReached); require(funds[msg.sender] > 0); require(address(this).balance >= funds[msg.sender]); uint256 toSend = funds[msg.sender]; delete funds[msg.sender]; msg.sender.transfer(toSend); } /** * @dev Allows owner to transfer BEAM tokens * @dev from the crowdsale smart contract balance */ function transferTokens( address _beneficiary, uint256 _tokenAmount ) external onlyOwner { require(token.balanceOf(address(this)) >= _tokenAmount); token.transfer(_beneficiary, _tokenAmount); } /** * @dev Allows owner to add raising fund manually * @param _beneficiary Address performing the token purchase * @param _usdUnits Value in USD units involved in the purchase */ function buyForFiat(address _beneficiary, uint256 _usdUnits) external onlyOwner onlyWhileOpen onlyActualPrice { uint256 _weiAmount = _usdUnits.mul(centsInDollar).div(priceETHUSD); _preValidatePurchase(_beneficiary, _weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( _beneficiary, _weiAmount, tokens ); _postValidatePurchase(); } /** * @dev Mints bonuses by admin * @param _beneficiary Address performing the token purchase * @param _tokenUnits Amount of the tokens to mint */ function mintBonus(address _beneficiary, uint256 _tokenUnits) external onlyOwner onlyWhileOpen { _processPurchase(_beneficiary, _tokenUnits); emit TokenPurchase(_beneficiary, 0, _tokenUnits); bonuses = bonuses.add(_tokenUnits); _postValidatePurchase(); } /** * @dev Allows owner to finish the seed round */ function finishSeedRound() external onlyOwner onlyWhileOpen { require(!seedFinished); seedFinished = true; emit SeedRoundFinished(); emit StartPrivateRound(); } /** * @dev Allows owner to change the discount for seed round */ function setDiscountSeed(uint256 _discountSeed) external onlyOwner onlyWhileOpen { discountSeed = _discountSeed; } /** * @dev Allows owner to change the discount for private round */ function setDiscountPrivate(uint256 _discountPrivate) external onlyOwner onlyWhileOpen { discountPrivate = _discountPrivate; } /** * @dev Allows owner to change the discount for public round */ function setDiscountPublic(uint256 _discountPublic) external onlyOwner onlyWhileOpen { discountPublic = _discountPublic; } /** * @dev Allows owner to start or renew public round * @dev Function accesable only after the end of the seed round * @dev If _enable is true, private round ends and public round starts * @dev If _enable is false, public round ends and private round starts * @param _enable Whether the public round is open */ function setPublicRound(bool _enable) external onlyOwner onlyWhileOpen { require(seedFinished); publicRound = _enable; if (_enable) { emit PrivateRoundFinished(); emit StartPublicRound(); } else { emit PublicRoundFinished(); emit StartPrivateRound(); } } /** * @dev low level token purchase */ function buyTokens() public payable onlyWhileOpen onlyWhitelisted whenNotPaused onlyActualPrice { address _beneficiary = msg.sender; uint256 _weiAmount = msg.value; _preValidatePurchase(_beneficiary, _weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(_weiAmount); _weiAmount = _weiAmount.sub(_applyDiscount(_weiAmount)); funds[_beneficiary] = funds[_beneficiary].add(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(_beneficiary, _weiAmount, tokens); _forwardFunds(_weiAmount); _postValidatePurchase(); } /** * @return Actual token price in USD units */ function tokenPrice() public view returns(uint256) { uint256 _supplyInt = token.totalSupply().div(10 ** decimals); return uint256(10 ** 18).add(_supplyInt.mul(increasing)); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements * @dev to revert state when conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal pure { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @return The square root of 'x' */ function sqrt(uint256 x) internal pure returns (uint256) { uint256 z = (x.add(1)).div(2); uint256 y = x; while (z < y) { y = z; z = ((x.div(z)).add(z)).div(2); } return y; } /** * @return The amount of tokens (without decimals) for specified _usdUnits accounting the price increasing */ function tokenIntAmount(uint256 _startPrice, uint256 _usdUnits) internal view returns(uint256) { uint256 sqrtVal = sqrt(((_startPrice.mul(2).sub(increasing)).pow(2)).add(_usdUnits.mul(8).mul(increasing))); return (increasing.add(sqrtVal).sub(_startPrice.mul(2))).div(increasing.mul(2)); } /** * @dev Calculates the remainder USD amount. * @param _startPrice Address performing the token purchase * @param _usdUnits Value involved in the purchase * @param _tokenIntAmount Value of tokens without decimals * @return Number of USD units to process purchase */ function _remainderAmount( uint256 _startPrice, uint256 _usdUnits, uint256 _tokenIntAmount ) internal view returns(uint256) { uint256 _summ = (_startPrice.mul(2).add(increasing.mul(_tokenIntAmount.sub(1))).mul(_tokenIntAmount)).div(2); return _usdUnits.sub(_summ); } /** * @dev Validation of an executed purchase. Observe state and use revert * statements to undo rollback when valid conditions are not met. */ function _postValidatePurchase() internal { if (!seedFinished) _checkSeed(); if (!softCapReached) _checkSoftCap(); } /** * @dev Source of tokens. The way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.mint(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev The way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) { uint256 _usdUnits = _weiAmount.mul(priceETHUSD).div(centsInDollar); usdRaised = usdRaised.add(_usdUnits); uint256 _tokenPrice = tokenPrice(); uint256 _tokenIntAmount = tokenIntAmount(_tokenPrice, _usdUnits); uint256 _tokenUnitAmount = _tokenIntAmount.mul(10 ** decimals); uint256 _newPrice = tokenPrice().add(_tokenIntAmount.mul(increasing)); uint256 _usdRemainder; if (_tokenIntAmount == 0) _usdRemainder = _usdUnits; else _usdRemainder = _remainderAmount(_tokenPrice, _usdUnits, _tokenIntAmount); _tokenUnitAmount = _tokenUnitAmount.add(_usdRemainder.mul(10 ** decimals).div(_newPrice)); return _tokenUnitAmount; } /** * @dev Checks the amount of sold tokens to finish seed round. */ function _checkSeed() internal { if (token.totalSupply() >= tokensForSeed) { seedFinished = true; emit SeedRoundFinished(); emit StartPrivateRound(); } } /** * @dev Checks the USD raised to hit the sodt cap. */ function _checkSoftCap() internal { if (usdRaised >= softCap) { softCapReached = true; emit SoftCapReached(); } } /** * @dev Applys the reward according to bonus system. * @param _weiAmount Value in wei to applying bonus system */ function _applyDiscount(uint256 _weiAmount) internal returns (uint256) { address _payer = msg.sender; uint256 _refundAmount; if (!seedFinished) { _refundAmount = _weiAmount.mul(discountSeed).div(100); } else if (!publicRound) { _refundAmount = _weiAmount.mul(discountPrivate).div(100); } else { _refundAmount = _weiAmount.mul(discountPublic).div(100); } _payer.transfer(_refundAmount); return _refundAmount; } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds(uint256 _weiAmount) internal { wallet.transfer(_weiAmount); } /** * @dev set minUpdatePeriod */ function setMinUpdatePeriod(uint256 _minUpdatePeriod) public onlyOwner { minUpdatePeriod = _minUpdatePeriod; } }
6/30/2022 beam-contracts-audit/readme.md at audit · BlockchainLabsNZ/beam-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/beam-contracts-audit/blob/audit/audit/readme.md 1/5BlockchainLabsNZ /beam-contracts-audit Public beam-contracts-audit / audit / readme.mdCode Issues 1 Pull requests Actions Projects Wiki Security Insights audit Beam Smart Contract Audit R eport Preamble This audit report was undertaken by BlockchainLabs.nz for the purpose of providing feedback to HubbleLand . It has subsequently been shared publicly without any express or implied warranty. Solidity contracts were sourced directly from the HubbleLand team at this commit hash 11b086ca757f1 , we would encourage all community members and token holders to make their own assessment of the contracts once they are deployed and verified. Scope The following contract was a subject for static, dynamic and functional analyses: Contracts BeamCrowdsale.sol BeamT oken.sol126 lines (93 sloc) 8.34 KB6/30/2022 beam-contracts-audit/readme.md at audit · BlockchainLabsNZ/beam-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/beam-contracts-audit/blob/audit/audit/readme.md 2/5Focus areas The 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 Test coverage Dynamic tests Gas usage Functional tests6/30/2022 beam-contracts-audit/readme.md at audit · BlockchainLabsNZ/beam-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/beam-contracts-audit/blob/audit/audit/readme.md 3/5Issues Severity Description MinorA defect that does not have a material impact on the contract execution and is likely to be subjective. ModerateA 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 Typo in event name MenegerUpdated - Correctness #L16 and #L70 View on GitHub Fixed: 468b86 Prefer explicit declaration of variable types - Best practice Prefer to use explicit variables types. It is recommended to explicitly define your variable types and keep consistency. This confirms your intent and safeguards against a future when the default type changes. #L411 Prefer uint256 instead of uint. View on GitHub Fixed: 468b86 Function docstring not accurate to function - Best practice The _postValidatePurchase docstring mentions that the function should use revert statements to rollback when valid conditions are not met. The _checkSeed and _checkSoftCap functions do not use any reverts. #L873-L874 View on GitHub Fixed: 468b86 Avoid magic numbers - Best practice In BeamCrowdsale.sol there are some hard coded values, this code could be more readable/maintainable if the values were saved to a variable instead. The two oraclize_query functions contain this line: if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price View on GitHub Fixed: 468b86 Recommend externalising shared contracts e.g Ownable, SafeMath, Whitelist Best Practice There are shared contracts which are imported by CustomContract.sol, BeamCrowdsale.sol, and BeamT oken.sol which are duplicated in each file. These shared contracts could be put into their own file6/30/2022 beam-contracts-audit/readme.md at audit · BlockchainLabsNZ/beam-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/beam-contracts-audit/blob/audit/audit/readme.md 4/5so they only need to be modified once. This would make it less likely to introduce mistakes if the contracts need changed. View on GitHub Moderate Race condition found when user claiming their ETH from the contract - Best practice, Security` #L643-L644 This is a typical race condition. It can cause you lose all the ETHs deposited in the contract. Fixing is required! More infor about Race Condition View on GitHub Fixed: 468b86 Major None found Critical None found Observations The function setPublicRound allows you to start/finish a public or private round. There is no check that the public or private round has already been finished, so it would be possible to start either round multiple times. The usage for the buyForFiat function is not well documented, this function is only for owners so this is not a huge issue. How to calculate _usdUnits is not clear unless you hunt around the contract for other usages. The crowdsale contract has a withdrawFunds function that allows the contract owner to withdraw all ETH from the contract at any time. https://github.com/BlockchainLabsNZ/beam-contracts- audit/blob/master/contracts/BeamCrowdsale.sol#L605-L611 Conclusion The developers demonstrated an understanding of Solidity and smart contracts. They were receptive to the feedback provided to help improve the robustness of the contracts. W e took part in carefully reviewing all source code provided.6/30/2022 beam-contracts-audit/readme.md at audit · BlockchainLabsNZ/beam-contracts-audit · GitHub https://github.com/BlockchainLabsNZ/beam-contracts-audit/blob/audit/audit/readme.md 5/5Overall we consider the resulting contracts following the audit feedback period adequate and any potential vulnerabilities have now been fully resolved. These contracts have a low level risk of ETH and BEAM being hacked or stolen from the inspected contracts ___ Disclaimer Our team uses our current understanding of the best practises for Solidity and Smart Contracts. Development in Solidity and for Blockchain is an emerging 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.
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 (line 545) 2.b Fix (one line with code reference): Check return value of transferFrom (line 545) Observations The codebase is well written and follows best practices. Conclusion The audit found two minor issues which have been addressed. The codebase is well written and follows best practices. Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem: Typo in event name MenegerUpdated - Correctness #L16 and #L70 2.b Fix: Fixed: 468b86 2.a Problem: Prefer explicit declaration of variable types - Best practice 2.b Fix: Fixed: 468b86 Major None Critical None Observations Function docstring not accurate to function - Best practice Conclusion The audit report found two minor issues with the contracts, which have been fixed. No major or critical issues were found. Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues - Problem: The _checkSeed and _checkSoftCap functions do not use any reverts. #L873-L874 - Fix: 468b86 Moderate Issues - Problem: Avoid magic numbers in BeamCrowdsale.sol - Fix: 468b86 Major Issues - None found Critical Issues - None found Observations - The function setPublicRound allows you to start/finish a public or private round without any check that the public or private round has already been finished. - The usage for the buyForFiat function is not well documented. - The crowdsale contract has a withdrawFunds function that allows the contract owner to withdraw all ETH from the contract at any time. Conclusion - The developers demonstrated an understanding of Solidity and smart contracts. - The resulting contracts following the audit feedback period are adequate and any potential vulnerabilities have now been fully resolved. - These contracts have a low level risk of ETH and BEAM being hacked or
pragma solidity 0.4.23; contract PoaProxy { uint8 public constant version = 1; bytes32 public constant proxyMasterContractSlot = keccak256("masterAddress"); bytes32 public constant proxyRegistrySlot = keccak256("registry"); event ProxyUpgradedEvent(address upgradedFrom, address upgradedTo); constructor( address _master, address _registry ) public { require(_master != address(0)); require(_registry != address(0)); bytes32 _proxyMasterContractSlot = proxyMasterContractSlot; bytes32 _proxyRegistrySlot = proxyRegistrySlot; // all storage locations are pre-calculated using hashes of names assembly { sstore(_proxyMasterContractSlot, _master) // store master address in master slot sstore(_proxyRegistrySlot, _registry) // store registry address in registry slot } } // // proxy state getters // function proxyMasterContract() public view returns (address _masterContract) { bytes32 _proxyMasterContractSlot = proxyMasterContractSlot; assembly { _masterContract := sload(_proxyMasterContractSlot) } } function proxyRegistry() public view returns (address _proxyRegistry) { bytes32 _proxyRegistrySlot = proxyRegistrySlot; assembly { _proxyRegistry := sload(_proxyRegistrySlot) } } // // proxy state helpers // function getContractAddress( string _name ) public view returns (address _contractAddress) { bytes4 _sig = bytes4(keccak256("getContractAddress32(bytes32)")); bytes32 _name32 = keccak256(_name); bytes32 _proxyRegistrySlot = proxyRegistrySlot; assembly { let _call := mload(0x40) // set _call to free memory pointer mstore(_call, _sig) // store _sig at _call pointer mstore(add(_call, 0x04), _name32) // store _name32 at _call offset by 4 bytes for pre-existing _sig // staticcall(g, a, in, insize, out, outsize) => 0 on error 1 on success let success := staticcall( gas, // g = gas: whatever was passed already sload(_proxyRegistrySlot), // a = address: address in storage _call, // in = mem in mem[in..(in+insize): set to free memory pointer 0x24, // insize = mem insize mem[in..(in+insize): size of sig (bytes4) + bytes32 = 0x24 _call, // out = mem out mem[out..(out+outsize): output assigned to this storage address 0x20 // outsize = mem outsize mem[out..(out+outsize): output should be 32byte slot (address size = 0x14 < slot size 0x20) ) // revert if not successful if iszero(success) { revert(0, 0) } _contractAddress := mload(_call) // assign result to return value mstore(0x40, add(_call, 0x24)) // advance free memory pointer by largest _call size } } // ensures that address has code/is contract function proxyIsContract(address _address) private view returns (bool) { uint256 _size; assembly { _size := extcodesize(_address) } return _size > 0; } // // proxy state setters // function proxyChangeMaster(address _newMaster) public returns (bool) { require(msg.sender == getContractAddress("PoaManager")); require(_newMaster != address(0)); require(proxyMasterContract() != _newMaster); require(proxyIsContract(_newMaster)); address _oldMaster = proxyMasterContract(); bytes32 _proxyMasterContractSlot = proxyMasterContractSlot; assembly { sstore(_proxyMasterContractSlot, _newMaster) } emit ProxyUpgradedEvent(_oldMaster, _newMaster); getContractAddress("Logger").call( bytes4(keccak256("logProxyUpgradedEvent(address,address)")), _oldMaster, _newMaster ); return true; } // // fallback for all proxied functions // function() external payable { bytes32 _proxyMasterContractSlot = proxyMasterContractSlot; assembly { // load address from first storage pointer let _master := sload(_proxyMasterContractSlot) // calldatacopy(t, f, s) calldatacopy( 0x0, // t = mem position to 0x0, // f = mem position from calldatasize // s = size bytes ) // delegatecall(g, a, in, insize, out, outsize) => 0 on error 1 on success let success := delegatecall( gas, // g = gas _master, // a = address 0x0, // in = mem in mem[in..(in+insize) calldatasize, // insize = mem insize mem[in..(in+insize) 0x0, // out = mem out mem[out..(out+outsize) 0 // outsize = mem outsize mem[out..(out+outsize) ) // returndatacopy(t, f, s) returndatacopy( 0x0, // t = mem position to 0x0, // f = mem position from returndatasize // s = size bytes ) // check if call was a success and return if no errors & revert if errors if iszero(success) { revert(0, 0) } return( 0x0, returndatasize ) } } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IPoaToken.sol"; import "./PoaProxy.sol"; contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private brokerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private brokerMap; event BrokerAddedEvent(address indexed broker); event BrokerRemovedEvent(address indexed broker); event BrokerStatusChangedEvent(address indexed broker, bool active); event TokenAddedEvent(address indexed token); event TokenRemovedEvent(address indexed token); event TokenStatusChangedEvent(address indexed token, bool active); modifier doesEntityExist(address _entityAddress, EntityState entity) { require(_entityAddress != address(0)); require(entity.index != 0); _; } modifier isNewBroker(address _brokerAddress) { require(_brokerAddress != address(0)); require(brokerMap[_brokerAddress].index == 0); _; } modifier onlyActiveBroker() { EntityState memory entity = brokerMap[msg.sender]; require(entity.active); _; } constructor( address _registryAddress ) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and broker, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Broker functions // // Return all tracked broker addresses function getBrokerAddressList() public view returns (address[]) { return brokerAddressList; } // Add a broker and set active value to true function addBroker(address _brokerAddress) public onlyOwner isNewBroker(_brokerAddress) { brokerMap[_brokerAddress] = addEntity( _brokerAddress, brokerAddressList, true ); emit BrokerAddedEvent(_brokerAddress); } // Remove a broker function removeBroker(address _brokerAddress) public onlyOwner doesEntityExist(_brokerAddress, brokerMap[_brokerAddress]) { address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(brokerMap[_brokerAddress], brokerAddressList); brokerMap[addressToUpdate].index = indexUpdate; delete brokerMap[_brokerAddress]; emit BrokerRemovedEvent(_brokerAddress); } // Set previously delisted broker to listed function listBroker(address _brokerAddress) public onlyOwner doesEntityExist(_brokerAddress, brokerMap[_brokerAddress]) { setEntityActiveValue(brokerMap[_brokerAddress], true); emit BrokerStatusChangedEvent(_brokerAddress, true); } // Set previously listed broker to delisted function delistBroker(address _brokerAddress) public onlyOwner doesEntityExist(_brokerAddress, brokerMap[_brokerAddress]) { setEntityActiveValue(brokerMap[_brokerAddress], false); emit BrokerStatusChangedEvent(_brokerAddress, false); } function getBrokerStatus(address _brokerAddress) public view doesEntityExist(_brokerAddress, brokerMap[_brokerAddress]) returns (bool) { return brokerMap[_brokerAddress].active; } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createProxy(address _target) private returns (address _proxyContract) { _proxyContract = new PoaProxy(_target, address(registry)); } // Create a PoaToken contract with given parameters, and set active value to true function addToken ( string _name, string _symbol, // fiat symbol used in ExchangeRates string _fiatCurrency, address _custodian, uint256 _totalSupply, // given as unix time (seconds since 01.01.1970) uint256 _startTime, // given as seconds offset from startTime uint256 _fundingTimeout, // given as seconds offset from fundingTimeout uint256 _activationTimeout, // given as fiat cents uint256 _fundingGoalInCents ) public onlyActiveBroker returns (address) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _tokenAddress = createProxy(_poaTokenMaster); IPoaToken(_tokenAddress).setupContract( _name, _symbol, _fiatCurrency, msg.sender, _custodian, _totalSupply, _startTime, _fundingTimeout, _activationTimeout, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAddedEvent(_tokenAddress); return _tokenAddress; } // Remove a token function removeToken(address _tokenAddress) public onlyOwner doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]) { address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemovedEvent(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]) { setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChangedEvent(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]) { setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChangedEvent(_tokenAddress, false); } function getTokenStatus(address _tokenAddress) public view doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]) returns (bool) { return tokenMap[_tokenAddress].active; } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } function setupPoaToken( address _tokenAddress, string _name, string _symbol, // fiat symbol used in ExchangeRates string _fiatCurrency, address _broker, address _custodian, uint256 _totalSupply, // given as unix time (seconds since 01.01.1970) uint256 _startTime, // given as seconds uint256 _fundingTimeout, uint256 _activationTimeout, // given as fiat cents uint256 _fundingGoalInCents ) public onlyOwner returns (bool) { IPoaToken(_tokenAddress).setupContract( _name, _symbol, _fiatCurrency, _broker, _custodian, _totalSupply, _startTime, _fundingTimeout, _activationTimeout, _fundingGoalInCents ); return true; } function upgradeToken( address _proxyTokenAddress, address _masterUpgrade ) public onlyOwner returns (bool) { PoaProxy(_proxyTokenAddress).proxyChangeMaster(_masterUpgrade); } // toggle whitelisting required on transfer & transferFrom for a token function toggleTokenWhitelistTransfers( address _tokenAddress ) public onlyOwner returns (bool) { return IPoaToken(_tokenAddress).toggleWhitelistTransfers(); } // // Fallback // // prevent anyone from sending funds other than selfdestructs of course :) function() public payable { revert(); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IExchangeRateProvider.sol"; /* Q/A Q: Why are there two contracts for ExchangeRates? A: Testing Oraclize seems to be a bit difficult especially considering the bridge requires node v6... With that in mind, it was decided that the best way to move forward was to isolate the oraclize functionality and replace with a stub in order to facilitate effective tests. Q: Why are rates private? A: So that they can be returned through custom getters getRate and getRateReadable. This is so that we can revert when a rate has not been initialized or an error happened when fetching. Oraclize returns '' when erroring which we parse as a uint256 which turns to 0. */ // main contract contract ExchangeRates is Ownable { uint8 public constant version = 1; // instance of Registry to be used for getting other contract addresses IRegistry private registry; // flag used to tell recursive rate fetching to stop bool public ratesActive = true; struct Settings { string queryString; uint256 callInterval; uint256 callbackGasLimit; } // the actual exchange rate for each currency // private so that when rate is 0 (error or unset) we can revert through // getter functions getRate and getRateReadable mapping (bytes32 => uint256) private rates; // points to currencySettings from callback // is used to validate queryIds from ExchangeRateProvider mapping (bytes32 => string) public queryTypes; // storage for query settings... modifiable for each currency // accessed and used by ExchangeRateProvider mapping (string => Settings) private currencySettings; event RateUpdatedEvent(string currency, uint256 rate); event QueryNoMinBalanceEvent(); event QuerySentEvent(string currency); event SettingsUpdatedEvent(string currency); // used to only allow specific contract to call specific functions modifier onlyContract(string _contractName) { require( msg.sender == registry.getContractAddress(_contractName) ); _; } // sets registry for talking to ExchangeRateProvider constructor( address _registryAddress ) public payable { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); owner = msg.sender; } // start rate fetching for a specific currency. Kicks off the first of // possibly many recursive query calls on ExchangeRateProvider to get rates. function fetchRate(string _queryType) external onlyOwner payable returns (bool) { // get the ExchangeRateProvider from registry IExchangeRateProvider provider = IExchangeRateProvider( registry.getContractAddress("ExchangeRateProvider") ); // get settings to use in query on ExchangeRateProvider uint256 _callInterval; uint256 _callbackGasLimit; string memory _queryString; ( _callInterval, _callbackGasLimit, _queryString ) = getCurrencySettings(_queryType); // check that queryString isn't empty before making the query require( bytes(_queryString).length > 0, "_queryString is empty" ); // make query on ExchangeRateProvider // forward any ether value sent on to ExchangeRateProvider // setQuery is called from ExchangeRateProvider to trigger an event // whether there is enough balance or not provider.sendQuery.value(msg.value)( _queryString, _callInterval, _callbackGasLimit, _queryType ); return true; } // // start exchange rate provider only functions // // set a pending queryId callable only by ExchangeRateProvider // set from sendQuery on ExchangeRateProvider // used to check that correct query is being matched to correct values function setQueryId( bytes32 _queryId, string _queryType ) external onlyContract("ExchangeRateProvider") returns (bool) { if (_queryId[0] != 0x0 && bytes(_queryType)[0] != 0x0) { emit QuerySentEvent(_queryType); queryTypes[_queryId] = _queryType; } else { emit QueryNoMinBalanceEvent(); } return true; } // called only by ExchangeRateProvider // sets the rate for a given currency when query __callback occurs. // checks that the queryId returned is correct. function setRate( bytes32 _queryId, uint256 _result ) external onlyContract("ExchangeRateProvider") returns (bool) { // get the query type (usd, eur, etc) string memory _queryType = queryTypes[_queryId]; // check that first byte of _queryType is not 0 (something wrong or empty) // if the queryType is 0 then the queryId is incorrect require(bytes(_queryType).length > 0); // set _queryId to empty (uninitialized, to prevent from being called again) delete queryTypes[_queryId]; // set currency rate depending on _queryType (USD, EUR, etc.) rates[keccak256(_queryType)] = _result; // event for particular rate that was updated emit RateUpdatedEvent( _queryType, _result ); return true; } // // end exchange rate provider only settings // /* set setting for a given currency: currencyName: used as identifier to store settings (stored as bytes8) queryString: the http endpoint to hit to get data along with format example: "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD" callInterval: used to specifiy how often (if at all) the rate should refresh callbackGasLimit: used to specify how much gas to give the oraclize callback */ function setCurrencySettings( string _currencyName, string _queryString, uint256 _callInterval, uint256 _callbackGasLimit ) external onlyOwner returns (bool) { // store settings by bytes8 of string, convert queryString to bytes array currencySettings[toUpperCase(_currencyName)] = Settings( _queryString, _callInterval, _callbackGasLimit ); emit SettingsUpdatedEvent(_currencyName); return true; } // set only query string in settings for a given currency function setCurrencySettingQueryString( string _currencyName, string _queryString ) external onlyOwner returns (bool) { Settings storage _settings = currencySettings[toUpperCase(_currencyName)]; _settings.queryString = _queryString; emit SettingsUpdatedEvent(_currencyName); return true; } // set only callInterval in settings for a given currency function setCurrencySettingCallInterval( string _currencyName, uint256 _callInterval ) external onlyOwner returns (bool) { Settings storage _settings = currencySettings[toUpperCase(_currencyName)]; _settings.callInterval = _callInterval; emit SettingsUpdatedEvent(_currencyName); return true; } // set only callbackGasLimit in settings for a given currency function setCurrencySettingCallbackGasLimit( string _currencyName, uint256 _callbackGasLimit ) external onlyOwner returns (bool) { Settings storage _settings = currencySettings[toUpperCase(_currencyName)]; _settings.callbackGasLimit = _callbackGasLimit; emit SettingsUpdatedEvent(_currencyName); return true; } // set callback gasPrice for all currencies function setCallbackGasPrice(uint256 _gasPrice) external onlyOwner returns (bool) { // get the ExchangeRateProvider from registry IExchangeRateProvider provider = IExchangeRateProvider( registry.getContractAddress("ExchangeRateProvider") ); provider.setCallbackGasPrice(_gasPrice); emit SettingsUpdatedEvent("ALL"); return true; } // set to active or inactive in order to stop recursive rate fetching // rate needs to be fetched once in order for it to stop. function toggleRatesActive() external onlyOwner returns (bool) { ratesActive = !ratesActive; emit SettingsUpdatedEvent("ALL"); return true; } // // end setter functions // // // start getter functions // // retrieve settings for a given currency (queryType) function getCurrencySettings(string _queryTypeString) public view returns (uint256, uint256, string) { Settings memory _settings = currencySettings[_queryTypeString]; return ( _settings.callInterval, _settings.callbackGasLimit, _settings.queryString ); } // get rate with string for easy use by regular accounts function getRate(string _queryTypeString) external view returns (uint256) { uint256 _rate = rates[keccak256(toUpperCase(_queryTypeString))]; require(_rate > 0, "Fiat rate should be higher than zero"); return _rate; } // get rate with bytes32 for easier assembly calls // uppercase protection not provided... function getRate32(bytes32 _queryType32) external view returns (uint256) { uint256 _rate = rates[_queryType32]; require(_rate > 0, "Fiat rate should be higher than zero"); return _rate; } // // end getter functions // // // start utility functions // // convert string to uppercase to ensure that there are not multiple // instances of same currencies function toUpperCase(string _base) pure public returns (string) { bytes memory _stringBytes = bytes(_base); for ( uint _byteCounter = 0; _byteCounter < _stringBytes.length; _byteCounter++ ) { if ( _stringBytes[_byteCounter] >= 0x61 && _stringBytes[_byteCounter] <= 0x7A ) { _stringBytes[_byteCounter] = bytes1( uint8(_stringBytes[_byteCounter]) - 32 ); } } return string(_stringBytes); } // // end utility functions // // used for selfdestructing the provider in order to get back any unused ether // useful for upgrades where we want to get money back from contract function killProvider(address _address) public onlyOwner { // get the ExchangeRateProvider from registry IExchangeRateProvider provider = IExchangeRateProvider( registry.getContractAddress("ExchangeRateProvider") ); provider.selfDestruct(_address); } // prevent anyone from sending funds other than selfdestructs of course :) function() public payable { revert(); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; contract CustomPOAToken is PausableToken { uint8 public constant version = 1; string public name; string public symbol; uint8 public constant decimals = 18; address public owner; address public broker; address public custodian; uint256 public creationBlock; uint256 public timeoutBlock; // the total per token payout rate: accumulates as payouts are received uint256 public totalPerTokenPayout; uint256 public tokenSaleRate; uint256 public fundedAmount; uint256 public fundingGoal; uint256 public initialSupply; // ‰ permille NOT percent uint256 public constant feeRate = 5; // self contained whitelist on contract, must be whitelisted to buy mapping (address => bool) public whitelisted; // used to deduct already claimed payouts on a per token basis mapping(address => uint256) public claimedPerTokenPayouts; // fallback for when a transfer happens with payouts remaining mapping(address => uint256) public unclaimedPayoutTotals; enum Stages { Funding, Pending, Failed, Active, Terminated } Stages public stage = Stages.Funding; event StageEvent(Stages stage); event BuyEvent(address indexed buyer, uint256 amount); event PayoutEvent(uint256 amount); event ClaimEvent(uint256 payout); event TerminatedEvent(); event WhitelistedEvent(address indexed account, bool isWhitelisted); modifier isWhitelisted() { require(whitelisted[msg.sender]); _; } modifier onlyCustodian() { require(msg.sender == custodian); _; } // start stage related modifiers modifier atStage(Stages _stage) { require(stage == _stage); _; } modifier atEitherStage(Stages _stage, Stages _orStage) { require(stage == _stage || stage == _orStage); _; } modifier checkTimeout() { if (stage == Stages.Funding && block.number >= creationBlock.add(timeoutBlock)) { uint256 _unsoldBalance = balances[this]; balances[this] = 0; totalSupply_ = totalSupply_.sub(_unsoldBalance); emit Transfer(this, address(0), balances[this]); enterStage(Stages.Failed); } _; } // end stage related modifiers // token totalSupply must be more than fundingGoal! constructor ( string _name, string _symbol, address _broker, address _custodian, uint256 _timeoutBlock, uint256 _totalSupply, uint256 _fundingGoal ) public { require(_fundingGoal > 0); require(_totalSupply > _fundingGoal); owner = msg.sender; name = _name; symbol = _symbol; broker = _broker; custodian = _custodian; timeoutBlock = _timeoutBlock; creationBlock = block.number; // essentially sqm unit of building... totalSupply_ = _totalSupply; initialSupply = _totalSupply; fundingGoal = _fundingGoal; balances[this] = _totalSupply; paused = true; } // start token conversion functions /******************* * TKN supply * * --- = ------- * * ETH funding * *******************/ // util function to convert wei to tokens. can be used publicly to see // what the balance would be for a given Ξ amount. // will drop miniscule amounts of wei due to integer division function weiToTokens(uint256 _weiAmount) public view returns (uint256) { return _weiAmount .mul(1e18) .mul(initialSupply) .div(fundingGoal) .div(1e18); } // util function to convert tokens to wei. can be used publicly to see how // much Ξ would be received for token reclaim amount // will typically lose 1 wei unit of Ξ due to integer division function tokensToWei(uint256 _tokenAmount) public view returns (uint256) { return _tokenAmount .mul(1e18) .mul(fundingGoal) .div(initialSupply) .div(1e18); } // end token conversion functions // pause override function unpause() public onlyOwner whenPaused { // only allow unpausing when in Active stage require(stage == Stages.Active); return super.unpause(); } // stage related functions function enterStage(Stages _stage) private { stage = _stage; emit StageEvent(_stage); } // start whitelist related functions // allow address to buy tokens function whitelistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != true); whitelisted[_address] = true; emit WhitelistedEvent(_address, true); } // disallow address to buy tokens. function blacklistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != false); whitelisted[_address] = false; emit WhitelistedEvent(_address, false); } // check to see if contract whitelist has approved address to buy function whitelisted(address _address) public view returns (bool) { return whitelisted[_address]; } // end whitelist related functions // start fee handling functions // public utility function to allow checking of required fee for a given amount function calculateFee(uint256 _value) public pure returns (uint256) { return feeRate.mul(_value).div(1000); } // end fee handling functions // start lifecycle functions function buy() public payable checkTimeout atStage(Stages.Funding) isWhitelisted returns (bool) { uint256 _payAmount; uint256 _buyAmount; // check if balance has met funding goal to move on to Pending if (fundedAmount.add(msg.value) < fundingGoal) { // _payAmount is just value sent _payAmount = msg.value; // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // check that buyer will indeed receive something after integer division // this check cannot be done in other case because it could prevent // contract from moving to next stage require(_buyAmount > 0); } else { // let the world know that the token is in Pending Stage enterStage(Stages.Pending); // set refund amount (overpaid amount) uint256 _refundAmount = fundedAmount.add(msg.value).sub(fundingGoal); // get actual Ξ amount to buy _payAmount = msg.value.sub(_refundAmount); // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // assign remaining dust uint256 _dust = balances[this].sub(_buyAmount); // sub dust from contract balances[this] = balances[this].sub(_dust); // give dust to owner balances[owner] = balances[owner].add(_dust); emit Transfer(this, owner, _dust); // SHOULD be ok even with reentrancy because of enterStage(Stages.Pending) msg.sender.transfer(_refundAmount); } // deduct token buy amount balance from contract balance balances[this] = balances[this].sub(_buyAmount); // add token buy amount to sender's balance balances[msg.sender] = balances[msg.sender].add(_buyAmount); // increment the funded amount fundedAmount = fundedAmount.add(_payAmount); // send out event giving info on amount bought as well as claimable dust emit Transfer(this, msg.sender, _buyAmount); emit BuyEvent(msg.sender, _buyAmount); return true; } function activate() external checkTimeout onlyCustodian payable atStage(Stages.Pending) returns (bool) { // calculate company fee charged for activation uint256 _fee = calculateFee(fundingGoal); // value must exactly match fee require(msg.value == _fee); // if activated and fee paid: put in Active stage enterStage(Stages.Active); // owner (company) fee set in unclaimedPayoutTotals to be claimed by owner unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee); // custodian value set to claimable. can now be claimed via claim function // set all eth in contract other than fee as claimable. // should only be buy()s. this ensures buy() dust is cleared unclaimedPayoutTotals[custodian] = unclaimedPayoutTotals[custodian] .add(address(this).balance.sub(_fee)); // allow trading of tokens paused = false; // let world know that this token can now be traded. emit Unpause(); return true; } // used when property no longer exists etc. allows for winding down via payouts // can no longer be traded after function is run function terminate() external onlyCustodian atStage(Stages.Active) returns (bool) { // set Stage to terminated enterStage(Stages.Terminated); // pause. Cannot be unpaused now that in Stages.Terminated paused = true; // let the world know this token is in Terminated Stage emit TerminatedEvent(); } // emergency temporary function used only in case of emergency to return // Ξ to contributors in case of catastrophic contract failure. function kill() external onlyOwner { // stop trading paused = true; // enter stage which will no longer allow unpausing enterStage(Stages.Terminated); // transfer funds to company in order to redistribute manually owner.transfer(address(this).balance); // let the world know that this token is in Terminated Stage emit TerminatedEvent(); } // end lifecycle functions // start payout related functions // get current payout for perTokenPayout and unclaimed function currentPayout(address _address, bool _includeUnclaimed) public view returns (uint256) { /* need to check if there have been no payouts safe math will throw otherwise due to dividing 0 The below variable represents the total payout from the per token rate pattern it uses this funky naming pattern in order to differentiate from the unclaimedPayoutTotals which means something very different. */ uint256 _totalPerTokenUnclaimedConverted = totalPerTokenPayout == 0 ? 0 : balances[_address] .mul(totalPerTokenPayout.sub(claimedPerTokenPayouts[_address])) .div(1e18); /* balances may be bumped into unclaimedPayoutTotals in order to maintain balance tracking accross token transfers perToken payout rates are stored * 1e18 in order to be kept accurate perToken payout is / 1e18 at time of usage for actual Ξ balances unclaimedPayoutTotals are stored as actual Ξ value no need for rate * balance */ return _includeUnclaimed ? _totalPerTokenUnclaimedConverted.add(unclaimedPayoutTotals[_address]) : _totalPerTokenUnclaimedConverted; } // settle up perToken balances and move into unclaimedPayoutTotals in order // to ensure that token transfers will not result in inaccurate balances function settleUnclaimedPerTokenPayouts(address _from, address _to) private returns (bool) { // add perToken balance to unclaimedPayoutTotals which will not be affected by transfers unclaimedPayoutTotals[_from] = unclaimedPayoutTotals[_from].add(currentPayout(_from, false)); // max out claimedPerTokenPayouts in order to effectively make perToken balance 0 claimedPerTokenPayouts[_from] = totalPerTokenPayout; // same as above for to unclaimedPayoutTotals[_to] = unclaimedPayoutTotals[_to].add(currentPayout(_to, false)); // same as above for to claimedPerTokenPayouts[_to] = totalPerTokenPayout; return true; } // used to manually set Stage to Failed when no users have bought any tokens // if no buy()s occurred before timeoutBlock token would be stuck in Funding function setFailed() external atStage(Stages.Funding) checkTimeout returns (bool) { if (stage == Stages.Funding) { revert(); } return true; } // reclaim Ξ for sender if fundingGoal is not met within timeoutBlock function reclaim() external checkTimeout atStage(Stages.Failed) returns (bool) { // get token balance of user uint256 _tokenBalance = balances[msg.sender]; // ensure that token balance is over 0 require(_tokenBalance > 0); // set token balance to 0 so re reclaims are not possible balances[msg.sender] = 0; // decrement totalSupply by token amount being reclaimed totalSupply_ = totalSupply_.sub(_tokenBalance); emit Transfer(msg.sender, address(0), _tokenBalance); // decrement fundedAmount by eth amount converted from token amount being reclaimed fundedAmount = fundedAmount.sub(tokensToWei(_tokenBalance)); // set reclaim total as token value uint256 _reclaimTotal = tokensToWei(_tokenBalance); // send Ξ back to sender msg.sender.transfer(_reclaimTotal); return true; } // send Ξ to contract to be claimed by token holders function payout() external payable atEitherStage(Stages.Active, Stages.Terminated) onlyCustodian returns (bool) { // calculate fee based on feeRate uint256 _fee = calculateFee(msg.value); // ensure the value is high enough for a fee to be claimed require(_fee > 0); // deduct fee from payout uint256 _payoutAmount = msg.value.sub(_fee); /* totalPerTokenPayout is a rate at which to payout based on token balance it is stored as * 1e18 in order to keep accuracy it is / 1e18 when used relating to actual Ξ values */ totalPerTokenPayout = totalPerTokenPayout .add(_payoutAmount .mul(1e18) .div(totalSupply_) ); // take remaining dust and send to owner rather than leave stuck in contract // should not be more than a few wei uint256 _delta = (_payoutAmount.mul(1e18) % totalSupply_).div(1e18); unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee).add(_delta); // let the world know that a payout has happened for this token emit PayoutEvent(_payoutAmount); return true; } // claim total Ξ claimable for sender based on token holdings at time of each payout function claim() external atEitherStage(Stages.Active, Stages.Terminated) returns (uint256) { /* pass true to currentPayout in order to get both: perToken payouts unclaimedPayoutTotals */ uint256 _payoutAmount = currentPayout(msg.sender, true); // check that there indeed is a pending payout for sender require(_payoutAmount > 0); // max out per token payout for sender in order to make payouts effectively // 0 for sender claimedPerTokenPayouts[msg.sender] = totalPerTokenPayout; // 0 out unclaimedPayoutTotals for user unclaimedPayoutTotals[msg.sender] = 0; // let the world know that a payout for sender has been claimed emit ClaimEvent(_payoutAmount); // transfer Ξ payable amount to sender msg.sender.transfer(_payoutAmount); return _payoutAmount; } // end payout related functions // start ERC20 overrides // same as ERC20 transfer other than settling unclaimed payouts function transfer ( address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(msg.sender, _to)); return super.transfer(_to, _value); } // same as ERC20 transfer other than settling unclaimed payouts function transferFrom ( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(_from, _to)); return super.transferFrom(_from, _to, _value); } // end ERC20 overrides // check if there is a way to get around gas issue when no gas limit calculated... // fallback function defaulting to buy function() public payable { buy(); } } // <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. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; // thrown in to make truffle happy contract OraclizeAPI { } contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public 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); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() 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) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } 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_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 pure 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 pure 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 pure 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 pure 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 pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure 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 pure 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 pure 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 pure 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 view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; 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 memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, 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(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(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] = byte(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) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; 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){ // 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); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) 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) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(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] == keccak256(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); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) 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 pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // 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> pragma solidity 0.4.23; import "./interfaces/IRegistry.sol"; import "./interfaces/IPoaManager.sol"; import "./interfaces/IPoaToken.sol"; contract CentralLogger { uint8 public constant version = 1; // registry instance to get other contract addresses IRegistry public registry; constructor( address _registryAddress ) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // only allow listed poa tokens to trigger events modifier onlyActivePoaToken() { require( IPoaManager( registry.getContractAddress("PoaManager") ).getTokenStatus(msg.sender) ); _; } // possible events from a PoaToken event StageEvent( address indexed tokenAddress, uint256 stage ); event BuyEvent( address indexed tokenAddress, address indexed buyer, uint256 amount ); event ProofOfCustodyUpdatedEvent( address indexed tokenAddress, string ipfsHash ); event PayoutEvent( address indexed tokenAddress, uint256 amount ); event ClaimEvent( address indexed tokenAddress, address indexed claimer, uint256 payout ); event TerminatedEvent( address indexed tokenAddress ); event CustodianChangedEvent( address indexed tokenAddress, address oldAddress, address newAddress ); event ReclaimEvent( address indexed tokenAddress, address indexed reclaimer, uint256 amount ); // possible events from PoaProxy event ProxyUpgradedEvent( address indexed tokenAddress, address upgradedFrom, address upgradedTo ); // event triggers for each event function logStageEvent( uint256 stage ) external onlyActivePoaToken { emit StageEvent(msg.sender, stage); } function logBuyEvent( address buyer, uint256 amount ) external onlyActivePoaToken { emit BuyEvent(msg.sender, buyer, amount); } function logProofOfCustodyUpdatedEvent() external onlyActivePoaToken { // easier to get the set ipfsHash from contract rather than send over string string memory _realIpfsHash = IPoaToken(msg.sender).proofOfCustody(); emit ProofOfCustodyUpdatedEvent( msg.sender, _realIpfsHash ); } function logPayoutEvent( uint256 _amount ) external onlyActivePoaToken { emit PayoutEvent( msg.sender, _amount ); } function logClaimEvent( address _claimer, uint256 _payout ) external onlyActivePoaToken { emit ClaimEvent( msg.sender, _claimer, _payout ); } function logTerminatedEvent() external onlyActivePoaToken { emit TerminatedEvent(msg.sender); } function logCustodianChangedEvent( address _oldAddress, address _newAddress ) external onlyActivePoaToken { emit CustodianChangedEvent( msg.sender, _oldAddress, _newAddress ); } function logReclaimEvent( address _reclaimer, uint256 _amount ) external onlyActivePoaToken { emit ReclaimEvent( msg.sender, _reclaimer, _amount ); } function logProxyUpgradedEvent( address _upgradedFrom, address _upgradedTo ) external onlyActivePoaToken { emit ProxyUpgradedEvent( msg.sender, _upgradedFrom, _upgradedTo ); } // keep money from entering this contract, unless selfdestruct of course :) function() public payable { revert(); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./interfaces/IAccessToken.sol"; import "./interfaces/IRegistry.sol"; contract FeeManager { using SafeMath for uint256; uint8 public constant version = 1; uint256 actRate = 1000; IRegistry private registry; constructor( address _registryAddress ) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } function weiToAct(uint256 _wei) view public returns (uint256) { return _wei.mul(actRate); } function actToWei(uint256 _act) view public returns (uint256) { return _act.div(actRate); } function payFee() public payable returns (bool) { IAccessToken act = IAccessToken( registry.getContractAddress("AccessToken") ); require(act.distribute(weiToAct(msg.value))); return true; } function claimFee( uint256 _value ) public returns (bool) { IAccessToken act = IAccessToken( registry.getContractAddress("AccessToken") ); require(act.burn(msg.sender, _value)); msg.sender.transfer(actToWei(_value)); return true; } // prevent anyone from sending funds other than selfdestructs of course :) function() public payable { revert(); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IBrickblockToken.sol"; import "./interfaces/IFeeManager.sol"; import "./interfaces/IAccessToken.sol"; contract BrickblockAccount is Ownable { uint8 public constant version = 1; uint256 public fundsReleaseBlock; IRegistry private registry; constructor ( address _registryAddress, uint256 _fundsReleaseBlock ) public { registry = IRegistry(_registryAddress); fundsReleaseBlock = _fundsReleaseBlock; } function pullFunds() external onlyOwner returns (bool) { IBrickblockToken bbk = IBrickblockToken( registry.getContractAddress("BrickblockToken") ); uint256 _companyFunds = bbk.balanceOf(address(bbk)); return bbk.transferFrom(address(bbk), this, _companyFunds); } function lockBBK ( uint256 _value ) external onlyOwner returns (bool) { IAccessToken act = IAccessToken( registry.getContractAddress("AccessToken") ); IBrickblockToken bbk = IBrickblockToken( registry.getContractAddress("BrickblockToken") ); require(bbk.approve(address(act), _value)); return act.lockBBK(_value); } function unlockBBK( uint256 _value ) external onlyOwner returns (bool) { IAccessToken act = IAccessToken( registry.getContractAddress("AccessToken") ); return act.unlockBBK(_value); } function claimFee( uint256 _value ) external onlyOwner returns (bool) { IFeeManager fmr = IFeeManager( registry.getContractAddress("FeeManager") ); return fmr.claimFee(_value); } // SWC-Unprotected Ether Withdrawal: L84-95 function withdrawEthFunds( address _address, uint256 _value ) external onlyOwner returns (bool) { require(address(this).balance > 0); _address.transfer(_value); return true; } function withdrawActFunds( address _address, uint256 _value ) external onlyOwner returns (bool) { IAccessToken act = IAccessToken( registry.getContractAddress("AccessToken") ); return act.transfer(_address, _value); } function withdrawBbkFunds( address _address, uint256 _value ) external onlyOwner returns (bool) { require(fundsReleaseBlock < block.number); IBrickblockToken bbk = IBrickblockToken( registry.getContractAddress("BrickblockToken") ); return bbk.transfer(_address, _value); } // ensure that we can be paid ether function() public payable {} } // SWC-Integer Overflow and Underflow: L2-308 pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IBrickblockToken.sol"; /* glossary: dividendParadigm: the way of handling dividends, and the per token data structures * totalLockedBBK * (totalMintedPerToken - distributedPerBBK) / 1e18 * this is the typical way of handling dividends. * per token data structures are stored * 1e18 (for more accuracy) * this works fine until BBK is locked or unlocked. * need to still know the amount they HAD locked before a change. * securedFundsParadigm solves this (read below) * when BBK is locked or unlocked, current funds for the relevant account are bumped to a new paradigm for balance tracking. * when bumped to new paradigm, dividendParadigm is essentially zeroed out by setting distributedPerBBK to totalMintedPerToken * (100 * (100 - 100) === 0) * all minting activity related balance increments are tracked through this securedFundsParadigm: funds that are bumped out of dividends during lock / unlock * securedTokenDistributions (mapping) * needed in order to track ACT balance after lock/unlockBBK * tracks funds that have been bumped from dividendParadigm * works as a regular balance (not per token) doubleEntryParadigm: taking care of transfer and transferFroms * receivedBalances[adr] - spentBalances[adr] * needed in order to track correct balance after transfer/transferFrom * receivedBalances used to increment any transfers to an account * increments balanceOf * needed to accurately track balanceOf after transfers and transferFroms * spentBalances * decrements balanceOf * needed to accurately track balanceOf after transfers and transferFroms dividendParadigm, securedFundsParadigm, doubleEntryParadigm combined * when all combined, should correctly: * show balance using balanceOf * balances is set to private (cannot guarantee accuracy of this) * balances not updated to correct values unless a transfer/transferFrom happens * dividendParadigm + securedFundsParadigm + doubleEntryParadigm * totalLockedBBK * (totalMintedPerToken - distributedPerBBK[adr]) / 1e18 + securedTokenDistributions[adr] + receivedBalances[adr] - spentBalances[adr] */ contract AccessToken is PausableToken { uint8 public constant version = 1; // instance of registry contract to get contract addresses IRegistry internal registry; string public constant name = "AccessToken"; string public constant symbol = "ACT"; uint8 public constant decimals = 18; // total amount of minted ACT that a single BBK token is entitled to uint256 internal totalMintedPerToken; // total amount of BBK that is currently locked into ACT contract // used to calculate how much to increment totalMintedPerToken during minting uint256 public totalLockedBBK; // used to save information on who has how much BBK locked in // used in dividendParadigm (see glossary) mapping(address => uint256) internal lockedBBK; // used to decrement totalMintedPerToken by amounts that have already been moved to securedTokenDistributions // used in dividendParadigm (see glossary) mapping(address => uint256) internal distributedPerBBK; // used to store ACT balances that have been moved off of: // dividendParadigm (see glossary) to securedFundsParadigm mapping(address => uint256) internal securedTokenDistributions; // ERC20 override... keep private and only use balanceOf instead mapping(address => uint256) internal balances; // mapping tracking incoming balances in order to have correct balanceOf // used in doubleEntryParadigm (see glossary) mapping(address => uint256) public receivedBalances; // mapping tracking outgoing balances in order to have correct balanceOf // used in doubleEntryParadigm (see glossary) mapping(address => uint256) public spentBalances; event MintEvent(uint256 amount); event BurnEvent(address indexed burner, uint256 value); event BBKLockedEvent( address indexed locker, uint256 lockedAmount, uint256 totalLockedAmount ); event BBKUnlockedEvent( address indexed locker, uint256 lockedAmount, uint256 totalLockedAmount ); modifier onlyContract(string _contractName) { require( msg.sender == registry.getContractAddress(_contractName) ); _; } constructor ( address _registryAddress ) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // check an address for amount of currently locked BBK // works similar to basic ERC20 balanceOf function lockedBbkOf( address _address ) external view returns (uint256) { return lockedBBK[_address]; } // transfers BBK from an account to this contract // uses settlePerTokenToSecured to move funds in dividendParadigm to securedFundsParadigm // keeps a record of transfers in lockedBBK (securedFundsParadigm) function lockBBK( uint256 _amount ) external returns (bool) { IBrickblockToken _bbk = IBrickblockToken( registry.getContractAddress("BrickblockToken") ); require(settlePerTokenToSecured(msg.sender)); lockedBBK[msg.sender] = lockedBBK[msg.sender].add(_amount); totalLockedBBK = totalLockedBBK.add(_amount); require(_bbk.transferFrom(msg.sender, this, _amount)); emit BBKLockedEvent(msg.sender, _amount, totalLockedBBK); return true; } // transfers BBK from this contract to an account // uses settlePerTokenToSecured to move funds in dividendParadigm to securedFundsParadigm // keeps a record of transfers in lockedBBK (securedFundsParadigm) function unlockBBK( uint256 _amount ) external returns (bool) { IBrickblockToken _bbk = IBrickblockToken( registry.getContractAddress("BrickblockToken") ); require(_amount <= lockedBBK[msg.sender]); require(settlePerTokenToSecured(msg.sender)); lockedBBK[msg.sender] = lockedBBK[msg.sender].sub(_amount); totalLockedBBK = totalLockedBBK.sub(_amount); require(_bbk.transfer(msg.sender, _amount)); emit BBKUnlockedEvent(msg.sender, _amount, totalLockedBBK); return true; } // distribute tokens to all BBK token holders // uses dividendParadigm to distribute ACT to lockedBBK holders // adds delta (integer division remainders) to owner securedFundsParadigm balance function distribute( uint256 _amount ) external onlyContract("FeeManager") returns (bool) { totalMintedPerToken = totalMintedPerToken .add( _amount .mul(1e18) .div(totalLockedBBK) ); uint256 _delta = (_amount.mul(1e18) % totalLockedBBK).div(1e18); securedTokenDistributions[owner] = securedTokenDistributions[owner].add(_delta); totalSupply_ = totalSupply_.add(_amount); emit MintEvent(_amount); return true; } // bumps dividendParadigm balance to securedFundsParadigm // ensures that BBK transfers will not affect ACT balance accrued function settlePerTokenToSecured( address _address ) private returns (bool) { securedTokenDistributions[_address] = securedTokenDistributions[_address] .add( lockedBBK[_address] .mul(totalMintedPerToken.sub(distributedPerBBK[_address])) .div(1e18) ); distributedPerBBK[_address] = totalMintedPerToken; return true; } // // start ERC20 overrides // // combines dividendParadigm, securedFundsParadigm, and doubleEntryParadigm // in order to give a correct balance function balanceOf( address _address ) public view returns (uint256) { return totalMintedPerToken == 0 ? 0 : lockedBBK[_address] .mul(totalMintedPerToken.sub(distributedPerBBK[_address])) .div(1e18) .add(securedTokenDistributions[_address]) .add(receivedBalances[_address]) .sub(spentBalances[_address]); } // does the same thing as ERC20 transfer but... // uses balanceOf rather than balances[adr] (balances is inaccurate see above) // sets correct values for doubleEntryParadigm (see glossary) function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balanceOf(msg.sender)); spentBalances[msg.sender] = spentBalances[msg.sender].add(_value); receivedBalances[_to] = receivedBalances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // does the same thing as ERC20 transferFrom but... // uses balanceOf rather than balances[adr] (balances is inaccurate see above) // sets correct values for doubleEntryParadigm (see glossary) function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balanceOf(_from)); require(_value <= allowed[_from][msg.sender]); spentBalances[_from] = spentBalances[_from].add(_value); receivedBalances[_to] = receivedBalances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } // // end ERC20 overrides // // callable only by FeeManager contract // burns tokens through incrementing spentBalances[adr] and decrements totalSupply // works with doubleEntryParadigm (see glossary) function burn( address _address, uint256 _value ) external onlyContract("FeeManager") returns (bool) { require(_value <= balanceOf(_address)); spentBalances[_address] = spentBalances[_address].add(_value); totalSupply_ = totalSupply_.sub(_value); emit BurnEvent(_address, _value); return true; } // prevent anyone from sending funds other than selfdestructs of course :) // SWC-Code With No Effects: L302-307 function() public payable { revert(); } } pragma solidity 0.4.23; contract Migrations { address public owner; uint public lastCompletedMigration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) restricted public { lastCompletedMigration = completed; } function upgrade(address newAddress) restricted public { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract Whitelist is Ownable { uint8 public constant version = 1; mapping (address => bool) public whitelisted; event WhitelistedEvent(address indexed account, bool isWhitelisted); function addAddress(address _address) public onlyOwner { require(whitelisted[_address] != true); whitelisted[_address] = true; emit WhitelistedEvent(_address, true); } function removeAddress(address _address) public onlyOwner { require(whitelisted[_address] != false); whitelisted[_address] = false; emit WhitelistedEvent(_address, false); } // prevent anyone from sending funds other than selfdestructs of course :) function() public payable { revert(); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; contract BrickblockToken is PausableToken { string public constant name = "BrickblockToken"; string public constant symbol = "BBK"; uint256 public constant initialSupply = 500 * (10 ** 6) * (10 ** uint256(decimals)); uint256 public companyTokens; uint256 public bonusTokens; uint8 public constant contributorsShare = 51; uint8 public constant companyShare = 35; uint8 public constant bonusShare = 14; uint8 public constant decimals = 18; address public bonusDistributionAddress; address public fountainContractAddress; bool public tokenSaleActive; bool public dead = false; event TokenSaleFinished ( uint256 totalSupply, uint256 distributedTokens, uint256 bonusTokens, uint256 companyTokens ); event Burn(address indexed burner, uint256 value); // This modifier is used in `distributeTokens()` and ensures that no more than 51% of the total supply can be distributed modifier supplyAvailable(uint256 _value) { uint256 _distributedTokens = initialSupply.sub(balances[this].add(bonusTokens)); uint256 _maxDistributedAmount = initialSupply.mul(contributorsShare).div(100); require(_distributedTokens.add(_value) <= _maxDistributedAmount); _; } constructor( address _bonusDistributionAddress ) public { require(_bonusDistributionAddress != address(0)); bonusTokens = initialSupply.mul(bonusShare).div(100); companyTokens = initialSupply.mul(companyShare).div(100); bonusDistributionAddress = _bonusDistributionAddress; totalSupply_ = initialSupply; balances[this] = initialSupply; emit Transfer(address(0), this, initialSupply); // distribute bonusTokens to bonusDistributionAddress balances[this] = balances[this].sub(bonusTokens); balances[bonusDistributionAddress] = balances[bonusDistributionAddress].add(bonusTokens); emit Transfer(this, bonusDistributionAddress, bonusTokens); // we need to start with trading paused to make sure that there can be no transfers while the token sale is still ongoing // we will unpause the contract manually after finalizing the token sale by calling `unpause()` which is a function inherited from PausableToken paused = true; tokenSaleActive = true; } // For worst case scenarios, e.g. when a vulnerability in this contract would be discovered and we would have to deploy a new contract // This is only for visibility purposes to publicly indicate that we consider this contract "dead" and don't intend to re-activate it ever again function toggleDead() external onlyOwner returns (bool) { dead = !dead; } // Helper function used in changeFountainContractAddress to ensure an address parameter is a contract and not an external address function isContract(address addr) private view returns (bool) { uint _size; assembly { _size := extcodesize(addr) } return _size > 0; } // Fountain contract address could change over time, so we need the ability to update its address function changeFountainContractAddress(address _newAddress) external onlyOwner returns (bool) { require(isContract(_newAddress)); require(_newAddress != address(this)); require(_newAddress != owner); fountainContractAddress = _newAddress; return true; } // Custom transfer function that enables us to distribute tokens while contract is paused. Cannot be used after end of token sale function distributeTokens(address _contributor, uint256 _value) external onlyOwner supplyAvailable(_value) returns (bool) { require(tokenSaleActive == true); require(_contributor != address(0)); require(_contributor != owner); balances[this] = balances[this].sub(_value); balances[_contributor] = balances[_contributor].add(_value); emit Transfer(this, _contributor, _value); return true; } // Distribute tokens reserved for partners and staff to a wallet owned by Brickblock function distributeBonusTokens(address _recipient, uint256 _value) external onlyOwner returns (bool) { require(_recipient != address(0)); require(_recipient != owner); balances[bonusDistributionAddress] = balances[bonusDistributionAddress].sub(_value); balances[_recipient] = balances[_recipient].add(_value); emit Transfer(bonusDistributionAddress, _recipient, _value); return true; } // Calculate the shares for company, bonus & contibutors based on the intial totalSupply of 500.000.000 tokens - not what is left over after burning function finalizeTokenSale() external onlyOwner returns (bool) { // ensure that sale is active. is set to false at the end. can only be performed once. require(tokenSaleActive == true); // ensure that fountainContractAddress has been set require(fountainContractAddress != address(0)); // calculate new total supply. need to do this in two steps in order to have accurate totalSupply due to integer division uint256 _distributedTokens = initialSupply.sub(balances[this].add(bonusTokens)); uint256 _newTotalSupply = _distributedTokens.add(bonusTokens.add(companyTokens)); // unpurchased amount of tokens which will be burned uint256 _burnAmount = totalSupply_.sub(_newTotalSupply); // leave remaining balance for company to be claimed at later date balances[this] = balances[this].sub(_burnAmount); emit Burn(this, _burnAmount); // allow our fountain contract to transfer the company tokens to itself allowed[this][fountainContractAddress] = companyTokens; emit Approval(this, fountainContractAddress, companyTokens); // set new totalSupply totalSupply_ = _newTotalSupply; // prevent this function from ever running again after finalizing the token sale tokenSaleActive = false; // dispatch event showing sale is finished emit TokenSaleFinished( totalSupply_, _distributedTokens, bonusTokens, companyTokens ); // everything went well return true return true; } // fallback function - do not allow any eth transfers to this contract function() external { revert(); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/token/ERC20/PausableToken.sol"; /* solium-disable security/no-block-members */ /* solium-disable security/no-low-level-calls */ contract PoaToken is PausableToken { uint256 public constant version = 1; // instance of registry to call other contracts address public registry; // ERC20 name of the token string public name; // ERC20 symbol string public symbol; // ipfs hash for proof of custody by custodian string public proofOfCustody; // fiat currency symbol used to get rate string public fiatCurrency; // broker who is selling property, whitelisted on PoaManager address public broker; // custodian in charge of taking care of asset and payouts address public custodian; // ERC0 decimals uint256 public constant decimals = 18; // ‰ permille NOT percent: fee paid to BBK holders through ACT uint256 public constant feeRate = 5; // used to check when contract should move from PreFunding to Funding stage uint256 public startTime; // amount of seconds until moving to Failed from // Funding stage after startTime uint256 public fundingTimeout; // amount of seconds until moving to Failed from // Pending stage after startTime + fundingTimeout uint256 public activationTimeout; // amount needed before moving to pending calculated in fiat uint256 public fundingGoalInCents; // the total per token payout rate: accumulates as payouts are received uint256 public totalPerTokenPayout; // used to keep track of of actual fundedAmount in eth uint256 public fundedAmountInWei; // used to enable/disable whitelist required transfers/transferFroms bool public whitelistTransfers; // used to deduct already claimed payouts on a per token basis mapping(address => uint256) public claimedPerTokenPayouts; // fallback for when a transfer happens with payouts remaining mapping(address => uint256) public unclaimedPayoutTotals; // needs to be used due to tokens not directly correlating to fundingGoal // due to fluctuating fiat rates mapping(address => uint256) public investmentAmountPerUserInWei; // used to calculate balanceOf by deducting spent balances mapping(address => uint256) public spentBalances; // used to calculate balanceOf by adding received balances mapping(address => uint256) public receivedBalances; // hide balances to ensure that only balanceOf is being used mapping(address => uint256) private balances; enum Stages { PreFunding, Funding, Pending, Failed, Active, Terminated } Stages public stage = Stages.PreFunding; event StageEvent(Stages stage); event BuyEvent(address indexed buyer, uint256 amount); event PayoutEvent(uint256 amount); event ClaimEvent(address indexed claimer, uint256 payout); event TerminatedEvent(); event ProofOfCustodyUpdatedEvent(string ipfsHash); event ReclaimEvent(address indexed reclaimer, uint256 amount); event CustodianChangedEvent(address indexed oldAddress, address indexed newAddress); modifier eitherCustodianOrOwner() { owner = getContractAddress("PoaManager"); require( msg.sender == custodian || msg.sender == owner ); _; } modifier onlyOwner() { owner = getContractAddress("PoaManager"); require(msg.sender == owner); _; } modifier onlyCustodian() { require(msg.sender == custodian); _; } modifier atStage(Stages _stage) { require(stage == _stage); _; } modifier atEitherStage(Stages _stage, Stages _orStage) { require(stage == _stage || stage == _orStage); _; } modifier isBuyWhitelisted() { require(checkIsWhitelisted(msg.sender)); _; } modifier isTransferWhitelisted(address _to) { if (whitelistTransfers) { require(checkIsWhitelisted(_to)); } _; } modifier checkTimeout() { uint256 fundingTimeoutDeadline = startTime.add(fundingTimeout); uint256 activationTimeoutDeadline = startTime .add(fundingTimeout) .add(activationTimeout); if ( (stage == Stages.Funding && block.timestamp >= fundingTimeoutDeadline) || (stage == Stages.Pending && block.timestamp >= activationTimeoutDeadline) ) { enterStage(Stages.Failed); } _; } modifier validIpfs(string _ipfsHash) { // check that the most common hashing algo is used sha256 // and that the length is correct. In theory it could be different // but use of this functionality is limited to only custodian // so this validation should suffice require(bytes(_ipfsHash).length == 46); require(bytes(_ipfsHash)[0] == 0x51); require(bytes(_ipfsHash)[1] == 0x6D); require(keccak256(bytes(_ipfsHash)) != keccak256(bytes(proofOfCustody))); _; } // token totalSupply must be more than fundingGoalInCents! function setupContract ( string _name, string _symbol, // fiat symbol used in ExchangeRates string _fiatCurrency, address _broker, address _custodian, uint256 _totalSupply, // given as unix time (seconds since 01.01.1970) uint256 _startTime, // given as seconds uint256 _fundingTimeout, uint256 _activationTimeout, // given as fiat cents uint256 _fundingGoalInCents ) public returns (bool) { // ensure that setup has not been called require(startTime == 0); // ensure all strings are valid require(bytes(_name).length >= 3); require(bytes(_symbol).length >= 3); require(bytes(_fiatCurrency).length >= 3); // ensure all addresses given are valid require(_broker != address(0)); require(_custodian != address(0)); // ensure totalSupply is at least 1 whole token require(_totalSupply >= 1e18); require(_totalSupply > fundingGoalInCents); // ensure all uints are valid require(_startTime > block.timestamp); // ensure that fundingTimeout is at least 24 hours require(_fundingTimeout >= 60 * 60 * 24); // ensure that activationTimeout is at least 7 days require(_activationTimeout >= 60 * 60 * 24 * 7); require(_fundingGoalInCents > 0); // assign strings name = _name; symbol = _symbol; fiatCurrency = _fiatCurrency; // assign addresses broker = _broker; custodian = _custodian; // assign times startTime = _startTime; fundingTimeout = _fundingTimeout; activationTimeout = _activationTimeout; fundingGoalInCents = _fundingGoalInCents; totalSupply_ = _totalSupply; // assign bools paused = true; whitelistTransfers = false; // get registry address from PoaManager which should be msg.sender // need to use assembly here due to gas limitations address _tempReg; bytes4 _sig = bytes4(keccak256("registry()")); assembly { let _call := mload(0x40) // set _call to free memory pointer mstore(_call, _sig) // store _sig at _call pointer // staticcall(g, a, in, insize, out, outsize) => 0 on error 1 on success let success := staticcall( gas, // g = gas: whatever was passed already caller, // a = address: caller = msg.sender _call, // in = mem in mem[in..(in+insize): set to _call pointer 0x04, // insize = mem insize mem[in..(in+insize): size of _sig (bytes4) = 0x04 _call, // out = mem out mem[out..(out+outsize): output assigned to this storage address 0x20 // outsize = mem outsize mem[out..(out+outsize): output should be 32byte slot (address size = 0x14 < slot size 0x20) ) // revert if not successful if iszero(success) { revert(0, 0) } _tempReg := mload(_call) // assign result in mem pointer to previously declared _tempReg mstore(0x40, add(_call, 0x20)) // advance free memory pointer by largest _call size } // assign _tempReg gotten from assembly call to PoaManager.registry() to registry registry = _tempReg; owner = getContractAddress("PoaManager"); // run getRate once in order to see if rate is initialized, throws if not require(getFiatRate() > 0); return true; } // // start utility functions // // gets a given contract address by bytes32 saving gas function getContractAddress( string _name ) public view returns (address _contractAddress) { bytes4 _sig = bytes4(keccak256("getContractAddress32(bytes32)")); bytes32 _name32 = keccak256(_name); assembly { let _call := mload(0x40) // set _call to free memory pointer mstore(_call, _sig) // store _sig at _call pointer mstore(add(_call, 0x04), _name32) // store _name32 at _call offset by 4 bytes for pre-existing _sig // staticcall(g, a, in, insize, out, outsize) => 0 on error 1 on success let success := staticcall( gas, // g = gas: whatever was passed already sload(registry_slot), // a = address: address in storage _call, // in = mem in mem[in..(in+insize): set to free memory pointer 0x24, // insize = mem insize mem[in..(in+insize): size of sig (bytes4) + bytes32 = 0x24 _call, // out = mem out mem[out..(out+outsize): output assigned to this storage address 0x20 // outsize = mem outsize mem[out..(out+outsize): output should be 32byte slot (address size = 0x14 < slot size 0x20) ) // revert if not successful if iszero(success) { revert(0, 0) } _contractAddress := mload(_call) // assign result to return value mstore(0x40, add(_call, 0x24)) // advance free memory pointer by largest _call size } } // gas saving call to get fiat rate without interface function getFiatRate() public view returns (uint256 _fiatRate) { bytes4 _sig = bytes4(keccak256("getRate32(bytes32)")); address _exchangeRates = getContractAddress("ExchangeRates"); bytes32 _fiatCurrency = keccak256(fiatCurrency); assembly { let _call := mload(0x40) // set _call to free memory pointer mstore(_call, _sig) // store _sig at _call pointer mstore(add(_call, 0x04), _fiatCurrency) // store _fiatCurrency at _call offset by 4 bytes for pre-existing _sig // staticcall(g, a, in, insize, out, outsize) => 0 on error 1 on success let success := staticcall( gas, // g = gas: whatever was passed already _exchangeRates, // a = address: address from getContractAddress _call, // in = mem in mem[in..(in+insize): set to free memory pointer 0x24, // insize = mem insize mem[in..(in+insize): size of sig (bytes4) + bytes32 = 0x24 _call, // out = mem out mem[out..(out+outsize): output assigned to this storage address 0x20 // outsize = mem outsize mem[out..(out+outsize): output should be 32byte slot (uint256 size = 0x20 = slot size 0x20) ) // revert if not successful if iszero(success) { revert(0, 0) } _fiatRate := mload(_call) // assign result to return value mstore(0x40, add(_call, 0x24)) // advance free memory pointer by largest _call size } } // use assembly in order to avoid gas usage which is too high // used to check if whitelisted at Whitelist contract function checkIsWhitelisted(address _address) public view returns (bool _isWhitelisted) { bytes4 _sig = bytes4(keccak256("whitelisted(address)")); address _whitelistContract = getContractAddress("Whitelist"); address _arg = _address; assembly { let _call := mload(0x40) // set _call to free memory pointer mstore(_call, _sig) // store _sig at _call pointer mstore(add(_call, 0x04), _arg) // store _arg at _call offset by 4 bytes for pre-existing _sig // staticcall(g, a, in, insize, out, outsize) => 0 on error 1 on success let success := staticcall( gas, // g = gas: whatever was passed already _whitelistContract, // a = address: _whitelist address assigned from getContractAddress() _call, // in = mem in mem[in..(in+insize): set to _call pointer 0x24, // insize = mem insize mem[in..(in+insize): size of sig (bytes4) + bytes32 = 0x24 _call, // out = mem out mem[out..(out+outsize): output assigned to this storage address 0x20 // outsize = mem outsize mem[out..(out+outsize): output should be 32byte slot (bool size = 0x01 < slot size 0x20) ) // revert if not successful if iszero(success) { revert(0, 0) } _isWhitelisted := mload(_call) // assign result to returned value mstore(0x40, add(_call, 0x24)) // advance free memory pointer by largest _call size } } // returns fiat value in cents of given wei amount function weiToFiatCents(uint256 _wei) public view returns (uint256) { // get eth to fiat rate in cents from ExchangeRates return _wei.mul(getFiatRate()).div(1e18); } // returns wei value from fiat cents function fiatCentsToWei(uint256 _cents) public view returns (uint256) { return _cents.mul(1e18).div(getFiatRate()); } // get funded amount in cents function fundedAmountInCents() public view returns (uint256) { return weiToFiatCents(fundedAmountInWei); } // get fundingGoal in wei function fundingGoalInWei() public view returns (uint256) { return fiatCentsToWei(fundingGoalInCents); } // public utility function to allow checking of required fee for a given amount function calculateFee(uint256 _value) public pure returns (uint256) { // divide by 1000 because feeRate permille return feeRate.mul(_value).div(1000); } // pay fee to FeeManager function payFee(uint256 _value) private returns (bool) { require( // solium-disable-next-line security/no-call-value getContractAddress("FeeManager") .call.value(_value)(bytes4(keccak256("payFee()"))) ); } // // end utility functions // // pause override function unpause() public onlyOwner whenPaused { // only allow unpausing when in Active stage require(stage == Stages.Active); return super.unpause(); } // enables whitelisted transfers/transferFroms function toggleWhitelistTransfers() public onlyOwner returns (bool) { whitelistTransfers = !whitelistTransfers; return whitelistTransfers; } // // start lifecycle functions // // used to enter a new stage of the contract function enterStage(Stages _stage) private { stage = _stage; emit StageEvent(_stage); getContractAddress("Logger").call( bytes4(keccak256("logStageEvent(uint256)")), _stage ); } // used to start the sale as long as startTime has passed function startSale() public atStage(Stages.PreFunding) returns (bool) { require(block.timestamp >= startTime); enterStage(Stages.Funding); return true; } // buy tokens function buy() public payable checkTimeout atStage(Stages.Funding) isBuyWhitelisted returns (bool) { // prevent case where buying after reaching fundingGoal results in buyer // earning money on a buy if (weiToFiatCents(fundedAmountInWei) > fundingGoalInCents) { enterStage(Stages.Pending); if (msg.value > 0) { msg.sender.transfer(msg.value); } return false; } // get current funded amount + sent value in cents // with most current rate available uint256 _currentFundedCents = weiToFiatCents(fundedAmountInWei.add(msg.value)); // check if balance has met funding goal to move on to Pending if (_currentFundedCents < fundingGoalInCents) { // give a range due to fun fun integer division if (fundingGoalInCents.sub(_currentFundedCents) > 1) { // continue sale if more than 1 cent from goal in fiat return buyAndContinueFunding(msg.value); } else { // finish sale if within 1 cent of goal in fiat // no refunds for overpayment should be given return buyAndEndFunding(false); } } else { // finish sale, we are now over the funding goal // a refund for overpaid amount should be given return buyAndEndFunding(true); } } // buy and continue funding process (when funding goal not met) function buyAndContinueFunding(uint256 _payAmount) private returns (bool) { // save this for later in case needing to reclaim investmentAmountPerUserInWei[msg.sender] = investmentAmountPerUserInWei[msg.sender] .add(_payAmount); // increment the funded amount fundedAmountInWei = fundedAmountInWei.add(_payAmount); emit BuyEvent(msg.sender, _payAmount); getContractAddress("Logger").call( bytes4(keccak256("logBuyEvent(address,uint256)")), msg.sender, _payAmount ); return true; } // buy and finish funding process (when funding goal met) function buyAndEndFunding(bool _shouldRefund) private returns (bool) { // let the world know that the token is in Pending Stage enterStage(Stages.Pending); uint256 _refundAmount = _shouldRefund ? fundedAmountInWei.add(msg.value).sub(fiatCentsToWei(fundingGoalInCents)) : 0; // transfer refund amount back to user msg.sender.transfer(_refundAmount); // actual Ξ amount to buy after refund uint256 _payAmount = msg.value.sub(_refundAmount); buyAndContinueFunding(_payAmount); return true; } // used to manually set Stage to Failed when no users have bought any tokens // if no buy()s occurred before fundingTimeoutBlock token would be stuck in Funding // can also be used when activate is not called by custodian within activationTimeout // lastly can also be used when no one else has called reclaim. function setFailed() external atEitherStage(Stages.Funding, Stages.Pending) checkTimeout returns (bool) { if (stage != Stages.Failed) { revert(); } return true; } // function to change custodianship of poa function changeCustodianAddress(address _newCustodian) public onlyCustodian returns (bool) { require(_newCustodian != address(0)); require(_newCustodian != custodian); address _oldCustodian = custodian; custodian = _newCustodian; emit CustodianChangedEvent(_oldCustodian, _newCustodian); getContractAddress("Logger").call( bytes4(keccak256("logCustodianChangedEvent(address,address)")), _oldCustodian, _newCustodian ); return true; } // activate token with proofOfCustody fee is taken from contract balance // brokers must work this into their funding goals function activate(string _ipfsHash) external checkTimeout onlyCustodian atStage(Stages.Pending) validIpfs(_ipfsHash) returns (bool) { // calculate company fee charged for activation uint256 _fee = calculateFee(address(this).balance); // if activated and fee paid: put in Active stage enterStage(Stages.Active); // fee sent to FeeManager where fee gets // turned into ACT for lockedBBK holders payFee(_fee); proofOfCustody = _ipfsHash; // event showing that proofOfCustody has been updated. emit ProofOfCustodyUpdatedEvent(_ipfsHash); getContractAddress("Logger") .call(bytes4(keccak256("logProofOfCustodyUpdatedEvent()"))); // balance of contract (fundingGoalInCents) set to claimable by broker. // can now be claimed by broker via claim function // should only be buy()s - fee. this ensures buy() dust is cleared unclaimedPayoutTotals[broker] = unclaimedPayoutTotals[broker] .add(address(this).balance); // allow trading of tokens paused = false; // let world know that this token can now be traded. emit Unpause(); return true; } // used when property no longer exists etc. allows for winding down via payouts // can no longer be traded after function is run function terminate() external eitherCustodianOrOwner atStage(Stages.Active) returns (bool) { // set Stage to terminated enterStage(Stages.Terminated); // pause. Cannot be unpaused now that in Stages.Terminated paused = true; // let the world know this token is in Terminated Stage emit TerminatedEvent(); getContractAddress("Logger") .call(bytes4(keccak256("logTerminatedEvent()"))); return true; } // // end lifecycle functions // // // start payout related functions // // get current payout for perTokenPayout and unclaimed function currentPayout(address _address, bool _includeUnclaimed) public view returns (uint256) { /* need to check if there have been no payouts safe math will throw otherwise due to dividing 0 The below variable represents the total payout from the per token rate pattern it uses this funky naming pattern in order to differentiate from the unclaimedPayoutTotals which means something very different. */ uint256 _totalPerTokenUnclaimedConverted = totalPerTokenPayout == 0 ? 0 : balanceOf(_address) .mul(totalPerTokenPayout.sub(claimedPerTokenPayouts[_address])) .div(1e18); /* balances may be bumped into unclaimedPayoutTotals in order to maintain balance tracking accross token transfers perToken payout rates are stored * 1e18 in order to be kept accurate perToken payout is / 1e18 at time of usage for actual Ξ balances unclaimedPayoutTotals are stored as actual Ξ value no need for rate * balance */ return _includeUnclaimed ? _totalPerTokenUnclaimedConverted.add(unclaimedPayoutTotals[_address]) : _totalPerTokenUnclaimedConverted; } // settle up perToken balances and move into unclaimedPayoutTotals in order // to ensure that token transfers will not result in inaccurate balances function settleUnclaimedPerTokenPayouts(address _from, address _to) private returns (bool) { // add perToken balance to unclaimedPayoutTotals which will not be affected by transfers unclaimedPayoutTotals[_from] = unclaimedPayoutTotals[_from].add(currentPayout(_from, false)); // max out claimedPerTokenPayouts in order to effectively make perToken balance 0 claimedPerTokenPayouts[_from] = totalPerTokenPayout; // same as above for to unclaimedPayoutTotals[_to] = unclaimedPayoutTotals[_to].add(currentPayout(_to, false)); // same as above for to claimedPerTokenPayouts[_to] = totalPerTokenPayout; return true; } // reclaim Ξ for sender if fundingGoalInCents is not met within fundingTimeoutBlock function reclaim() external checkTimeout atStage(Stages.Failed) returns (bool) { totalSupply_ = 0; uint256 _refundAmount = investmentAmountPerUserInWei[msg.sender]; investmentAmountPerUserInWei[msg.sender] = 0; require(_refundAmount > 0); fundedAmountInWei = fundedAmountInWei.sub(_refundAmount); msg.sender.transfer(_refundAmount); emit ReclaimEvent(msg.sender, _refundAmount); getContractAddress("Logger").call( bytes4(keccak256("logReclaimEvent(address,uint256)")), msg.sender, _refundAmount ); return true; } // send Ξ to contract to be claimed by token holders function payout() external payable atEitherStage(Stages.Active, Stages.Terminated) onlyCustodian returns (bool) { // calculate fee based on feeRate uint256 _fee = calculateFee(msg.value); // ensure the value is high enough for a fee to be claimed require(_fee > 0); // deduct fee from payout uint256 _payoutAmount = msg.value.sub(_fee); /* totalPerTokenPayout is a rate at which to payout based on token balance it is stored as * 1e18 in order to keep accuracy it is / 1e18 when used relating to actual Ξ values */ totalPerTokenPayout = totalPerTokenPayout .add(_payoutAmount .mul(1e18) .div(totalSupply()) ); // take remaining dust and send to feeManager rather than leave stuck in // contract. should not be more than a few wei uint256 _delta = (_payoutAmount.mul(1e18) % totalSupply()).div(1e18); // pay fee along with any dust to FeeManager payFee(_fee.add(_delta)); // let the world know that a payout has happened for this token emit PayoutEvent(_payoutAmount.sub(_delta)); getContractAddress("Logger").call( bytes4(keccak256("logPayoutEvent(uint256)")), _payoutAmount.sub(_delta) ); return true; } // claim total Ξ claimable for sender based on token holdings at time of each payout function claim() external atEitherStage(Stages.Active, Stages.Terminated) returns (uint256) { /* pass true to currentPayout in order to get both: perToken payouts unclaimedPayoutTotals */ uint256 _payoutAmount = currentPayout(msg.sender, true); // check that there indeed is a pending payout for sender require(_payoutAmount > 0); // max out per token payout for sender in order to make payouts effectively // 0 for sender claimedPerTokenPayouts[msg.sender] = totalPerTokenPayout; // 0 out unclaimedPayoutTotals for user unclaimedPayoutTotals[msg.sender] = 0; // transfer Ξ payable amount to sender msg.sender.transfer(_payoutAmount); // let the world know that a payout for sender has been claimed emit ClaimEvent(msg.sender, _payoutAmount); getContractAddress("Logger").call( bytes4(keccak256("logClaimEvent(address,uint256)")), msg.sender, _payoutAmount ); return _payoutAmount; } // allow ipfs hash to be updated when audit etc occurs function updateProofOfCustody(string _ipfsHash) external atEitherStage(Stages.Active, Stages.Terminated) onlyCustodian validIpfs(_ipfsHash) returns (bool) { proofOfCustody = _ipfsHash; emit ProofOfCustodyUpdatedEvent(_ipfsHash); getContractAddress("Logger").call( bytes4(keccak256("logProofOfCustodyUpdatedEvent(string)")), _ipfsHash ); return true; } // // end payout related functions // // // start ERC20 overrides // // used for calculating starting balance once activated function startingBalance(address _address) private view returns (uint256) { return uint256(stage) > 3 ? investmentAmountPerUserInWei[_address] .mul(totalSupply()) .div(fundedAmountInWei) : 0; } // ERC20 override uses NoobCoin pattern function balanceOf(address _address) public view returns (uint256) { return startingBalance(_address) .add(receivedBalances[_address]) .sub(spentBalances[_address]); } /* ERC20 transfer override: uses NoobCoin pattern combined with settling payout balances each time run */ function transfer ( address _to, uint256 _value ) public whenNotPaused isTransferWhitelisted(_to) isTransferWhitelisted(msg.sender) returns (bool) { // move perToken payout balance to unclaimedPayoutTotals settleUnclaimedPerTokenPayouts(msg.sender, _to); require(_to != address(0)); require(_value <= balanceOf(msg.sender)); spentBalances[msg.sender] = spentBalances[msg.sender].add(_value); receivedBalances[_to] = receivedBalances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /* ERC20 transfer override: uses NoobCoin pattern combined with settling payout balances each time run */ function transferFrom ( address _from, address _to, uint256 _value ) public whenNotPaused isTransferWhitelisted(_to) isTransferWhitelisted(_from) returns (bool) { // move perToken payout balance to unclaimedPayoutTotals settleUnclaimedPerTokenPayouts(_from, _to); require(_to != address(0)); require(_value <= balanceOf(_from)); require(_value <= allowed[_from][msg.sender]); spentBalances[_from] = spentBalances[_from].add(_value); receivedBalances[_to] = receivedBalances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } // // end ERC20 overrides // // prevent anyone from sending funds other than selfdestructs of course :) function() public payable { revert(); } } pragma solidity 0.4.23; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract ContractRegistry is Ownable { uint8 public constant version = 1; address public owner; mapping (bytes32 => address) private contractAddresses; event UpdateContractEvent(string name, address indexed contractAddress); function updateContractAddress(string _name, address _address) public onlyOwner returns (address) { contractAddresses[keccak256(_name)] = _address; emit UpdateContractEvent(_name, _address); } function getContractAddress(string _name) public view returns (address) { require(contractAddresses[keccak256(_name)] != address(0)); return contractAddresses[keccak256(_name)]; } function getContractAddress32(bytes32 _name32) public view returns (address) { require(contractAddresses[_name32] != address(0)); return contractAddresses[_name32]; } // prevent anyone from sending funds other than selfdestructs of course :) function() public payable { revert(); } } pragma solidity 0.4.23; /* * This is an example of how we would upgrade the AccessToken contract if we had to. * Instead of doing a full data migration from ACTv1 to ACTv2 we could make * use of inheritance and just access the state on the old contract. * * NOTE: This should probably only be done once because every subsequent * update will get more confusing. If we really have to update the ACT * contract we should investigate then whether we should just use * the same proxy pattern we are using for the POA contract. */ import "./AccessToken.sol"; contract AccessTokenUpgradeExample is AccessToken { constructor(address _registry) AccessToken(_registry) {} function balanceOf( address _address ) public view returns (uint256) { return totalMintedPerToken == 0 ? 0 : AccessToken( registry.getContractAddress("AccessTokenOld") ).balanceOf(_address) .add(lockedBBK[_address]) .mul(totalMintedPerToken.sub(distributedPerBBK[_address])) .div(1e18) .add(securedTokenDistributions[_address]) .add(receivedBalances[_address]) .sub(spentBalances[_address]); } } pragma solidity 0.4.23; import "./OraclizeAPI.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IExchangeRates.sol"; contract ExchangeRateProvider is usingOraclize { uint8 public constant version = 1; IRegistry private registry; // ensure that only the oracle or ExchangeRates contract are allowed modifier onlyAllowed() { require( msg.sender == registry.getContractAddress("ExchangeRates") || msg.sender == oraclize_cbAddress() ); _; } modifier onlyExchangeRates() { require(msg.sender == registry.getContractAddress("ExchangeRates")); _; } constructor( address _registryAddress ) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // set gas price used for oraclize callbacks function setCallbackGasPrice(uint256 _gasPrice) onlyExchangeRates external returns (bool) { oraclize_setCustomGasPrice(_gasPrice); return true; } // send query to oraclize, results sent to __callback // money can be forwarded on from ExchangeRates // current implementation requires > 1e5 & < 2e5 callbackGasLimit function sendQuery( string _queryString, // SWC-Code With No Effects: L54-55 uint256 _callInterval, uint256 _callbackGasLimit, string _queryType ) onlyAllowed payable public returns (bool) { // check that there is enough money to make the query if (oraclize_getPrice("URL") > address(this).balance) { setQueryId(0x0, ""); return false; } else { // make query based on currencySettings for a given _queryType bytes32 _queryId = oraclize_query( _callInterval, "URL", _queryString, _callbackGasLimit ); // set the queryId on ExchangeRates so that it knows about it and can // accept it when __callback tries to set the rate setQueryId(_queryId, _queryType); return true; } } // set queryIds on ExchangeRates for later validation when __callback happens function setQueryId(bytes32 _identifier, string _queryType) private returns (bool) { // get current address of ExchangeRates IExchangeRates _exchangeRates = IExchangeRates( registry.getContractAddress("ExchangeRates") ); // run setQueryId on ExchangeRates _exchangeRates.setQueryId(_identifier, _queryType); } // callback function for returned results of oraclize call // solium-disable-next-line mixedcase function __callback(bytes32 _queryId, string _result) public { // make sure that the caller is oraclize require(msg.sender == oraclize_cbAddress()); // get currency address of ContractRegistry IExchangeRates _exchangeRates = IExchangeRates( registry.getContractAddress("ExchangeRates") ); // get settings data from ExchangeRates bool _ratesActive = _exchangeRates.ratesActive(); uint256 _callInterval; uint256 _callbackGasLimit; string memory _queryString; string memory _queryType = _exchangeRates.queryTypes(_queryId); ( _callInterval, _callbackGasLimit, _queryString ) = _exchangeRates.getCurrencySettings(_queryType); // set rate on ExchangeRates contract giving queryId for validation // rate is set in cents api returns float string which is parsed as int require(_exchangeRates.setRate(_queryId, parseInt(_result, 2))); // check if call interval has been set and that _ratesActive is still true // if so, call again with the interval if (_callInterval > 0 && _ratesActive) { sendQuery( _queryString, _callInterval, _callbackGasLimit, _queryType ); } } // used in case we need to get money out of the contract before replacing function selfDestruct(address _address) onlyExchangeRates public { selfdestruct(_address); } // ensure that we can fund queries by paying the contract function() payable public {} }
Brickblock_[Phase_2]_Audit-final.md 9/20/2018 1 / 22 Brickblock [Phase 2] Audit 1 Summary 1.1 Audit Dashboard 1.2 Audit Goals 1.3 System Overview 1.4 Key Observations/Recommendations 2 Issue Overview 3 Issue Detail 3.1 Unnecessary complexity in toXLengthString functions in PoaCommon 3.2 No plan for how a physical tokenized asset would handle a chain split 3.3 Usage of random storage slots in the Proxy adds too much complexity 3.4 Unnecessary usage of low-level .call() method 3.5 Withdraw method does not check if balance is sufficient for the withdrawal 3.6 Can lock and unlock 0 BBK in AccessToken 3.7 Precision in percent function can overflow 3.8 Transaction order dependence issue in ExchangeRates 3.9 Non-optimal ordering of instructions in PoaProxy and PoaToken fallback functions 3.10 ExchangeRateProvider 's callback check for access control is non-optimal 3.11 Inaccurate specification comment for setFailed() method in PoaCrowdsale 3.12 Unnecessary fallback functions to refuse payments 3.13 Comment about upgrade path is incorrect 3.14 buyAndEndFunding ends by calling buyAndContinueFunding 3.15 Unused variable has no dummy check in ExchangeRateProviderStub 3.16 FeeManager open-by-default design might introduce flaws in the token economy 3.17 Unnecessary refund action in PoaCrowdsale 3.18 this should be explicitly typecast to address 3.19 Blocking conditions in buyFiat 3.20 Use of ever-growing unsigned integers in PoaToken is dangerous 3.21 Use of ever-growing unsigned integers in AccessToken is dangerous 3.22 Non-optimal stage checking condition in PoaToken 3.23 Unnecessary static call to get POA Manager's address in POA proxy 3.24 Unnecessary static call to fetch registry's address in POA Proxy 3.25 Contradicting comment on POAManager 3.26 Inconsistent type used for decimals 3.27 Inconsistent event naming 3.28 Incorrect name of parameter in BBKUnlockedEvent 3.29 Usage of EntityState for both brokers and tokens in PoaManager is an anti-separation- of-concerns pattern 4 Tool based analysis 4.1 Mythril 4.2 Sūrya 4.3 Odyssey 5 Test Coverage Measurement Appendix 1 - File HashesBrickblock_[Phase_2]_Audit-final.md 9/20/2018 2 / 22 Appendix 2 - Severity A.2.1 - Minor A.2.2 - Medium A.2.3 - Major A.2.4 - Critical Appendix 3 - Disclosure 1 Summary ConsenSys Diligence conducted a security audit on Brickblock's system of smart contracts for tokenizing real-world assets with a specific focus on real estate. The scope of the audit included Brickblock's upgradable system of smart contracts, encompassing three tokens, a pricing oracle, and other utilities, but with the understanding that one of the contracts, POAManager, was not frozen and would undergo further development. The objective of the audit was to discover issues that could threaten the funds held in or behaviour of the Brickblock system, including its future upgradability. Final Revision Summary There were no critical or major issues with the contracts under review. All medium and minor issues have been diligently addressed by Brickblock through either code changes or detailed explanations that can be found in section 1.5 of this report. 1.1 Audit Dashboard Audit Details Project Name: Brickblock Audit Client Name: Brickblock Client Contact: Philip Paetz, Cody Lamson Auditors: Gonçalo Sá, Sarah Friend GitHub : https://github.com/brickblock-io/smart-contracts Languages: Solidity, Solidity Assembly, JavaScript Date: 8th June - Number of issues per severity 25 4 0 0 1.2 Audit Goals The focus of the audit was to verify that the smart contract system is secure, resilient and working according to its specifications. The audit activities can be grouped in the following three categories:Brickblock_[Phase_2]_Audit-final.md 9/20/2018 3 / 22Security: Identifying security related issues within each contract and within the system of contracts. Sound Architecture: Evaluation of the architecture of this system through the lens of established smart contract best practices and general software best practices. Code Correctness and Quality: A full review of the contract source code. The primary areas of focus include: Correctness Readability Sections of code with high complexity Improving scalability Quantity and quality of test coverage 1.3 System Overview Documentation The following documentation was available to the audit team: The README which describes how to work with the contracts. The Ecosystem documentation gives an architectural overview and detailed information about the individual contracts. The Tests against Geth doc which explains how to run the tests against geth and not truffle's ganache . Scope The audit focus was on the smart contract files, and test suites found in the following repositories: Repository Commit hash Commit date brickblock-io/smart-contractsf1f5b04722b9569e1d4c0b62ac4c490c0a785fd88th June 2018 The full list of smart contracts in scope of the audit can be found in chapter Appendix 1 - File Hashes. Design Brickblock is a system for managing the tokenization of assets, as well as custodianship/brokerage of and investment in those assets. The most important concepts of the Brickblock system are listed below: Registrar: is at the core of the system. It's an ownable contract that uses unstructured storage to manage an upgradeable directory of component contracts. POA Tokens: represents an asset that has been tokenized. It's called via a multitude of POAProxies that are deployed by POAManager via the delegate proxy factory pattern. Exchange Price Oracle: ExchangeRateProvider inherits from the Oraclize API and fetches current exchange rates, storing them in the ExchangeRates contract for use. BBK Token: is a double-entry paradigm token that can be locked for a period of time to collect ACT rewards. ACT Token: is another double-entry paradigm token that serves as a payout to locked-in BBK tokens and can be exchanged at a set-rate for Ether.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 4 / 22 To better understand how all the components interact it is helpful to analyze the system diagram (source ecosystem): 1.4 Key Observations/Recommendations Praises: The system specification was thorough from the day this phase of the audit was initiated and every design choice was well-founded. The Brickblock team was interactive throughout and diligent in applying fixes to presented issues. Recommendations: Last pass on specification: it is recommended that the team does one last pass on the specification and documentation of the codebase. This includes comments in the codebase, as some of these have proved to be inconsistent with current code state. Last pass on implementation: akin to the last pass on specification/documentation it is recommended that stale parts of the codebase are identified and removed before deployment to mainnet. Fix all issues: It is recommended to fix all the issues listed in the below chapters, at the very least the ones with severity Critical, Major and Medium. 1.5 Revision This section serves the sole purpose of acknowledging that the auditing team has approved all the changes coming into effect as a cause of the first revision of the report. The team acknowledges that all issues have been closed either by changing the codebase to correctly address the problem at hand or by having the development team provide a precise explanation of why said issue was not addressed. Remediation links are provided in each of the relevant issue sections. Non-fix explanations are found in this same section in the following table.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 5 / 22The commit hash agreed upon for checkpointing the codebase after all the fixes was: 99770100c9ae5ab7c8ac9d79e3fd0a8bce5f30b7 . Non-addressed Issues Explanation Issue NumberExplanation 3.4 Keep consistency of other calls where the event logger is used. 3.8 The power held by the owner of the system already enables other attacks. 3.15 Referenced code is just a stub for testing and so doesn't affect normal system operations. 3.16The current design allows for great flexibility as well as keeping fee payments simple. There have been no issues found with this so far. 3.20 Said overflows will not happen for a very large period of time. 3.21 Said overflows will not happen for a very large period of time. 3.22Due to the way we want to present balances to users during the crowdsale aspect, we want to ensure that the balance shows 0 for all users until a specific stage. There does not seem to be an easier way to do this. Additionally, the extra gas cost is not much. 3.22The struct is the same shape for both PoaToken and Broker data. The rights access is controlled with modifiers on the public functions (addBroker, removeBroker, addToken, removeToken) and then make use of private functions to work with the abstract EntityState. 2 Issue Overview The following table contains all the issues discovered during the audit. The issues are ordered based on their severity. A more detailed description of the levels of severity can be found in Appendix 2. The table also contains the Github status of any discovered issue. ChapterIssue TitleIssue StatusSeverityOpt. 3.1Unnecessary complexity in toXLengthString functions in PoaCommon ✔ 3.2No plan for how a physical tokenized asset would handle a chain split 3.3Usage of random storage slots in the Proxy adds too much complexity 3.4 Unnecessary usage of low-level .call() method 3.5Withdraw method does not check if balance is sufficient for the withdrawal 3.6 Can lock and unlock 0 BBK in AccessToken Brickblock_[Phase_2]_Audit-final.md 9/20/2018 6 / 22ChapterIssue TitleIssue StatusSeverityOpt. 3.7 Precision in percent function can overflow 3.8 Transaction order dependence issue in ExchangeRates 3.9Non-optimal ordering of instructions in PoaProxy and PoaToken fallback functions ✔ 3.10ExchangeRateProvider 's callback check for access control is non-optimal 3.11Inaccurate specification comment for setFailed() method in PoaCrowdsale 3.12 Unnecessary fallback functions to refuse payments ✔ 3.13 Comment about upgrade path is incorrect 3.14 buyAndEndFunding ends by calling buyAndContinueFunding 3.15Unused variable has no dummy check-in ExchangeRateProviderStub 3.16FeeManager open-by-default design might introduce flaws in the token economy 3.17 Unnecessary refund action in PoaCrowdsale ✔ 3.18this should be explicitly typecast to address 3.19 Blocking conditions in buyFiat 3.20Use of ever-growing unsigned integers in PoaToken is dangerous 3.21Use of ever-growing unsigned integers in AccessToken is dangerous 3.22 Non-optimal stage checking condition in PoaToken 3.23 Contradicting comment on POAManager 3.24 Inconsistent type used for decimals 3.25 Inconsistent event naming Brickblock_[Phase_2]_Audit-final.md 9/20/2018 7 / 22ChapterIssue TitleIssue StatusSeverityOpt. 3.26 Incorrect name of parameter in BBKUnlockedEvent 3.27Usage of EntityState for both brokers and tokens in PoaManager is an anti-separation-of-concerns pattern 3 Issue Detail 3.1 Unnecessary complexity in toXLengthString functions in PoaCommon Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/37 Description Both the toXLengthString functions in PoaCommon are too complex and can be substituted by a simpler version with a single assembly block. Remediation function to32LengthStringOpt( bytes32 _data ) pure internal returns (string) { // create new empty bytes array with same length as input bytes memory _bytesString = new bytes(32); // an assembly block is necessary to change memory layout directly assembly { // we store the _data bytes32 contents after the first 32 bytes of // _bytesString which hold its length mstore(add(_bytesString, 0x20), _data) } // and now we measure the string by searching for the first occurrence // of a zero'ed out byte for (uint256 _bytesCounter = 0; _bytesCounter < 32; _bytesCounter++) { if (_bytesString[_bytesCounter] == hex"00") { break; } } Brickblock_[Phase_2]_Audit-final.md 9/20/2018 8 / 22 // knowing the trimmed size we can now change its length directly assembly { // by changing the 32-byte-long slot we skipped over previously mstore(_bytesString, _bytesCounter) } return string(_bytesString); } function to64LengthStringOpt( bytes32[2] _data ) pure internal returns (string) { // create new empty bytes array with same length as input bytes memory _bytesString = new bytes(64); // an assembly block is necessary to change memory layout directly assembly { // we store the _data bytes32 contents after the first 32 bytes of // _bytesString which hold its length mstore(add(_bytesString, 0x20), mload(_data)) mstore(add(_bytesString, 0x40), mload(add(_data, 0x20))) } // and now we measure the string by searching for the first occurrence // of a zero'ed out byte for (uint256 _bytesCounter = 0; _bytesCounter < 64; _bytesCounter++) { if (_bytesString[_bytesCounter] == hex"00") { break; } } // knowing the trimmed size we can now change its length directly assembly { // by changing the 32-byte-long slot we skipped over previously mstore(_bytesString, _bytesCounter) } return string(_bytesString); } Brickblock_[Phase_2]_Audit-final.md 9/20/2018 9 / 223.2 No plan for how a physical tokenized asset would handle a chain split Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/48 Description The brickblock contract system creates tokens for physical assets, but in the event of an unplanned contentious hard fork, there would be two blockchain assets for each physical one. This is a potentially catastrophic scenario. Remediation Plan possible scenarios for how the brickblock system would handle the split tokens, choose a fork to support, and/or deprecate a fork. Add the plans to WORST-CASE-SCENARIOS.md 3.3 Usage of random storage slots in the Proxy adds too much complexity Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/21 Description There is a big complexity in the codebase stemming from the use of a custom implementation of randomized storage slots for system-wide storage variables. This promotes dense code and may introduce unknown vulnerabilities. Remediation The set of PoA-related contracts could make use inherited storage instead of having addresses reside in random slots in storage. This would avoid such heavy use of inline assembly, therefore, maintaining readability and safety. 3.4 Unnecessary usage of low-level .call() method Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/40 Description Throughout the set of PoA-related contracts, there is an unnecessary and possibly dangerous usage of the low- level .call() method since every contract being called is known by the caller beforehand. Remediation Typecast the address variable returned by ContractRegistry and call the relevant member of the contract type without the use of .call() (this is especially relevant in https://github.com/brickblock-io/smart- contracts/blob/6360f5e1ba0630fa0caf82ff9b58b2dc5e9e1b53/contracts/PoaCommon.sol#L184).Brickblock_[Phase_2]_Audit-final.md 9/20/2018 10 / 223.5 Withdraw method does not check if balance is sufficient for the withdrawal Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/29 Description The withdrawEthFunds in BrickblockAccount does not check that balance is greater than the amount being requested, just that it's greater than zero function withdrawEthFunds( address _address, uint256 _value ) external onlyOwner returns (bool) { require(address(this).balance > 0); _address.transfer(_value); return true; } Remediation Consider switching require(address(this).balance > 0); to require(address(this).balance >= _value); 3.6 Can lock and unlock 0 BBK in AccessToken Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/30 Description This method is public and can be called by anyone with quantity zero Remediation Consider adding a validator to the function to eliminate a possible source of user error require( _value > 0); 3.7 Precision in percent function can overflow Severity Issue Status GitHub Repo Issue LinkBrickblock_[Phase_2]_Audit-final.md 9/20/2018 11 / 22Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/46 Description The public percent function in PoaCrowdsale takes precision as a parameter, does not validate it, and does not use safe math uint256 _safeNumerator = _numerator.mul(10 ** (_precision + 1)); Remediation Though the only place the brickblock contract system currently uses this function, precision is set at 18, using safe math here could prevent future error as the contract system evolves. 3.8 Transaction order dependence issue in ExchangeRates Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/47 Description Even though there is an access control layer applied to the whole contract, there's a transaction order dependence issue with the "owner" agent in ExchangeRates . When seeing a big buy transaction come in, "owner", basically controlling the exchange rate, could prepend a transaction (or multiple ones) of his own to get all the contribution for, practically, no tokens in exchange. Remediation A timelock could be implemented to give buyers a safe window on which to execute buy orders, but since the "owner" already holds so much power in the ACL structure, this may not be needed for the end user to feel safe buying tokens. 3.9 Non-optimal ordering of instructions in PoaProxy and PoaToken fallback functions Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/45 Description In PoaProxy and PoaToken fallback functions, the order of the instructions can be changed to achieve better gas optimization. There is no need to copy return data to memory if the call result is false and the call is going to be reverted anyway. Remediation Have the iszero(result) condition check reside before the returndatacopy instruction.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 12 / 223.10 ExchangeRateProvider's callback check for access control is non-optimal Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/44 Description Going against proposed COP (condition-oriented programming) patterns and the general code style present throughout the codebase, the __callback method of ExchangeRateProvider (v. https://github.com/brickblock-io/smart- contracts/blob/6360f5e1ba0630fa0caf82ff9b58b2dc5e9e1b53/contracts/ExchangeRateProvider.sol#L100) does not use a modifier to check if the caller is authorized to run this function. Remediation Have this check: require(msg.sender == oraclize_cbAddress()); reside in a properly named onlyX modifier. 3.11 Inaccurate specification comment for setFailed() method in PoaCrowdsale Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/41 Description The specification comment above the setFailed() method mentions scenarios that don't need this function to get to the "Failed" stage. 3.12 Unnecessary fallback functions to refuse payments Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/42 Description In AccessToken , CentralLogger , ContractRegistry , ExchangeRates , FeeManager , PoaManager and Whitelist the presence of the fallback function there defined is not needed because the default Solidity behavior is to disallow payments to contracts through their fallback function. Remediation Remove the fallback function definition from these contracts. 3.13 Comment about upgrade path is incorrect Severity Issue Status GitHub Repo Issue LinkBrickblock_[Phase_2]_Audit-final.md 9/20/2018 13 / 22Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/35 Description This comment in AccessTokenUpgradeExample is incorrect. In the event of an upgrade, more than just inheritance will be required to access the state of the old contract. * This is an example of how we would upgrade the AccessToken contract if we had to. * Instead of doing a full data migration from ACTv1 to ACTv2 we could make * use of inheritance and just access the state on the old contract. Remediation Remove the comment to prevent a source of possible future confusion. 3.14 buyAndEndFunding ends by calling buyAndContinueFunding Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/39 Description The function that ends a PoaCrowdsale , buyAndEndFunding , ends by calling buyAndContinueFunding - though there is no wrong functionality here, it is counterintuitive. Remediation Since buyAndContinueFunding has more than one use, consider renaming it - it provides no guarantees that funding continues. 3.15 Unused variable has no dummy check-in ExchangeRateProviderStub Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/28 Description There are unused variables in the sendQuery function in ExchangeRateProvider, generating a compiler warning. In ExchangeRateProviderStub on the same function, there's a comment about doing a dummy check is wrong, but no dummy check is done. RemediationBrickblock_[Phase_2]_Audit-final.md 9/20/2018 14 / 22Silence the compiler by mentioning the variables _callInterval, _callbackGasLimit 3.16 FeeManager open-by-default design might introduce flaws in the token economy Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/18 Description The payFee function in FeeManager is public and does not validate or restrict msg.sender Remediation While this is intentional, it also increases the attack surface of the system, since paying a fee to FeeManager effects the totalSupply_ of ACT. Though at the moment any attack is likely prohibitively expensive, economic interference with the exchange rates of BBK to ACT is possible. 3.17 Unnecessary refund action in PoaCrowdsale Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/43 Description In the buyAndEndFunding() method of PoaCrowdsale there's a transfer action being executed every time even if the refund is equal to 0 or not even requested/needed. Remediation Only transfer if refundAmount > 0 . 3.18 this should be explicitly typecast to address Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/19 Description this is implicitly used as an address, which is forbidden in newer versions of solidity Remediation Every instance of this should now be explicitly typecast to the address type 3.19 Blocking conditions in buyFiat Severity Issue Status GitHub Repo Issue LinkBrickblock_[Phase_2]_Audit-final.md 9/20/2018 15 / 22Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/38 Description There is an edge case where the difference between fundingGoalInCents and fundedAmountInCentsDuringFiatFunding is less than 100, causing this earlier check require(_amountInCents >= 100); to block reaching the funding goal In addition, there is a logical error in the function: Because of the check if (fundingGoalInCents().sub(_newFundedAmount) >= 0) , the second check if (fundedAmountInCentsDuringFiatFunding() >= fundingGoalInCents()) can never be greater than, only less than or equal to. Remediation Though this can be unblocked by moving on to the third stage and funding with Ether, the gas fees to do so will likely be more than the remaining needed funding amount. Possible mitigations include removing the require(_amountInCents >= 100); , validating that fundingGoalInCents % 100 == 0 , or otherwise changing the logical flow. 3.20 Use of ever-growing unsigned integers in PoaToken is dangerous Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/36 Description Just like AccessToken , this contract makes use of unsigned integer variables that can only increase and create an attack surface for DoS attacks, as well as a scalability limitation. Remediation Even though from a very careful analysis we could see that any attack would be hugely costly this presents an opportunity for a possible extension over this token, in the future, to overlook this nature of said variables and for this to become an actual attack vector. Similarly to AccessToken , the results of balanceOf calls could be validated 3.21 Use of ever-growing unsigned integers in AccessToken is dangerous Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/33 DescriptionBrickblock_[Phase_2]_Audit-final.md 9/20/2018 16 / 22In both the balanceOf and distribute functions the math behind makes use of uint256 variables that are ever-growing (can only increase and never decrease, per specification), this creates an attack surface for DoS attacks. Remediation Even though from a very careful analysis we could see that any attack would be hugely costly this presents an opportunity for a possible extension over this token, in the future, to overlook this nature of said variables and for this to become an actual attack vector. The possibility of attack or accidental DOS can be prevented by using the results of balanceOf function in an overflow check uint256 newRecipientBalance = balanceOf(_to).add(_value); uint256 tempSpent = spentBalances[_to]; require(tempSpent.add(newRecipientBalance)); 3.22 Non-optimal stage checking condition in PoaToken Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/34 Description The check of whether PoaToken is in stage 4 is implemented in the startingBalance function which, in turn, is used in the balanceOf function which is transversal to a lot of other functions. Besides creating an extra piece of bytecode that will get executed even in the transferFrom and currentPayout functions, it is buried down in the logic which makes it harder to assess the certainty of the specification: "the token is only tradeable after stage 4". Remediation The use of a modifier on the transfer function alone would achieve the same effect and produce more readable and extensible code. 3.23 Contradicting comment on POAManager Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/24 Description The addToken() function in POAManager has a comment saying it initializes the entity with _active as true but actually sets it false. RemediationBrickblock_[Phase_2]_Audit-final.md 9/20/2018 17 / 22Verify that this is the correct behaviour in code, and correct the comment 3.24 Inconsistent type used for decimals Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/25 Description An inconsistent type is used for decimals. In POAToken uint256 is used, in AccessToken uint8 is used. Remediation Consider which type is preferable for this parameter and use it uniformly throughout all tokens. uint8 is more commonly seen in standards 3.25 Inconsistent event naming Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/26 Description Throughout the contract system - somewhat inconsistent event naming conventions, for example, Burn and BurnEvent event BurnEvent(address indexed burner, uint256 value); event Burn(address indexed burner, uint256 value); Remediation Decide on a naming convention and use it throughout the system. The BurnEvent pattern may be the stronger choice, as it follows the Differentiate functions and events best practice 3.26 Incorrect name of parameter in BBKUnlockedEvent Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/27 Description In AccessToken, wrong variable name, the second uint256 is actually the unlockedAmountBrickblock_[Phase_2]_Audit-final.md 9/20/2018 18 / 22 event BBKUnlockedEvent( address indexed locker, uint256 lockedAmount, uint256 totalLockedAmount ); Remediation Correct the variable name: event BBKUnlockedEvent( address indexed locker, uint256 unlockedAmount, uint256 totalLockedAmount ); 3.27 Usage of EntityState for both brokers and tokens in PoaManager is an anti- separation-of-concerns pattern Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/32 Description The use of the doesEntityExist modifier and the addEntity , removeEntity , and setEntityActiveValue to manipulate both brokers and tokens in the contract's state is an anti-pattern regarding separation of concerns. Since these functions are reused across two very different domains of logic state, this means that in the unlikely event of a public function related to brokers having a vulnerability there's a non-zero probability that tokens are compromised as well. Given the importance of the prior and latter lists, this is a clear escalation in the severity of a vulnerability. Remediation Create specific functions to handle each one of the different entities (e.g. addToken , removeBroker ) or implement the add, remove and set active logics for each entity in the public functions themselves instead of having shared private functions for that. 4 Tool based analysis The issues from the tool based analysis have been reviewed and the relevant issues have been listed in chapter 3 - Issues. 4.1 MythrilBrickblock_[Phase_2]_Audit-final.md 9/20/2018 19 / 22 Mythril is a security analysis tool for Ethereum smart contracts. It uses concolic analysis to detect various types of issues. The tool was used for automated vulnerability discovery for all audited contracts and libraries. More details on Mythril's current vulnerability coverage can be found here. The raw output of the Mythril vulnerability scan can be found here. It was thoroughly reviewed for possible vulnerabilities, and all the results stemming out of such analysis were included in the final issues report. 4.2 Sūrya Surya is a utility tool for smart contract systems. It provides a number of visual outputs and information about the structure of smart contracts. It also supports querying the function call graph in multiple ways to aid in the manual inspection and control flow analysis of contracts. A complete list of functions with their visibility and modifiers can be found here. 4.3 Odyssey Odyssey is an audit tool that acts as the glue between developers, auditors, and tools. It leverages Github as the platform for building software and aligns to the approach that quality needs to be addressed as early as possible in the development life cycle and small iterative security activities spread out through development help to produce a more secure smart contract system. In its current version Odyssey helps communicate audit issues to development teams better and to close them successfully. Appendix 1 - File Hashes The SHA1 hashes of the source code files in scope of the audit are listed in the table below. Contract File Name SHA1 hash stubs/RemoteContractStub.sol c2da2c57d0502a68acc9cafa134ffb62dfdc8446 stubs/RemoteContractUserStub.sol b4d9811cca3c8c2516d521f315945f18e1ca488c stubs/ExchangeRateProviderStub.solbce06f04ad4ae358e2802198484a95d7091cbdfb stubs/BrokenRemoteContractStub.sol76d0cd9bcb809cd26255fcbf0aca5aae593fdd13 stubs/PoaManagerStub.sol 886dd9d3f890acf7f6cf3c802a02e28dfcb38795 stubs/UpgradedPoa.sol 7ddde558f506efec77488ba958fc1db714d1df4d stubs/BrickblockFountainStub.sol 1fcd2643e33cf0fa76644dd2203b0fa697701ed5 PoaProxy.sol 2359f57c3503608f206195372e220d3673a127f2 PoaManager.sol 0022d2a65065359ef648d05fc1a01b049dd32ff3 ExchangeRates.sol dd4c7a19d798a5a097d12e7fd2146f18705d5e6c tools/WarpTool.sol c2e2f5b46c2382d5919a6a11852d8bd3718ea238Brickblock_[Phase_2]_Audit-final.md 9/20/2018 20 / 22Contract File Name SHA1 hash CustomPOAToken.sol bc8a19f076450c44a8c1cb175626e9ca5b21c712 OraclizeAPI.sol 974d293678647f934864c4eef21469c322e60f19 CentralLogger.sol 63d7facdd2fd969f798b7eef4f3eb89392f817ea FeeManager.sol ba1fa0085716b524424a8b1ba366fde272b03842 BrickblockAccount.sol 2c8cf3c8a6c8ce68044c89afaa1b30e5392f1b0c AccessToken.sol 9ea080dade42bf75787805d87be7aa7d3cdf2f11 Migrations.sol cfc2c3229aa8d50eb038dbdad89b79c10aa76e81 Whitelist.sol 0059355f7b70aefcae1e00293717c5547bf4c9f2 BrickblockToken.sol 1dc072c4a388eb02a8e5ff94e53170266b3986cd PoaToken.sol 7115dd663666c65344d60530cb7f3a1f2439a4a9 ContractRegistry.sol 2bad3f21834b921e00a2c69e70976f49b8f0b828 AccessTokenUpgradeExample.sol 4934bdfbf573caed91b947c4ce33fdd13525759a ExchangeRateProvider.sol 55ae134887bf0ec8b6436dd32026f69f384abf8b interfaces/IWhitelist.sol c1f79ab4dfe09e739142cba10bf5e8cb8c7cae00 interfaces/IAccessToken.sol 86ed15fbf886c084deec249dfb47286cfac1d328 interfaces/IBrickblockToken.sol 98db90ef02f16a9bf2097b7f7cbbdaef74e6c39d interfaces/IPoaToken.sol 0a00f80a0e25d19a9615247ed3f58c79cee592ed interfaces/IExchangeRates.sol 9f27b08adff3d6451689f6f2eaf60e7f79241676 interfaces/IFeeManager.sol cc418992580a2b7e471461c0aa71c554edc44206 interfaces/IRegistry.sol 33620967a81de0ecd2b82356eb8ed2eb1e3523cf interfaces/IExchangeRateProvider.sol 61f0a6d1f06f85f501d755c45f6ab2517a716472 interfaces/IPoaManager.sol 1d09eb035efbf7d087b4e6d60d25480cacf0d1d7 Appendix 2 - Severity A.2.1 - Minor Minor issues are generally subjective or potentially deal with topics like "best practices" or "readability". In general, minor issues do not indicate an actual problem or bug in the code. The maintainers should use their own judgment as to whether addressing these issues improves the codebase. A.2.2 - Medium Medium issues are generally objective but do not represent actual bugs or security problems.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 21 / 22These issues should be addressed unless there is a clear reason not to. A.2.3 - Major Major issues are things like bugs or security vulnerabilities. These issues may not be directly exploitable or may require a certain condition to arise to be exploited. Left unaddressed these issues are highly likely to cause problems with the operation of the contract or lead to a situation which allows the system to be exploited in some way. A.2.4 - Critical Critical issues are directly exploitable bugs or security vulnerabilities. Left unaddressed these issues are highly likely or guaranteed to cause critical problems or potentially a full failure in the operations of the contract. Appendix 3 - 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 other 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 Github account (https://github.com/GNSPS). 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 andBrickblock_[Phase_2]_Audit-final.md 9/20/2018 22 / 22CD 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 endorse 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 assume 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.
Issues Count of Minor/Moderate/Major/Critical - Minor: 25 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Unnecessary complexity in toXLengthString functions in PoaCommon (BB-1) 2.b Refactor toXLengthString functions to reduce complexity (BB-1) 3.a No plan for how a physical tokenized asset would handle a chain split (BB-2) 3.b Develop a plan for how a physical tokenized asset would handle a chain split (BB-2) 4.a Usage of random storage slots in the Proxy adds too much complexity (BB-3) 4.b Refactor the Proxy to use a more deterministic storage slot allocation (BB-3) 5.a Unnecessary usage of low-level .call() method (BB-4) 5.b Refactor the code to use higher-level abstractions (BB-4) 6.a Withdraw method does not check if balance is sufficient for the withdrawal (BB-5) 6.b Add a check to the withdraw method to ensure balance is sufficient (BB-5) 7.a Precision Issues Count of Minor/Moderate/Major/Critical: Minor: 25 Moderate: 4 Major: 0 Critical: 0 Minor Issues: Problem: Unstructured storage is used to manage an upgradeable directory of component contracts. (f1f5b04722b9569e1d4c0b62ac4c490c0a785fd88) Fix: Use structured storage to manage an upgradeable directory of component contracts. Moderate: Problem: POA tokens are not checked for overflow. (f1f5b04722b9569e1d4c0b62ac4c490c0a785fd88) Fix: POA tokens should be checked for overflow. Major: N/A Critical: N/A Observations: The audit team found that the smart contract system is secure, resilient and working according to its specifications. Conclusion: The audit team concluded that the smart contract system is secure and functioning as expected. Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.1 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 2.1 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. 2.2 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 2.2 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. 2.3 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 2.3 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. Moderate 3.1 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 3.1 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. 3.2 Problem: ExchangeRateProvider does not check
pragma solidity 0.4.18; import "frozen-zeppelin-solidity/contracts/token/PausableToken.sol"; contract CustomPOAToken is PausableToken { string public name; string public symbol; uint8 public constant decimals = 18; address public owner; address public broker; address public custodian; uint256 public creationBlock; uint256 public timeoutBlock; // the total per token payout rate: accumulates as payouts are received uint256 public totalPerTokenPayout; uint256 public tokenSaleRate; uint256 public fundedAmount; uint256 public fundingGoal; uint256 public initialSupply; // ‰ permille NOT percent uint256 public constant feeRate = 5; // self contained whitelist on contract, must be whitelisted to buy mapping (address => bool) public whitelisted; // used to deduct already claimed payouts on a per token basis mapping(address => uint256) public claimedPerTokenPayouts; // fallback for when a transfer happens with payouts remaining mapping(address => uint256) public unclaimedPayoutTotals; enum Stages { Funding, Pending, Failed, Active, Terminated } Stages public stage = Stages.Funding; event StageEvent(Stages stage); event BuyEvent(address indexed buyer, uint256 amount); event PayoutEvent(uint256 amount); event ClaimEvent(uint256 payout); event TerminatedEvent(); event WhitelistedEvent(address indexed account, bool isWhitelisted); modifier isWhitelisted() { require(whitelisted[msg.sender]); _; } modifier onlyCustodian() { require(msg.sender == custodian); _; } // start stage related modifiers modifier atStage(Stages _stage) { require(stage == _stage); _; } modifier atEitherStage(Stages _stage, Stages _orStage) { require(stage == _stage || stage == _orStage); _; } modifier checkTimeout() { if (stage == Stages.Funding && block.number >= creationBlock.add(timeoutBlock)) { uint256 _unsoldBalance = balances[this]; balances[this] = 0; totalSupply = totalSupply.sub(_unsoldBalance); Transfer(this, address(0), balances[this]); enterStage(Stages.Failed); } _; } // end stage related modifiers // token totalSupply must be more than fundingGoal! function CustomPOAToken ( string _name, string _symbol, address _broker, address _custodian, uint256 _timeoutBlock, uint256 _totalSupply, uint256 _fundingGoal ) public { require(_fundingGoal > 0); require(_totalSupply > _fundingGoal); owner = msg.sender; name = _name; symbol = _symbol; broker = _broker; custodian = _custodian; timeoutBlock = _timeoutBlock; creationBlock = block.number; // essentially sqm unit of building... totalSupply = _totalSupply; initialSupply = _totalSupply; fundingGoal = _fundingGoal; balances[this] = _totalSupply; paused = true; } // start token conversion functions /******************* * TKN supply * * --- = ------- * * ETH funding * *******************/ // util function to convert wei to tokens. can be used publicly to see // what the balance would be for a given Ξ amount. // will drop miniscule amounts of wei due to integer division function weiToTokens(uint256 _weiAmount) public view returns (uint256) { return _weiAmount .mul(1e18) .mul(initialSupply) .div(fundingGoal) .div(1e18); } // util function to convert tokens to wei. can be used publicly to see how // much Ξ would be received for token reclaim amount // will typically lose 1 wei unit of Ξ due to integer division function tokensToWei(uint256 _tokenAmount) public view returns (uint256) { return _tokenAmount .mul(1e18) .mul(fundingGoal) .div(initialSupply) .div(1e18); } // end token conversion functions // pause override function unpause() public onlyOwner whenPaused { // only allow unpausing when in Active stage require(stage == Stages.Active); return super.unpause(); } // stage related functions function enterStage(Stages _stage) private { stage = _stage; StageEvent(_stage); } // start whitelist related functions // allow address to buy tokens function whitelistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != true); whitelisted[_address] = true; WhitelistedEvent(_address, true); } // disallow address to buy tokens. function blacklistAddress(address _address) external onlyOwner atStage(Stages.Funding) { require(whitelisted[_address] != false); whitelisted[_address] = false; WhitelistedEvent(_address, false); } // check to see if contract whitelist has approved address to buy function whitelisted(address _address) public view returns (bool) { return whitelisted[_address]; } // end whitelist related functions // start fee handling functions // public utility function to allow checking of required fee for a given amount function calculateFee(uint256 _value) public view returns (uint256) { return feeRate.mul(_value).div(1000); } // end fee handling functions // start lifecycle functions function buy() public payable checkTimeout atStage(Stages.Funding) isWhitelisted returns (bool) { uint256 _payAmount; uint256 _buyAmount; // check if balance has met funding goal to move on to Pending if (fundedAmount.add(msg.value) < fundingGoal) { // _payAmount is just value sent _payAmount = msg.value; // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // check that buyer will indeed receive something after integer division // this check cannot be done in other case because it could prevent // contract from moving to next stage require(_buyAmount > 0); } else { // let the world know that the token is in Pending Stage enterStage(Stages.Pending); // set refund amount (overpaid amount) uint256 _refundAmount = fundedAmount.add(msg.value).sub(fundingGoal); // get actual Ξ amount to buy _payAmount = msg.value.sub(_refundAmount); // get token amount from wei... drops remainders (keeps wei dust in contract) _buyAmount = weiToTokens(_payAmount); // assign remaining dust uint256 _dust = balances[this].sub(_buyAmount); // sub dust from contract balances[this] = balances[this].sub(_dust); // give dust to owner balances[owner] = balances[owner].add(_dust); Transfer(this, owner, _dust); // SHOULD be ok even with reentrancy because of enterStage(Stages.Pending) msg.sender.transfer(_refundAmount); } // deduct token buy amount balance from contract balance balances[this] = balances[this].sub(_buyAmount); // add token buy amount to sender's balance balances[msg.sender] = balances[msg.sender].add(_buyAmount); // increment the funded amount fundedAmount = fundedAmount.add(_payAmount); // send out event giving info on amount bought as well as claimable dust Transfer(this, msg.sender, _buyAmount); BuyEvent(msg.sender, _buyAmount); return true; } function activate() external checkTimeout onlyCustodian payable atStage(Stages.Pending) returns (bool) { // calculate company fee charged for activation uint256 _fee = calculateFee(fundingGoal); // value must exactly match fee require(msg.value == _fee); // if activated and fee paid: put in Active stage enterStage(Stages.Active); // owner (company) fee set in unclaimedPayoutTotals to be claimed by owner unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee); // custodian value set to claimable. can now be claimed via claim function // set all eth in contract other than fee as claimable. // should only be buy()s. this ensures buy() dust is cleared unclaimedPayoutTotals[custodian] = unclaimedPayoutTotals[custodian] .add(this.balance.sub(_fee)); // allow trading of tokens paused = false; // let world know that this token can now be traded. Unpause(); return true; } // used when property no longer exists etc. allows for winding down via payouts // can no longer be traded after function is run function terminate() external onlyCustodian atStage(Stages.Active) returns (bool) { // set Stage to terminated enterStage(Stages.Terminated); // pause. Cannot be unpaused now that in Stages.Terminated paused = true; // let the world know this token is in Terminated Stage TerminatedEvent(); } // emergency temporary function used only in case of emergency to return // Ξ to contributors in case of catastrophic contract failure. function kill() external onlyOwner { // stop trading paused = true; // enter stage which will no longer allow unpausing enterStage(Stages.Terminated); // transfer funds to company in order to redistribute manually owner.transfer(this.balance); // let the world know that this token is in Terminated Stage TerminatedEvent(); } // end lifecycle functions // start payout related functions // get current payout for perTokenPayout and unclaimed function currentPayout(address _address, bool _includeUnclaimed) public view returns (uint256) { /* need to check if there have been no payouts safe math will throw otherwise due to dividing 0 The below variable represents the total payout from the per token rate pattern it uses this funky naming pattern in order to differentiate from the unclaimedPayoutTotals which means something very different. */ uint256 _totalPerTokenUnclaimedConverted = totalPerTokenPayout == 0 ? 0 : balances[_address] .mul(totalPerTokenPayout.sub(claimedPerTokenPayouts[_address])) .div(1e18); /* balances may be bumped into unclaimedPayoutTotals in order to maintain balance tracking accross token transfers perToken payout rates are stored * 1e18 in order to be kept accurate perToken payout is / 1e18 at time of usage for actual Ξ balances unclaimedPayoutTotals are stored as actual Ξ value no need for rate * balance */ return _includeUnclaimed ? _totalPerTokenUnclaimedConverted.add(unclaimedPayoutTotals[_address]) : _totalPerTokenUnclaimedConverted; } // settle up perToken balances and move into unclaimedPayoutTotals in order // to ensure that token transfers will not result in inaccurate balances function settleUnclaimedPerTokenPayouts(address _from, address _to) private returns (bool) { // add perToken balance to unclaimedPayoutTotals which will not be affected by transfers unclaimedPayoutTotals[_from] = unclaimedPayoutTotals[_from].add(currentPayout(_from, false)); // max out claimedPerTokenPayouts in order to effectively make perToken balance 0 claimedPerTokenPayouts[_from] = totalPerTokenPayout; // same as above for to unclaimedPayoutTotals[_to] = unclaimedPayoutTotals[_to].add(currentPayout(_to, false)); // same as above for to claimedPerTokenPayouts[_to] = totalPerTokenPayout; return true; } // used to manually set Stage to Failed when no users have bought any tokens // if no buy()s occurred before timeoutBlock token would be stuck in Funding function setFailed() external atStage(Stages.Funding) checkTimeout returns (bool) { if (stage == Stages.Funding) { revert(); } return true; } // reclaim Ξ for sender if fundingGoal is not met within timeoutBlock function reclaim() external checkTimeout atStage(Stages.Failed) returns (bool) { // get token balance of user uint256 _tokenBalance = balances[msg.sender]; // ensure that token balance is over 0 require(_tokenBalance > 0); // set token balance to 0 so re reclaims are not possible balances[msg.sender] = 0; // decrement totalSupply by token amount being reclaimed totalSupply = totalSupply.sub(_tokenBalance); Transfer(msg.sender, address(0), _tokenBalance); // decrement fundedAmount by eth amount converted from token amount being reclaimed fundedAmount = fundedAmount.sub(tokensToWei(_tokenBalance)); // set reclaim total as token value uint256 _reclaimTotal = tokensToWei(_tokenBalance); // send Ξ back to sender msg.sender.transfer(_reclaimTotal); return true; } // send Ξ to contract to be claimed by token holders function payout() external payable atEitherStage(Stages.Active, Stages.Terminated) onlyCustodian returns (bool) { // calculate fee based on feeRate uint256 _fee = calculateFee(msg.value); // ensure the value is high enough for a fee to be claimed require(_fee > 0); // deduct fee from payout uint256 _payoutAmount = msg.value.sub(_fee); /* totalPerTokenPayout is a rate at which to payout based on token balance it is stored as * 1e18 in order to keep accuracy it is / 1e18 when used relating to actual Ξ values */ totalPerTokenPayout = totalPerTokenPayout .add(_payoutAmount .mul(1e18) .div(totalSupply) ); // take remaining dust and send to owner rather than leave stuck in contract // should not be more than a few wei uint256 _delta = (_payoutAmount.mul(1e18) % totalSupply).div(1e18); unclaimedPayoutTotals[owner] = unclaimedPayoutTotals[owner].add(_fee).add(_delta); // let the world know that a payout has happened for this token PayoutEvent(_payoutAmount); return true; } // claim total Ξ claimable for sender based on token holdings at time of each payout function claim() external atEitherStage(Stages.Active, Stages.Terminated) returns (uint256) { /* pass true to currentPayout in order to get both: perToken payouts unclaimedPayoutTotals */ uint256 _payoutAmount = currentPayout(msg.sender, true); // check that there indeed is a pending payout for sender require(_payoutAmount > 0); // max out per token payout for sender in order to make payouts effectively // 0 for sender claimedPerTokenPayouts[msg.sender] = totalPerTokenPayout; // 0 out unclaimedPayoutTotals for user unclaimedPayoutTotals[msg.sender] = 0; // let the world know that a payout for sender has been claimed ClaimEvent(_payoutAmount); // transfer Ξ payable amount to sender msg.sender.transfer(_payoutAmount); return _payoutAmount; } // end payout related functions // start ERC20 overrides // same as ERC20 transfer other than settling unclaimed payouts function transfer ( address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(msg.sender, _to)); return super.transfer(_to, _value); } // same as ERC20 transfer other than settling unclaimed payouts function transferFrom ( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { // move perToken payout balance to unclaimedPayoutTotals require(settleUnclaimedPerTokenPayouts(_from, _to)); return super.transferFrom(_from, _to, _value); } // end ERC20 overrides // check if there is a way to get around gas issue when no gas limit calculated... // fallback function defaulting to buy function() public payable { buy(); } } pragma solidity 0.4.18; import "frozen-zeppelin-solidity/contracts/token/PausableToken.sol"; contract BrickblockToken is PausableToken { string public constant name = "BrickblockToken"; string public constant symbol = "BBK"; uint256 public constant initialSupply = 500 * (10 ** 6) * (10 ** uint256(decimals)); uint256 public companyTokens; uint256 public bonusTokens; uint8 public constant contributorsShare = 51; uint8 public constant companyShare = 35; uint8 public constant bonusShare = 14; uint8 public constant decimals = 18; address public bonusDistributionAddress; address public fountainContractAddress; bool public tokenSaleActive; bool public dead = false; event TokenSaleFinished ( uint256 totalSupply, uint256 distributedTokens, uint256 bonusTokens, uint256 companyTokens ); event Burn(address indexed burner, uint256 value); // This modifier is used in `distributeTokens()` and ensures that no more than 51% of the total supply can be distributed modifier supplyAvailable(uint256 _value) { uint256 _distributedTokens = initialSupply.sub(balances[this].add(bonusTokens)); uint256 _maxDistributedAmount = initialSupply.mul(contributorsShare).div(100); require(_distributedTokens.add(_value) <= _maxDistributedAmount); _; } function BrickblockToken(address _bonusDistributionAddress) public { require(_bonusDistributionAddress != address(0)); bonusTokens = initialSupply.mul(bonusShare).div(100); companyTokens = initialSupply.mul(companyShare).div(100); bonusDistributionAddress = _bonusDistributionAddress; totalSupply = initialSupply; balances[this] = initialSupply; Transfer(address(0), this, initialSupply); // distribute bonusTokens to bonusDistributionAddress balances[this] = balances[this].sub(bonusTokens); balances[bonusDistributionAddress] = balances[bonusDistributionAddress].add(bonusTokens); Transfer(this, bonusDistributionAddress, bonusTokens); // we need to start with trading paused to make sure that there can be no transfers while the token sale is still ongoing // we will unpause the contract manually after finalizing the token sale by calling `unpause()` which is a function inherited from PausableToken paused = true; tokenSaleActive = true; } // For worst case scenarios, e.g. when a vulnerability in this contract would be discovered and we would have to deploy a new contract // This is only for visibility purposes to publicly indicate that we consider this contract "dead" and don't intend to re-activate it ever again function toggleDead() external onlyOwner returns (bool) { dead = !dead; } // Helper function used in changeFountainContractAddress to ensure an address parameter is a contract and not an external address function isContract(address addr) private view returns (bool) { uint _size; assembly { _size := extcodesize(addr) } return _size > 0; } // Fountain contract address could change over time, so we need the ability to update its address function changeFountainContractAddress(address _newAddress) external onlyOwner returns (bool) { require(isContract(_newAddress)); require(_newAddress != address(this)); require(_newAddress != owner); fountainContractAddress = _newAddress; return true; } // Custom transfer function that enables us to distribute tokens while contract is paused. Cannot be used after end of token sale function distributeTokens(address _contributor, uint256 _value) external onlyOwner supplyAvailable(_value) returns (bool) { require(tokenSaleActive == true); require(_contributor != address(0)); require(_contributor != owner); balances[this] = balances[this].sub(_value); balances[_contributor] = balances[_contributor].add(_value); Transfer(this, _contributor, _value); return true; } // Distribute tokens reserved for partners and staff to a wallet owned by Brickblock function distributeBonusTokens(address _recipient, uint256 _value) external onlyOwner returns (bool) { require(_recipient != address(0)); require(_recipient != owner); balances[bonusDistributionAddress] = balances[bonusDistributionAddress].sub(_value); balances[_recipient] = balances[_recipient].add(_value); Transfer(bonusDistributionAddress, _recipient, _value); return true; } // Calculate the shares for company, bonus & contibutors based on the intial totalSupply of 500.000.000 tokens - not what is left over after burning function finalizeTokenSale() external onlyOwner returns (bool) { // ensure that sale is active. is set to false at the end. can only be performed once. require(tokenSaleActive == true); // ensure that fountainContractAddress has been set require(fountainContractAddress != address(0)); // calculate new total supply. need to do this in two steps in order to have accurate totalSupply due to integer division uint256 _distributedTokens = initialSupply.sub(balances[this].add(bonusTokens)); uint256 _newTotalSupply = _distributedTokens.add(bonusTokens.add(companyTokens)); // unpurchased amount of tokens which will be burned uint256 _burnAmount = totalSupply.sub(_newTotalSupply); // leave remaining balance for company to be claimed at later date balances[this] = balances[this].sub(_burnAmount); Burn(this, _burnAmount); // allow our fountain contract to transfer the company tokens to itself allowed[this][fountainContractAddress] = companyTokens; Approval(this, fountainContractAddress, companyTokens); // set new totalSupply totalSupply = _newTotalSupply; // prevent this function from ever running again after finalizing the token sale tokenSaleActive = false; // dispatch event showing sale is finished TokenSaleFinished( totalSupply, _distributedTokens, bonusTokens, companyTokens ); // everything went well return true return true; } // fallback function - do not allow any eth transfers to this contract function() external { revert(); } }
Brickblock_[Phase_2]_Audit-final.md 9/20/2018 1 / 22 Brickblock [Phase 2] Audit 1 Summary 1.1 Audit Dashboard 1.2 Audit Goals 1.3 System Overview 1.4 Key Observations/Recommendations 2 Issue Overview 3 Issue Detail 3.1 Unnecessary complexity in toXLengthString functions in PoaCommon 3.2 No plan for how a physical tokenized asset would handle a chain split 3.3 Usage of random storage slots in the Proxy adds too much complexity 3.4 Unnecessary usage of low-level .call() method 3.5 Withdraw method does not check if balance is sufficient for the withdrawal 3.6 Can lock and unlock 0 BBK in AccessToken 3.7 Precision in percent function can overflow 3.8 Transaction order dependence issue in ExchangeRates 3.9 Non-optimal ordering of instructions in PoaProxy and PoaToken fallback functions 3.10 ExchangeRateProvider 's callback check for access control is non-optimal 3.11 Inaccurate specification comment for setFailed() method in PoaCrowdsale 3.12 Unnecessary fallback functions to refuse payments 3.13 Comment about upgrade path is incorrect 3.14 buyAndEndFunding ends by calling buyAndContinueFunding 3.15 Unused variable has no dummy check in ExchangeRateProviderStub 3.16 FeeManager open-by-default design might introduce flaws in the token economy 3.17 Unnecessary refund action in PoaCrowdsale 3.18 this should be explicitly typecast to address 3.19 Blocking conditions in buyFiat 3.20 Use of ever-growing unsigned integers in PoaToken is dangerous 3.21 Use of ever-growing unsigned integers in AccessToken is dangerous 3.22 Non-optimal stage checking condition in PoaToken 3.23 Unnecessary static call to get POA Manager's address in POA proxy 3.24 Unnecessary static call to fetch registry's address in POA Proxy 3.25 Contradicting comment on POAManager 3.26 Inconsistent type used for decimals 3.27 Inconsistent event naming 3.28 Incorrect name of parameter in BBKUnlockedEvent 3.29 Usage of EntityState for both brokers and tokens in PoaManager is an anti-separation- of-concerns pattern 4 Tool based analysis 4.1 Mythril 4.2 Sūrya 4.3 Odyssey 5 Test Coverage Measurement Appendix 1 - File HashesBrickblock_[Phase_2]_Audit-final.md 9/20/2018 2 / 22 Appendix 2 - Severity A.2.1 - Minor A.2.2 - Medium A.2.3 - Major A.2.4 - Critical Appendix 3 - Disclosure 1 Summary ConsenSys Diligence conducted a security audit on Brickblock's system of smart contracts for tokenizing real-world assets with a specific focus on real estate. The scope of the audit included Brickblock's upgradable system of smart contracts, encompassing three tokens, a pricing oracle, and other utilities, but with the understanding that one of the contracts, POAManager, was not frozen and would undergo further development. The objective of the audit was to discover issues that could threaten the funds held in or behaviour of the Brickblock system, including its future upgradability. Final Revision Summary There were no critical or major issues with the contracts under review. All medium and minor issues have been diligently addressed by Brickblock through either code changes or detailed explanations that can be found in section 1.5 of this report. 1.1 Audit Dashboard Audit Details Project Name: Brickblock Audit Client Name: Brickblock Client Contact: Philip Paetz, Cody Lamson Auditors: Gonçalo Sá, Sarah Friend GitHub : https://github.com/brickblock-io/smart-contracts Languages: Solidity, Solidity Assembly, JavaScript Date: 8th June - Number of issues per severity 25 4 0 0 1.2 Audit Goals The focus of the audit was to verify that the smart contract system is secure, resilient and working according to its specifications. The audit activities can be grouped in the following three categories:Brickblock_[Phase_2]_Audit-final.md 9/20/2018 3 / 22Security: Identifying security related issues within each contract and within the system of contracts. Sound Architecture: Evaluation of the architecture of this system through the lens of established smart contract best practices and general software best practices. Code Correctness and Quality: A full review of the contract source code. The primary areas of focus include: Correctness Readability Sections of code with high complexity Improving scalability Quantity and quality of test coverage 1.3 System Overview Documentation The following documentation was available to the audit team: The README which describes how to work with the contracts. The Ecosystem documentation gives an architectural overview and detailed information about the individual contracts. The Tests against Geth doc which explains how to run the tests against geth and not truffle's ganache . Scope The audit focus was on the smart contract files, and test suites found in the following repositories: Repository Commit hash Commit date brickblock-io/smart-contractsf1f5b04722b9569e1d4c0b62ac4c490c0a785fd88th June 2018 The full list of smart contracts in scope of the audit can be found in chapter Appendix 1 - File Hashes. Design Brickblock is a system for managing the tokenization of assets, as well as custodianship/brokerage of and investment in those assets. The most important concepts of the Brickblock system are listed below: Registrar: is at the core of the system. It's an ownable contract that uses unstructured storage to manage an upgradeable directory of component contracts. POA Tokens: represents an asset that has been tokenized. It's called via a multitude of POAProxies that are deployed by POAManager via the delegate proxy factory pattern. Exchange Price Oracle: ExchangeRateProvider inherits from the Oraclize API and fetches current exchange rates, storing them in the ExchangeRates contract for use. BBK Token: is a double-entry paradigm token that can be locked for a period of time to collect ACT rewards. ACT Token: is another double-entry paradigm token that serves as a payout to locked-in BBK tokens and can be exchanged at a set-rate for Ether.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 4 / 22 To better understand how all the components interact it is helpful to analyze the system diagram (source ecosystem): 1.4 Key Observations/Recommendations Praises: The system specification was thorough from the day this phase of the audit was initiated and every design choice was well-founded. The Brickblock team was interactive throughout and diligent in applying fixes to presented issues. Recommendations: Last pass on specification: it is recommended that the team does one last pass on the specification and documentation of the codebase. This includes comments in the codebase, as some of these have proved to be inconsistent with current code state. Last pass on implementation: akin to the last pass on specification/documentation it is recommended that stale parts of the codebase are identified and removed before deployment to mainnet. Fix all issues: It is recommended to fix all the issues listed in the below chapters, at the very least the ones with severity Critical, Major and Medium. 1.5 Revision This section serves the sole purpose of acknowledging that the auditing team has approved all the changes coming into effect as a cause of the first revision of the report. The team acknowledges that all issues have been closed either by changing the codebase to correctly address the problem at hand or by having the development team provide a precise explanation of why said issue was not addressed. Remediation links are provided in each of the relevant issue sections. Non-fix explanations are found in this same section in the following table.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 5 / 22The commit hash agreed upon for checkpointing the codebase after all the fixes was: 99770100c9ae5ab7c8ac9d79e3fd0a8bce5f30b7 . Non-addressed Issues Explanation Issue NumberExplanation 3.4 Keep consistency of other calls where the event logger is used. 3.8 The power held by the owner of the system already enables other attacks. 3.15 Referenced code is just a stub for testing and so doesn't affect normal system operations. 3.16The current design allows for great flexibility as well as keeping fee payments simple. There have been no issues found with this so far. 3.20 Said overflows will not happen for a very large period of time. 3.21 Said overflows will not happen for a very large period of time. 3.22Due to the way we want to present balances to users during the crowdsale aspect, we want to ensure that the balance shows 0 for all users until a specific stage. There does not seem to be an easier way to do this. Additionally, the extra gas cost is not much. 3.22The struct is the same shape for both PoaToken and Broker data. The rights access is controlled with modifiers on the public functions (addBroker, removeBroker, addToken, removeToken) and then make use of private functions to work with the abstract EntityState. 2 Issue Overview The following table contains all the issues discovered during the audit. The issues are ordered based on their severity. A more detailed description of the levels of severity can be found in Appendix 2. The table also contains the Github status of any discovered issue. ChapterIssue TitleIssue StatusSeverityOpt. 3.1Unnecessary complexity in toXLengthString functions in PoaCommon ✔ 3.2No plan for how a physical tokenized asset would handle a chain split 3.3Usage of random storage slots in the Proxy adds too much complexity 3.4 Unnecessary usage of low-level .call() method 3.5Withdraw method does not check if balance is sufficient for the withdrawal 3.6 Can lock and unlock 0 BBK in AccessToken Brickblock_[Phase_2]_Audit-final.md 9/20/2018 6 / 22ChapterIssue TitleIssue StatusSeverityOpt. 3.7 Precision in percent function can overflow 3.8 Transaction order dependence issue in ExchangeRates 3.9Non-optimal ordering of instructions in PoaProxy and PoaToken fallback functions ✔ 3.10ExchangeRateProvider 's callback check for access control is non-optimal 3.11Inaccurate specification comment for setFailed() method in PoaCrowdsale 3.12 Unnecessary fallback functions to refuse payments ✔ 3.13 Comment about upgrade path is incorrect 3.14 buyAndEndFunding ends by calling buyAndContinueFunding 3.15Unused variable has no dummy check-in ExchangeRateProviderStub 3.16FeeManager open-by-default design might introduce flaws in the token economy 3.17 Unnecessary refund action in PoaCrowdsale ✔ 3.18this should be explicitly typecast to address 3.19 Blocking conditions in buyFiat 3.20Use of ever-growing unsigned integers in PoaToken is dangerous 3.21Use of ever-growing unsigned integers in AccessToken is dangerous 3.22 Non-optimal stage checking condition in PoaToken 3.23 Contradicting comment on POAManager 3.24 Inconsistent type used for decimals 3.25 Inconsistent event naming Brickblock_[Phase_2]_Audit-final.md 9/20/2018 7 / 22ChapterIssue TitleIssue StatusSeverityOpt. 3.26 Incorrect name of parameter in BBKUnlockedEvent 3.27Usage of EntityState for both brokers and tokens in PoaManager is an anti-separation-of-concerns pattern 3 Issue Detail 3.1 Unnecessary complexity in toXLengthString functions in PoaCommon Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/37 Description Both the toXLengthString functions in PoaCommon are too complex and can be substituted by a simpler version with a single assembly block. Remediation function to32LengthStringOpt( bytes32 _data ) pure internal returns (string) { // create new empty bytes array with same length as input bytes memory _bytesString = new bytes(32); // an assembly block is necessary to change memory layout directly assembly { // we store the _data bytes32 contents after the first 32 bytes of // _bytesString which hold its length mstore(add(_bytesString, 0x20), _data) } // and now we measure the string by searching for the first occurrence // of a zero'ed out byte for (uint256 _bytesCounter = 0; _bytesCounter < 32; _bytesCounter++) { if (_bytesString[_bytesCounter] == hex"00") { break; } } Brickblock_[Phase_2]_Audit-final.md 9/20/2018 8 / 22 // knowing the trimmed size we can now change its length directly assembly { // by changing the 32-byte-long slot we skipped over previously mstore(_bytesString, _bytesCounter) } return string(_bytesString); } function to64LengthStringOpt( bytes32[2] _data ) pure internal returns (string) { // create new empty bytes array with same length as input bytes memory _bytesString = new bytes(64); // an assembly block is necessary to change memory layout directly assembly { // we store the _data bytes32 contents after the first 32 bytes of // _bytesString which hold its length mstore(add(_bytesString, 0x20), mload(_data)) mstore(add(_bytesString, 0x40), mload(add(_data, 0x20))) } // and now we measure the string by searching for the first occurrence // of a zero'ed out byte for (uint256 _bytesCounter = 0; _bytesCounter < 64; _bytesCounter++) { if (_bytesString[_bytesCounter] == hex"00") { break; } } // knowing the trimmed size we can now change its length directly assembly { // by changing the 32-byte-long slot we skipped over previously mstore(_bytesString, _bytesCounter) } return string(_bytesString); } Brickblock_[Phase_2]_Audit-final.md 9/20/2018 9 / 223.2 No plan for how a physical tokenized asset would handle a chain split Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/48 Description The brickblock contract system creates tokens for physical assets, but in the event of an unplanned contentious hard fork, there would be two blockchain assets for each physical one. This is a potentially catastrophic scenario. Remediation Plan possible scenarios for how the brickblock system would handle the split tokens, choose a fork to support, and/or deprecate a fork. Add the plans to WORST-CASE-SCENARIOS.md 3.3 Usage of random storage slots in the Proxy adds too much complexity Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/21 Description There is a big complexity in the codebase stemming from the use of a custom implementation of randomized storage slots for system-wide storage variables. This promotes dense code and may introduce unknown vulnerabilities. Remediation The set of PoA-related contracts could make use inherited storage instead of having addresses reside in random slots in storage. This would avoid such heavy use of inline assembly, therefore, maintaining readability and safety. 3.4 Unnecessary usage of low-level .call() method Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/40 Description Throughout the set of PoA-related contracts, there is an unnecessary and possibly dangerous usage of the low- level .call() method since every contract being called is known by the caller beforehand. Remediation Typecast the address variable returned by ContractRegistry and call the relevant member of the contract type without the use of .call() (this is especially relevant in https://github.com/brickblock-io/smart- contracts/blob/6360f5e1ba0630fa0caf82ff9b58b2dc5e9e1b53/contracts/PoaCommon.sol#L184).Brickblock_[Phase_2]_Audit-final.md 9/20/2018 10 / 223.5 Withdraw method does not check if balance is sufficient for the withdrawal Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/29 Description The withdrawEthFunds in BrickblockAccount does not check that balance is greater than the amount being requested, just that it's greater than zero function withdrawEthFunds( address _address, uint256 _value ) external onlyOwner returns (bool) { require(address(this).balance > 0); _address.transfer(_value); return true; } Remediation Consider switching require(address(this).balance > 0); to require(address(this).balance >= _value); 3.6 Can lock and unlock 0 BBK in AccessToken Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/30 Description This method is public and can be called by anyone with quantity zero Remediation Consider adding a validator to the function to eliminate a possible source of user error require( _value > 0); 3.7 Precision in percent function can overflow Severity Issue Status GitHub Repo Issue LinkBrickblock_[Phase_2]_Audit-final.md 9/20/2018 11 / 22Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/46 Description The public percent function in PoaCrowdsale takes precision as a parameter, does not validate it, and does not use safe math uint256 _safeNumerator = _numerator.mul(10 ** (_precision + 1)); Remediation Though the only place the brickblock contract system currently uses this function, precision is set at 18, using safe math here could prevent future error as the contract system evolves. 3.8 Transaction order dependence issue in ExchangeRates Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/47 Description Even though there is an access control layer applied to the whole contract, there's a transaction order dependence issue with the "owner" agent in ExchangeRates . When seeing a big buy transaction come in, "owner", basically controlling the exchange rate, could prepend a transaction (or multiple ones) of his own to get all the contribution for, practically, no tokens in exchange. Remediation A timelock could be implemented to give buyers a safe window on which to execute buy orders, but since the "owner" already holds so much power in the ACL structure, this may not be needed for the end user to feel safe buying tokens. 3.9 Non-optimal ordering of instructions in PoaProxy and PoaToken fallback functions Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/45 Description In PoaProxy and PoaToken fallback functions, the order of the instructions can be changed to achieve better gas optimization. There is no need to copy return data to memory if the call result is false and the call is going to be reverted anyway. Remediation Have the iszero(result) condition check reside before the returndatacopy instruction.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 12 / 223.10 ExchangeRateProvider's callback check for access control is non-optimal Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/44 Description Going against proposed COP (condition-oriented programming) patterns and the general code style present throughout the codebase, the __callback method of ExchangeRateProvider (v. https://github.com/brickblock-io/smart- contracts/blob/6360f5e1ba0630fa0caf82ff9b58b2dc5e9e1b53/contracts/ExchangeRateProvider.sol#L100) does not use a modifier to check if the caller is authorized to run this function. Remediation Have this check: require(msg.sender == oraclize_cbAddress()); reside in a properly named onlyX modifier. 3.11 Inaccurate specification comment for setFailed() method in PoaCrowdsale Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/41 Description The specification comment above the setFailed() method mentions scenarios that don't need this function to get to the "Failed" stage. 3.12 Unnecessary fallback functions to refuse payments Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/42 Description In AccessToken , CentralLogger , ContractRegistry , ExchangeRates , FeeManager , PoaManager and Whitelist the presence of the fallback function there defined is not needed because the default Solidity behavior is to disallow payments to contracts through their fallback function. Remediation Remove the fallback function definition from these contracts. 3.13 Comment about upgrade path is incorrect Severity Issue Status GitHub Repo Issue LinkBrickblock_[Phase_2]_Audit-final.md 9/20/2018 13 / 22Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/35 Description This comment in AccessTokenUpgradeExample is incorrect. In the event of an upgrade, more than just inheritance will be required to access the state of the old contract. * This is an example of how we would upgrade the AccessToken contract if we had to. * Instead of doing a full data migration from ACTv1 to ACTv2 we could make * use of inheritance and just access the state on the old contract. Remediation Remove the comment to prevent a source of possible future confusion. 3.14 buyAndEndFunding ends by calling buyAndContinueFunding Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/39 Description The function that ends a PoaCrowdsale , buyAndEndFunding , ends by calling buyAndContinueFunding - though there is no wrong functionality here, it is counterintuitive. Remediation Since buyAndContinueFunding has more than one use, consider renaming it - it provides no guarantees that funding continues. 3.15 Unused variable has no dummy check-in ExchangeRateProviderStub Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/28 Description There are unused variables in the sendQuery function in ExchangeRateProvider, generating a compiler warning. In ExchangeRateProviderStub on the same function, there's a comment about doing a dummy check is wrong, but no dummy check is done. RemediationBrickblock_[Phase_2]_Audit-final.md 9/20/2018 14 / 22Silence the compiler by mentioning the variables _callInterval, _callbackGasLimit 3.16 FeeManager open-by-default design might introduce flaws in the token economy Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/18 Description The payFee function in FeeManager is public and does not validate or restrict msg.sender Remediation While this is intentional, it also increases the attack surface of the system, since paying a fee to FeeManager effects the totalSupply_ of ACT. Though at the moment any attack is likely prohibitively expensive, economic interference with the exchange rates of BBK to ACT is possible. 3.17 Unnecessary refund action in PoaCrowdsale Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/43 Description In the buyAndEndFunding() method of PoaCrowdsale there's a transfer action being executed every time even if the refund is equal to 0 or not even requested/needed. Remediation Only transfer if refundAmount > 0 . 3.18 this should be explicitly typecast to address Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/19 Description this is implicitly used as an address, which is forbidden in newer versions of solidity Remediation Every instance of this should now be explicitly typecast to the address type 3.19 Blocking conditions in buyFiat Severity Issue Status GitHub Repo Issue LinkBrickblock_[Phase_2]_Audit-final.md 9/20/2018 15 / 22Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/38 Description There is an edge case where the difference between fundingGoalInCents and fundedAmountInCentsDuringFiatFunding is less than 100, causing this earlier check require(_amountInCents >= 100); to block reaching the funding goal In addition, there is a logical error in the function: Because of the check if (fundingGoalInCents().sub(_newFundedAmount) >= 0) , the second check if (fundedAmountInCentsDuringFiatFunding() >= fundingGoalInCents()) can never be greater than, only less than or equal to. Remediation Though this can be unblocked by moving on to the third stage and funding with Ether, the gas fees to do so will likely be more than the remaining needed funding amount. Possible mitigations include removing the require(_amountInCents >= 100); , validating that fundingGoalInCents % 100 == 0 , or otherwise changing the logical flow. 3.20 Use of ever-growing unsigned integers in PoaToken is dangerous Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/36 Description Just like AccessToken , this contract makes use of unsigned integer variables that can only increase and create an attack surface for DoS attacks, as well as a scalability limitation. Remediation Even though from a very careful analysis we could see that any attack would be hugely costly this presents an opportunity for a possible extension over this token, in the future, to overlook this nature of said variables and for this to become an actual attack vector. Similarly to AccessToken , the results of balanceOf calls could be validated 3.21 Use of ever-growing unsigned integers in AccessToken is dangerous Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/33 DescriptionBrickblock_[Phase_2]_Audit-final.md 9/20/2018 16 / 22In both the balanceOf and distribute functions the math behind makes use of uint256 variables that are ever-growing (can only increase and never decrease, per specification), this creates an attack surface for DoS attacks. Remediation Even though from a very careful analysis we could see that any attack would be hugely costly this presents an opportunity for a possible extension over this token, in the future, to overlook this nature of said variables and for this to become an actual attack vector. The possibility of attack or accidental DOS can be prevented by using the results of balanceOf function in an overflow check uint256 newRecipientBalance = balanceOf(_to).add(_value); uint256 tempSpent = spentBalances[_to]; require(tempSpent.add(newRecipientBalance)); 3.22 Non-optimal stage checking condition in PoaToken Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/34 Description The check of whether PoaToken is in stage 4 is implemented in the startingBalance function which, in turn, is used in the balanceOf function which is transversal to a lot of other functions. Besides creating an extra piece of bytecode that will get executed even in the transferFrom and currentPayout functions, it is buried down in the logic which makes it harder to assess the certainty of the specification: "the token is only tradeable after stage 4". Remediation The use of a modifier on the transfer function alone would achieve the same effect and produce more readable and extensible code. 3.23 Contradicting comment on POAManager Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/24 Description The addToken() function in POAManager has a comment saying it initializes the entity with _active as true but actually sets it false. RemediationBrickblock_[Phase_2]_Audit-final.md 9/20/2018 17 / 22Verify that this is the correct behaviour in code, and correct the comment 3.24 Inconsistent type used for decimals Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/25 Description An inconsistent type is used for decimals. In POAToken uint256 is used, in AccessToken uint8 is used. Remediation Consider which type is preferable for this parameter and use it uniformly throughout all tokens. uint8 is more commonly seen in standards 3.25 Inconsistent event naming Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/26 Description Throughout the contract system - somewhat inconsistent event naming conventions, for example, Burn and BurnEvent event BurnEvent(address indexed burner, uint256 value); event Burn(address indexed burner, uint256 value); Remediation Decide on a naming convention and use it throughout the system. The BurnEvent pattern may be the stronger choice, as it follows the Differentiate functions and events best practice 3.26 Incorrect name of parameter in BBKUnlockedEvent Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/27 Description In AccessToken, wrong variable name, the second uint256 is actually the unlockedAmountBrickblock_[Phase_2]_Audit-final.md 9/20/2018 18 / 22 event BBKUnlockedEvent( address indexed locker, uint256 lockedAmount, uint256 totalLockedAmount ); Remediation Correct the variable name: event BBKUnlockedEvent( address indexed locker, uint256 unlockedAmount, uint256 totalLockedAmount ); 3.27 Usage of EntityState for both brokers and tokens in PoaManager is an anti- separation-of-concerns pattern Severity Issue Status GitHub Repo Issue Link brickblock-audit-report-2issues/32 Description The use of the doesEntityExist modifier and the addEntity , removeEntity , and setEntityActiveValue to manipulate both brokers and tokens in the contract's state is an anti-pattern regarding separation of concerns. Since these functions are reused across two very different domains of logic state, this means that in the unlikely event of a public function related to brokers having a vulnerability there's a non-zero probability that tokens are compromised as well. Given the importance of the prior and latter lists, this is a clear escalation in the severity of a vulnerability. Remediation Create specific functions to handle each one of the different entities (e.g. addToken , removeBroker ) or implement the add, remove and set active logics for each entity in the public functions themselves instead of having shared private functions for that. 4 Tool based analysis The issues from the tool based analysis have been reviewed and the relevant issues have been listed in chapter 3 - Issues. 4.1 MythrilBrickblock_[Phase_2]_Audit-final.md 9/20/2018 19 / 22 Mythril is a security analysis tool for Ethereum smart contracts. It uses concolic analysis to detect various types of issues. The tool was used for automated vulnerability discovery for all audited contracts and libraries. More details on Mythril's current vulnerability coverage can be found here. The raw output of the Mythril vulnerability scan can be found here. It was thoroughly reviewed for possible vulnerabilities, and all the results stemming out of such analysis were included in the final issues report. 4.2 Sūrya Surya is a utility tool for smart contract systems. It provides a number of visual outputs and information about the structure of smart contracts. It also supports querying the function call graph in multiple ways to aid in the manual inspection and control flow analysis of contracts. A complete list of functions with their visibility and modifiers can be found here. 4.3 Odyssey Odyssey is an audit tool that acts as the glue between developers, auditors, and tools. It leverages Github as the platform for building software and aligns to the approach that quality needs to be addressed as early as possible in the development life cycle and small iterative security activities spread out through development help to produce a more secure smart contract system. In its current version Odyssey helps communicate audit issues to development teams better and to close them successfully. Appendix 1 - File Hashes The SHA1 hashes of the source code files in scope of the audit are listed in the table below. Contract File Name SHA1 hash stubs/RemoteContractStub.sol c2da2c57d0502a68acc9cafa134ffb62dfdc8446 stubs/RemoteContractUserStub.sol b4d9811cca3c8c2516d521f315945f18e1ca488c stubs/ExchangeRateProviderStub.solbce06f04ad4ae358e2802198484a95d7091cbdfb stubs/BrokenRemoteContractStub.sol76d0cd9bcb809cd26255fcbf0aca5aae593fdd13 stubs/PoaManagerStub.sol 886dd9d3f890acf7f6cf3c802a02e28dfcb38795 stubs/UpgradedPoa.sol 7ddde558f506efec77488ba958fc1db714d1df4d stubs/BrickblockFountainStub.sol 1fcd2643e33cf0fa76644dd2203b0fa697701ed5 PoaProxy.sol 2359f57c3503608f206195372e220d3673a127f2 PoaManager.sol 0022d2a65065359ef648d05fc1a01b049dd32ff3 ExchangeRates.sol dd4c7a19d798a5a097d12e7fd2146f18705d5e6c tools/WarpTool.sol c2e2f5b46c2382d5919a6a11852d8bd3718ea238Brickblock_[Phase_2]_Audit-final.md 9/20/2018 20 / 22Contract File Name SHA1 hash CustomPOAToken.sol bc8a19f076450c44a8c1cb175626e9ca5b21c712 OraclizeAPI.sol 974d293678647f934864c4eef21469c322e60f19 CentralLogger.sol 63d7facdd2fd969f798b7eef4f3eb89392f817ea FeeManager.sol ba1fa0085716b524424a8b1ba366fde272b03842 BrickblockAccount.sol 2c8cf3c8a6c8ce68044c89afaa1b30e5392f1b0c AccessToken.sol 9ea080dade42bf75787805d87be7aa7d3cdf2f11 Migrations.sol cfc2c3229aa8d50eb038dbdad89b79c10aa76e81 Whitelist.sol 0059355f7b70aefcae1e00293717c5547bf4c9f2 BrickblockToken.sol 1dc072c4a388eb02a8e5ff94e53170266b3986cd PoaToken.sol 7115dd663666c65344d60530cb7f3a1f2439a4a9 ContractRegistry.sol 2bad3f21834b921e00a2c69e70976f49b8f0b828 AccessTokenUpgradeExample.sol 4934bdfbf573caed91b947c4ce33fdd13525759a ExchangeRateProvider.sol 55ae134887bf0ec8b6436dd32026f69f384abf8b interfaces/IWhitelist.sol c1f79ab4dfe09e739142cba10bf5e8cb8c7cae00 interfaces/IAccessToken.sol 86ed15fbf886c084deec249dfb47286cfac1d328 interfaces/IBrickblockToken.sol 98db90ef02f16a9bf2097b7f7cbbdaef74e6c39d interfaces/IPoaToken.sol 0a00f80a0e25d19a9615247ed3f58c79cee592ed interfaces/IExchangeRates.sol 9f27b08adff3d6451689f6f2eaf60e7f79241676 interfaces/IFeeManager.sol cc418992580a2b7e471461c0aa71c554edc44206 interfaces/IRegistry.sol 33620967a81de0ecd2b82356eb8ed2eb1e3523cf interfaces/IExchangeRateProvider.sol 61f0a6d1f06f85f501d755c45f6ab2517a716472 interfaces/IPoaManager.sol 1d09eb035efbf7d087b4e6d60d25480cacf0d1d7 Appendix 2 - Severity A.2.1 - Minor Minor issues are generally subjective or potentially deal with topics like "best practices" or "readability". In general, minor issues do not indicate an actual problem or bug in the code. The maintainers should use their own judgment as to whether addressing these issues improves the codebase. A.2.2 - Medium Medium issues are generally objective but do not represent actual bugs or security problems.Brickblock_[Phase_2]_Audit-final.md 9/20/2018 21 / 22These issues should be addressed unless there is a clear reason not to. A.2.3 - Major Major issues are things like bugs or security vulnerabilities. These issues may not be directly exploitable or may require a certain condition to arise to be exploited. Left unaddressed these issues are highly likely to cause problems with the operation of the contract or lead to a situation which allows the system to be exploited in some way. A.2.4 - Critical Critical issues are directly exploitable bugs or security vulnerabilities. Left unaddressed these issues are highly likely or guaranteed to cause critical problems or potentially a full failure in the operations of the contract. Appendix 3 - 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 other 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 Github account (https://github.com/GNSPS). 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 andBrickblock_[Phase_2]_Audit-final.md 9/20/2018 22 / 22CD 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 endorse 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 assume 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.
Issues Count of Minor/Moderate/Major/Critical - Minor: 25 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.1 Unnecessary complexity in toXLengthString functions in PoaCommon Problem: Unnecessary complexity in toXLengthString functions in PoaCommon Fix: Refactor the toXLengthString functions in PoaCommon 2.2 No plan for how a physical tokenized asset would handle a chain split Problem: No plan for how a physical tokenized asset would handle a chain split Fix: Implement a plan for how a physical tokenized asset would handle a chain split 2.3 Usage of random storage slots in the Proxy adds too much complexity Problem: Usage of random storage slots in the Proxy adds too much complexity Fix: Refactor the Proxy to use deterministic storage slots 2.4 Unnecessary usage of low-level .call() method Problem: Unnecessary usage of low-level .call() method Fix: Refactor the code to use higher-level abstractions 2.5 Withdraw method does not check if balance is sufficient for the withdrawal Issues Count of Minor/Moderate/Major/Critical: 25 Minor 0 Moderate 0 Major 0 Critical Minor Issues: 2.a Problem: Registrar contract uses unstructured storage (code reference: f1f5b04722b9569e1d4c0b62ac4c490c0a785fd88) 2.b Fix: Upgradeable directory of component contracts (code reference: f1f5b04722b9569e1d4c0b62ac4c490c0a785fd88) Moderate: None Major: None Critical: None Observations: The audit focused on the smart contract files and test suites found in the repositories. Conclusion: The audit found 25 minor issues which were addressed by Brickblock through code changes or detailed explanations. Issues Count of Minor/Moderate/Major/Critical - Minor: 3 - Moderate: 3 - Major: 0 - Critical: 0 Minor Issues 2.1 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 2.1 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. 2.2 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 2.2 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. 2.3 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 2.3 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. Moderate 3.1 Problem: ExchangeRateProvider does not check for the existence of the ExchangeRates contract before calling its functions. 3.1 Fix: Added a check to ensure that the ExchangeRates contract exists before calling its functions. 3.2 Problem: ExchangeRateProvider does not check
pragma solidity ^0.5.0; import "./GSNMultiSigWallet.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 GSNMultiSigWalletWithDailyLimit is GSNMultiSigWallet { /* * 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 initialize(address[] memory _owners, uint _required, uint _dailyLimit) public initializer { GSNMultiSigWallet.initialize(_owners, _required); dailyLimit = _dailyLimit; } // constructor(address[] memory _owners, uint _required, uint _dailyLimit) // public // GSNMultiSigWallet(_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; emit 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(_msgSender()) confirmed(transactionId, _msgSender()) 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)) emit Execution(transactionId); else { emit 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 view returns (uint) { if (now > lastDay + 24 hours) return dailyLimit; if (dailyLimit < spentToday) return 0; return dailyLimit - spentToday; } }pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/GSNRecipientERC20Fee.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "./GSNMultiSigWalletWithDailyLimit.sol"; contract GSNMultisigFactory is GSNRecipientERC20Fee, MinterRole, Ownable { address[] deployedWallets; event ContractInstantiation(address sender, address instantiation); function initialize(string memory name, string memory symbol) public initializer { GSNRecipientERC20Fee.initialize(name, symbol); MinterRole.initialize(_msgSender()); Ownable.initialize(_msgSender()); } function mint(address account, uint256 amount) public onlyMinter { _mint(account, amount); } function removeMinter(address account) public onlyOwner { _removeMinter(account); } function getDeployedWallets() public view returns(address[] memory) { return deployedWallets; } function create(address[] memory _owners, uint _required, uint _dailyLimit) public returns (address wallet) { GSNMultiSigWalletWithDailyLimit multisig = new GSNMultiSigWalletWithDailyLimit(); multisig.initialize(_owners, _required, _dailyLimit); wallet = address(multisig); deployedWallets.push(wallet); emit ContractInstantiation(_msgSender(), wallet); } } //SWC-Integer Overflow and Underflow: L1-L429 //SWC-Floating Pragma: L2 pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/GSNRecipient.sol"; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract GSNMultiSigWallet is GSNRecipient { /* * 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(_msgSender() == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(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 != 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() external payable { if (msg.value > 0) emit Deposit(_msgSender(), 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 initialize(address[] memory _owners, uint _required) public initializer validRequirement(_owners.length, _required) { GSNRecipient.initialize(); for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } // constructor(address[] memory _owners, uint _required) public // validRequirement(_owners.length, _required) // { // for (uint 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 (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); 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 (uint 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(uint _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 Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory 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(_msgSender()) transactionExists(transactionId) notConfirmed(transactionId, _msgSender()) { confirmations[transactionId][_msgSender()] = true; emit Confirmation(_msgSender(), transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. //SWC-Transaction Order Dependence: L227-L256 function revokeConfirmation(uint transactionId) public ownerExists(_msgSender()) confirmed(transactionId, _msgSender()) notExecuted(transactionId) { confirmations[transactionId][_msgSender()] = false; emit Revocation(_msgSender(), transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(_msgSender()) confirmed(transactionId, _msgSender()) 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)) emit Execution(transactionId); else { emit 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 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(uint transactionId) public view 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 memory data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit 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 view 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 view 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 view returns (address[] memory) { 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 view returns (address[] memory _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 view returns (uint[] memory _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]; } // accept all requests function acceptRelayedCall( address, address from, bytes calldata, uint256 transactionFee, uint256 gasPrice, uint256, uint256, bytes calldata, uint256 maxPossibleCharge ) external view returns (uint256, bytes memory) { return _approveRelayedCall(abi.encode(from, maxPossibleCharge, transactionFee, gasPrice)); } function _preRelayedCall(bytes memory context) internal returns (bytes32) { } function _postRelayedCall(bytes memory context, bool, uint256 actualCharge, bytes32) internal { } }
April 29th 2020— Quantstamp Verified Multis This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type GSN-enabled Multisig Auditors Kacper Bąk , Senior Research EngineerAlex Murashkin , Senior Software EngineerMartin Derka , Senior Research EngineerTimeline 2019-12-11 through 2020-04-29 EVM Istanbul Languages Solidity, Javascript Methods Architecture Review, Computer-Aided Verification, Manual Review Specification GSN-enabled Multisig Source Code Repository Commit MULTISig 635f670 MULTISig 517c472 Goals Can user's funds get locked up in the contract? •Is upgradeability implemented correctly? •May unauthorized users perform transactions thru the multisig? •Changelog 2019-12-13 - Initial report •2020-01-10 - Reaudit based on commit •517c472 2020-04-24 - Fallback function fix based on commit •de8c6dd 2020-04-29 - Revised report based on commit •54f1694 Overall AssessmentOverall the code is well-written, however, we found a few low-risk issues. We recommend addressing them and/or considering the consequences of ignoring the issues. Furthermore, although our audit focused on the fork diff vs the Gnosis implementation , we reviewed the whole codebase. Furthermore, we assumed that the used OpenZeppelin contracts were audited and, if necessary, fixed. the team has acknowledged or resolved a few of the reported issues. Also, a test suite has been added to the project. Quantstamp confirms that the reported inability of the contract to accept Ether via and under Istanbul EVM is fixed in commit . However, it should be noted that the use of goes against the as this field would be the address of the RelayHub instead of the user. The Multis team considers the consequences of the mismatch in this scenario benign as the address is only used for emitting an event. The change does not appear to have impact on the rest of the contract's functionality, however, the interactions were not subject to the re-audit. Westrongly recommend testing the contracts on Istanbul mainnet to ensure that the contracts work as intended. commit 95d51ae Update: Update: transfer() send() 54f1694 msg.sender recommended API use of GSN network msg.sender Total Issues8 (2 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 3 (0 Resolved)Informational Risk Issues 3 (1 Resolved)Undetermined Risk Issues 2 (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. Summary of Findings ID Description Severity Status QSP- 1 Malicious co-owner may deplete the multisig creator's funds for GSN Low Unresolved QSP- 2 Privileged Roles and Ownership Low Acknowledged QSP- 3 Integer Overflow / Underflow Low Unresolved QSP- 4 Unlocked Pragma Informational Resolved QSP- 5 Race Conditions / Front-Running Informational Acknowledged QSP- 6 Theoretically possible integer overflow Informational Unresolved QSP- 7 Compatibility of the contracts with the Istanbul Ethereum hard fork Undetermined Acknowledged QSP- 8 Malicious user can spam the array deployedWallets Undetermined Resolved 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 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 controlbased 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: • Maian• Mythril• Securify• SlitherSteps taken to run the tools: 1. Installed the Mythril tool from Pypi:pip3 install mythril 2. Ran the Mythril tool on each contract:myth -x path/to/contract 3. Ran the Securify tool:java -Xmx6048m -jar securify-0.1.jar -fs contract.sol 4. Cloned the MAIAN tool:git clone --depth 1 https://github.com/MAIAN-tool/MAIAN.git maian 5. Ran the MAIAN tool on each contract:cd maian/tool/ && python3 maian.py -s path/to/contract contract.sol 6. Installed the Slither tool:pip install slither-analyzer 7. Run Slither from the project directoryslither . Assessment Findings QSP-1 Malicious co-owner may deplete the multisig creator's funds for GSNSeverity: Low Risk Unresolved Status: File(s) affected: GSNMultiSigWallet.sol Current implementation requires trusting that the multisig owners behave well. A malicious co-owner (or when their account gets hacked) could: 1) repeatedly call for random stuff; or 2) just alternate between calling and repeatedly. Consequently, the multisig creator’s balance used for GSN payments could get depleted. It is possible because the function accepts all requests regardless of the cost. Description:submitTransaction() confirmTransaction() revokeConfirmation() acceptRelayedCall() We recommend monitoring the usage of the contract and the balance used for GSN payments. In case of problems, the function may be used to kick out a poorly behaving owner. Recommendation:removeOwner() QSP-2 Privileged Roles and Ownership Severity: Low Risk Acknowledged Status: File(s) affected: GSNMultisigFactory.sol Exploit Scenario: 1. The owner callsfor the only minter that was available as of the initialization time. removeMinter() 2. Although the functionexists, nobody has the minter role, therefore, there is no way to add the minter back and make the contract operational again. addMinter()Privileged Roles and Ownership needs to be made clear to the users, especially because removing the owner and/or minter may lead to a DoS. Depending on the intended use, you may consider removing the function and/or owner altogether. Recommendation:removeMinter() QSP-3 Integer Overflow / Underflow Severity: Low Risk Unresolved Status: File(s) affected: GSNMultiSigWallet.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. Specifically, integer underflow may occur in line 401 in the statement . Description:to - from We recommend checking that >= . Recommendation: to fromQSP-4 Unlocked Pragma Severity: Informational Resolved Status: , , File(s) affected: GSNMultiSigWallet.sol GSNMultiSigWalletWithDailyLimit.sol GSNMultisigFactory.sol Related Issue(s): SWC-103 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-5 Race Conditions / Front-Running Severity: Informational Acknowledged Status: File(s) affected: GSNMultiSigWallet.sol Related Issue(s): SWC-114 A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. Specifically, there is a transaction order dependence (TOD) between the functions and . Description:revokeConfirmation() executeTransaction() We don't have a recommendation as of now, however, we wanted to point out this concern. Recommendation: QSP-6 Theoretically possible integer overflowSeverity: Informational Unresolved Status: File(s) affected: GSNMultiSigWalletWithDailyLimit.sol Related Issue(s): SWC-101 The contract assumes that the daily limit for spent ether is a number that can be represented by due to the type of . Lines 66 and 73 use regular addition and subtraction. If ether supply ever required more than 256 bits to represent it, the contract might need to be redeployed to avoid integer overflow. Description:uint256 spentToday Currently we have no recommendation. As of now, this issue is theoretical, not practical. Recommendation: QSP-7 Compatibility of the contracts with the Istanbul Ethereum hard fork Severity: Undetermined Acknowledged Status: File(s) affected: GSNMultiSigWallet.sol Gas usage is a main concern for smart contract developers and users. The recent hard fork of Ethereum, Istanbul, repriced the gas cost of instructions (see ). The function hardcodes a gas cost constant in line 263. Description:EIP-1679 external_call() 34710 To confirm compatibility of the contract with Istanbul fork, we recommend: 1) creating a test suite, 2) performing manual tests on the mainnet, and 3) performing gas analysis. Recommendation:the team informed us that they are going to add a test suite and perform manual tests on the mainnet to confirm the compatibility. Update: QSP-8 Malicious user can spam the array deployedWallets Severity: Undetermined Resolved Status: File(s) affected: GSNMultisigFactory.sol The factory allows anybody to create a new wallet via the function . Consequently, there is no limit on the number of wallets that can be created. A malicious user could "spam" the array with a large number of empty wallets, which could make the array retrieval a more time-consuming process. Description:create() deployedWallets Currently we have no recommendation since the severity and likelihood of the problem, and consequences are unclear. Recommendation: Automated Analyses Maian MAIAN failed to deploy the contract, and, therefore could not complete the analysis. Mythril Mythril reported the following: integer overflows in , , . We classified them as false positives. • GSNMultiSigWallet.getTransactionIds() SafeMath.add() UINT256_MAX exception states in in , and in in . We classified them as false positives. •address[] public owners; Ownable.sol _transactionIds[i - from] = transactionIdsTemp[i]; GSNMultiSigWallet.sol integer underflow in . It is a true positive. • GSNMultiSigWallet.sol#401 Securify Securify reported the following: locked ether in due to the payable function. We classified it as a false positive since owners may submit a transfer transaction. •GSNMultiSigWallet.sol missing input validation in multiple locations. Upon closer inspection, we classified them as false positives. •Slither Slither reported locked ether in since it has a payable fallback function, but it does not have an explicit function to withdraw the ether. We classified it as a false positive since owners may submit a transfer transaction. GSNMultiSigWalletWithDailyLimitCode Documentation There is no documentation on the order of operations when it comes to creating a new contract, funding the contract, granting tokens to potential multisig creators, etc. Lack of documentation will make it harder for contract users to understand the expected behavior and deployment process. the team has added documentation in . Two remarks: Update: README.md in line 6: "[todo: link to medium blog post about gasless]". We recommend resolving the TODO item.•in line 30: "finaly". We recommend fixing the typo. •Adherence to Best Practices The code adheres to best practices, however, in and : the commented out code should be either removed or annotated that it is a reference implementation. resolved. GSNMultiSigWallet.sol#122GSNMultiSigWalletWithDailyLimit.sol#36 Update: Test Results Test Suite Results The code comes with a test suite. It runs a ganache instance with the arguments and . Specifying contract size and a higher gas limit for running tests does not imply that the mainnet deployment is working. We recommend running ganache with default parameters to make sure the deployment and tests work as expected. --allowUnlimitedContractSize--gasLimit=97219750 GSNMultiSigWallet ✓ Fail execution of transaction (224ms) ✓ Execute transaction (247ms) ✓ Accept relay call (57ms) GSNMultiSigWalletWithDailyLimit ✓ create multisig (57ms) ✓ receive deposits ✓ withdraw below daily limit (185ms) ✓ update daily limit (741ms) ✓ execute various limit scenarios (5904ms) GSNMultisigFactory ✓ Add minter, mint and remove minter (386ms) ✓ Create contract from factory (263ms) ✓ Send money to contract (123ms) ✓ Receive money from contract transfer (118ms) ✓ Update daily limit (361ms) ✓ Add owner (366ms) ✓ Replace owner (587ms) ✓ Remove owner (1665ms) ✓ Revoke confirmation (466ms) ✓ Change requirement (360ms) ✓ Execute transaction (352ms) ✓ Fail execution of transaction (176ms) ✓ Fail execution of transaction below daily limit (655ms) 21 passing (39s) Code Coverage The code features reasonable coverage. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 99.24 81.67 95.12 99.31 DumbTransfer.sol 100 100 100 100 GSNMultiSigWallet.sol 98.91 75 93.33 99.04 413 GSNMultiSigWalletWithDailyLimit.so l 100100 100 100 GSNMultisigFactory.sol 100 100 100 100 All files 99.24 81.67 95.12 99.31 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 40010c40c8b8e8c057d7e1658b3d240374d10e9bd818e0156a97944470e8c974 ./contracts/GSNMultiSigWalletWithDailyLimit.sol 47022d5d2b94a4289be051fe112b4b0c0b0d78e00c882f5019f57776e1582448 ./contracts/DumbTransfer.sol 41286b0c54c4acead151f1664b25fe936bc3762131e2b49c7ca4521a63c4871a ./contracts/GSNMultisigFactory.sol 8877bc69314fcc5aad5dffbe87db3cc7ea7b060a4485c0f8c2e4230fc3a18752 ./contracts/GSNMultiSigWallet.sol Tests b47d33045959c600266892ce564b7e892399acf011a65d612fcc6a9d2bcdd1de ./test/javascript/testGSNMultisigFactory.js 19c07869bb37682a5def7718762f2fc87d2092ca5c14472d2f2434e6e58d734f ./test/javascript/testGSNMultiSigWalletWithDailyLimit.js 3b9bb0abfdf2544581452e73221ec583afb079246e7ffd3afe76e2837d576080 ./test/javascript/utils.js 52efe2c0372bbbae910f97c0aafd49652782c7556bccdf4cf67aef265c1e34e3 ./test/javascript/testGSNMultiSigWallet.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. Multis Audit
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) The use of msg.sender instead of tx.origin in the fallback function (commit de8c6dd). 2.b Fix (one line with code reference) Replace msg.sender with tx.origin in the fallback function (commit 54f1694). Observations •The code is well-written. •The team has acknowledged or resolved a few of the reported issues. •A test suite has been added to the project. •The reported inability of the contract to accept Ether via and under Istanbul EVM is fixed in commit. •The use of msg.sender instead of tx.origin in the fallback function (commit de8c6dd). Conclusion Overall, the code is well-written and the team has acknowledged or resolved a few of the reported issues. We recommend addressing the minor issues and/or considering the consequences of ignoring them. Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations - Change does not appear to have impact on the rest of the contract's functionality - Interactions were not subject to the re-audit - Recommended testing the contracts on Istanbul mainnet - Total Issues 8 (2 Resolved) - High Risk Issues 0 (0 Resolved) - Medium Risk Issues 0 (0 Resolved) - Low Risk Issues 3 (0 Resolved) - Informational Risk Issues 3 (1 Resolved) - Undetermined Risk Issues 2 (1 Resolved) Conclusion The audit report concluded that there were no Minor, Moderate, Major or Critical issues found. However, it is recommended to test the contracts on Istanbul mainnet to ensure that the contracts work as intended. Issues Count of Minor/Moderate/Major/Critical Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues 2.a Problem: Malicious co-owner may deplete the multisig creator's funds for GSN (QSP-1) 2.b Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues: None Major Issues: None Critical Issues: None Observations - Code review included review of specifications, sources, and instructions provided to Quantstamp to understand the size, scope, and functionality of the smart contract. - Manual review of code was done to identify potential vulnerabilities. - Comparison to specification was done to check whether the code does what the specifications, sources, and instructions provided to Quantstamp describe. - Test coverage analysis was done to determine whether the test cases are actually covering the code and how much code is exercised when the test cases are run. - Symbolic execution was done to analyze a program to determine what inputs cause each part of a program to execute. - Best practices review was done to improve efficiency, effectiveness, clarify, maintainability, security, and control
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/vault-interfaces/IFYToken.sol"; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "@yield-protocol/vault-interfaces/DataTypes.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/math/WMul.sol"; import "@yield-protocol/utils-v2/contracts/math/WDiv.sol"; import "@yield-protocol/utils-v2/contracts/math/WDivUp.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastI128U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U32.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256I256.sol"; library CauldronMath { /// @dev Add a number (which might be negative) to a positive, and revert if the result is negative. function add(uint128 x, int128 y) internal pure returns (uint128 z) { require (y > 0 || x >= uint128(-y), "Result below zero"); z = y > 0 ? x + uint128(y) : x - uint128(-y); } } contract Cauldron is AccessControl() { using CauldronMath for uint128; using WMul for uint256; using WDiv for uint256; using WDivUp for uint256; using CastU128I128 for uint128; using CastI128U128 for int128; using CastU256U128 for uint256; using CastU256U32 for uint256; using CastU256I256 for uint256; event AssetAdded(bytes6 indexed assetId, address indexed asset); event SeriesAdded(bytes6 indexed seriesId, bytes6 indexed baseId, address indexed fyToken); event IlkAdded(bytes6 indexed seriesId, bytes6 indexed ilkId); event SpotOracleAdded(bytes6 indexed baseId, bytes6 indexed ilkId, address indexed oracle, uint32 ratio); event RateOracleAdded(bytes6 indexed baseId, address indexed oracle); event DebtLimitsSet(bytes6 indexed baseId, bytes6 indexed ilkId, uint96 max, uint24 min, uint8 dec); event VaultBuilt(bytes12 indexed vaultId, address indexed owner, bytes6 indexed seriesId, bytes6 ilkId); event VaultTweaked(bytes12 indexed vaultId, bytes6 indexed seriesId, bytes6 indexed ilkId); event VaultDestroyed(bytes12 indexed vaultId); event VaultGiven(bytes12 indexed vaultId, address indexed receiver); event VaultPoured(bytes12 indexed vaultId, bytes6 indexed seriesId, bytes6 indexed ilkId, int128 ink, int128 art); event VaultStirred(bytes12 indexed from, bytes12 indexed to, uint128 ink, uint128 art); event VaultRolled(bytes12 indexed vaultId, bytes6 indexed seriesId, uint128 art); event SeriesMatured(bytes6 indexed seriesId, uint256 rateAtMaturity); // ==== Configuration data ==== mapping (bytes6 => address) public assets; // Underlyings and collaterals available in Cauldron. 12 bytes still free. mapping (bytes6 => DataTypes.Series) public series; // Series available in Cauldron. We can possibly use a bytes6 (3e14 possible series). mapping (bytes6 => mapping(bytes6 => bool)) public ilks; // [seriesId][assetId] Assets that are approved as collateral for a series mapping (bytes6 => IOracle) public lendingOracles; // Variable rate lending oracle for an underlying mapping (bytes6 => mapping(bytes6 => DataTypes.SpotOracle)) public spotOracles; // [assetId][assetId] Spot price oracles // ==== Protocol data ==== mapping (bytes6 => mapping(bytes6 => DataTypes.Debt)) public debt; // [baseId][ilkId] Max and sum of debt per underlying and collateral. mapping (bytes6 => uint256) public ratesAtMaturity; // Borrowing rate at maturity for a mature series // ==== User data ==== mapping (bytes12 => DataTypes.Vault) public vaults; // An user can own one or more Vaults, each one with a bytes12 identifier mapping (bytes12 => DataTypes.Balances) public balances; // Both debt and assets // ==== Administration ==== /// @dev Add a new Asset. function addAsset(bytes6 assetId, address asset) external auth { require (assetId != bytes6(0), "Asset id is zero"); require (assets[assetId] == address(0), "Id already used"); assets[assetId] = asset; emit AssetAdded(assetId, address(asset)); } /// @dev Set the maximum and minimum debt for an underlying and ilk pair. Can be reset. function setDebtLimits(bytes6 baseId, bytes6 ilkId, uint96 max, uint24 min, uint8 dec) external auth { require (assets[baseId] != address(0), "Base not found"); require (assets[ilkId] != address(0), "Ilk not found"); DataTypes.Debt memory debt_ = debt[baseId][ilkId]; debt_.max = max; debt_.min = min; debt_.dec = dec; debt[baseId][ilkId] = debt_; emit DebtLimitsSet(baseId, ilkId, max, min, dec); } /// @dev Set a rate oracle. Can be reset. function setLendingOracle(bytes6 baseId, IOracle oracle) external auth { require (assets[baseId] != address(0), "Base not found"); lendingOracles[baseId] = oracle; emit RateOracleAdded(baseId, address(oracle)); } /// @dev Set a spot oracle and its collateralization ratio. Can be reset. function setSpotOracle(bytes6 baseId, bytes6 ilkId, IOracle oracle, uint32 ratio) external auth { require (assets[baseId] != address(0), "Base not found"); require (assets[ilkId] != address(0), "Ilk not found"); spotOracles[baseId][ilkId] = DataTypes.SpotOracle({ oracle: oracle, ratio: ratio // With 6 decimals. 1000000 == 100% }); // Allows to replace an existing oracle. emit SpotOracleAdded(baseId, ilkId, address(oracle), ratio); } /// @dev Add a new series function addSeries(bytes6 seriesId, bytes6 baseId, IFYToken fyToken) external auth { require (seriesId != bytes6(0), "Series id is zero"); address base = assets[baseId]; require (base != address(0), "Base not found"); require (fyToken != IFYToken(address(0)), "Series need a fyToken"); require (fyToken.underlying() == base, "Mismatched series and base"); require (lendingOracles[baseId] != IOracle(address(0)), "Rate oracle not found"); require (series[seriesId].fyToken == IFYToken(address(0)), "Id already used"); series[seriesId] = DataTypes.Series({ fyToken: fyToken, maturity: fyToken.maturity().u32(), baseId: baseId }); emit SeriesAdded(seriesId, baseId, address(fyToken)); } /// @dev Add a new Ilk (approve an asset as collateral for a series). function addIlks(bytes6 seriesId, bytes6[] calldata ilkIds) external auth { DataTypes.Series memory series_ = series[seriesId]; require ( series_.fyToken != IFYToken(address(0)), "Series not found" ); for (uint256 i; i < ilkIds.length; i++) { require ( spotOracles[series_.baseId][ilkIds[i]].oracle != IOracle(address(0)), "Spot oracle not found" ); ilks[seriesId][ilkIds[i]] = true; emit IlkAdded(seriesId, ilkIds[i]); } } // ==== Vault management ==== /// @dev Create a new vault, linked to a series (and therefore underlying) and a collateral function build(address owner, bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external auth returns(DataTypes.Vault memory vault) { require (vaultId != bytes12(0), "Vault id is zero"); require (seriesId != bytes12(0), "Series id is zero"); require (ilkId != bytes12(0), "Ilk id is zero"); require (vaults[vaultId].seriesId == bytes6(0), "Vault already exists"); // Series can't take bytes6(0) as their id require (ilks[seriesId][ilkId] == true, "Ilk not added to series"); vault = DataTypes.Vault({ owner: owner, seriesId: seriesId, ilkId: ilkId }); vaults[vaultId] = vault; emit VaultBuilt(vaultId, owner, seriesId, ilkId); } /// @dev Destroy an empty vault. Used to recover gas costs. function destroy(bytes12 vaultId) external auth { DataTypes.Balances memory balances_ = balances[vaultId]; require (balances_.art == 0 && balances_.ink == 0, "Only empty vaults"); delete vaults[vaultId]; emit VaultDestroyed(vaultId); } /// @dev Change a vault series and/or collateral types. function _tweak(bytes12 vaultId, DataTypes.Vault memory vault) internal { require (vault.seriesId != bytes6(0), "Series id is zero"); require (vault.ilkId != bytes6(0), "Ilk id is zero"); require (ilks[vault.seriesId][vault.ilkId] == true, "Ilk not added to series"); vaults[vaultId] = vault; emit VaultTweaked(vaultId, vault.seriesId, vault.ilkId); } /// @dev Change a vault series and/or collateral types. /// We can change the series if there is no debt, or assets if there are no assets function tweak(bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external auth returns(DataTypes.Vault memory vault) { DataTypes.Balances memory balances_ = balances[vaultId]; vault = vaults[vaultId]; if (seriesId != vault.seriesId) { require (balances_.art == 0, "Only with no debt"); vault.seriesId = seriesId; } if (ilkId != vault.ilkId) { require (balances_.ink == 0, "Only with no collateral"); vault.ilkId = ilkId; } _tweak(vaultId, vault); } /// @dev Transfer a vault to another user. function _give(bytes12 vaultId, address receiver) internal returns(DataTypes.Vault memory vault) { require (vaultId != bytes12(0), "Vault id is zero"); vault = vaults[vaultId]; vault.owner = receiver; vaults[vaultId] = vault; emit VaultGiven(vaultId, receiver); } /// @dev Transfer a vault to another user. function give(bytes12 vaultId, address receiver) external auth returns(DataTypes.Vault memory vault) { vault = _give(vaultId, receiver); } // ==== Asset and debt management ==== function vaultData(bytes12 vaultId, bool getSeries) internal view returns (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) { vault_ = vaults[vaultId]; require (vault_.seriesId != bytes6(0), "Vault not found"); if (getSeries) series_ = series[vault_.seriesId]; balances_ = balances[vaultId]; } /// @dev Convert a debt amount for a series from base to fyToken terms. /// @notice Think about rounding up if using, since we are dividing. function debtFromBase(bytes6 seriesId, uint128 base) external returns (uint128 art) { if (uint32(block.timestamp) >= series[seriesId].maturity) { DataTypes.Series memory series_ = series[seriesId]; art = uint256(base).wdivup(_accrual(seriesId, series_)).u128(); } else { art = base; } } /// @dev Convert a debt amount for a series from fyToken to base terms function debtToBase(bytes6 seriesId, uint128 art) external returns (uint128 base) { if (uint32(block.timestamp) >= series[seriesId].maturity) { DataTypes.Series memory series_ = series[seriesId]; base = uint256(art).wmul(_accrual(seriesId, series_)).u128(); } else { base = art; } } /// @dev Move collateral and debt between vaults. function stir(bytes12 from, bytes12 to, uint128 ink, uint128 art) external auth returns (DataTypes.Balances memory, DataTypes.Balances memory) { require (from != to, "Identical vaults"); (DataTypes.Vault memory vaultFrom, , DataTypes.Balances memory balancesFrom) = vaultData(from, false); (DataTypes.Vault memory vaultTo, , DataTypes.Balances memory balancesTo) = vaultData(to, false); if (ink > 0) { require (vaultFrom.ilkId == vaultTo.ilkId, "Different collateral"); balancesFrom.ink -= ink; balancesTo.ink += ink; } if (art > 0) { require (vaultFrom.seriesId == vaultTo.seriesId, "Different series"); balancesFrom.art -= art; balancesTo.art += art; } balances[from] = balancesFrom; balances[to] = balancesTo; if (ink > 0) require(_level(vaultFrom, balancesFrom, series[vaultFrom.seriesId]) >= 0, "Undercollateralized at origin"); if (art > 0) require(_level(vaultTo, balancesTo, series[vaultTo.seriesId]) >= 0, "Undercollateralized at destination"); emit VaultStirred(from, to, ink, art); return (balancesFrom, balancesTo); } /// @dev Add collateral and borrow from vault, pull assets from and push borrowed asset to user /// Or, repay to vault and remove collateral, pull borrowed asset from and push assets to user function _pour( bytes12 vaultId, DataTypes.Vault memory vault_, DataTypes.Balances memory balances_, DataTypes.Series memory series_, int128 ink, int128 art ) internal returns (DataTypes.Balances memory) { // For now, the collateralization checks are done outside to allow for underwater operation. That might change. if (ink != 0) { balances_.ink = balances_.ink.add(ink); } // Modify vault and global debt records. If debt increases, check global limit. if (art != 0) { DataTypes.Debt memory debt_ = debt[series_.baseId][vault_.ilkId]; balances_.art = balances_.art.add(art); debt_.sum = debt_.sum.add(art); uint128 dust = debt_.min * uint128(10) ** debt_.dec; uint128 line = debt_.max * uint128(10) ** debt_.dec; require (balances_.art == 0 || balances_.art >= dust, "Min debt not reached"); if (art > 0) require (debt_.sum <= line, "Max debt exceeded"); debt[series_.baseId][vault_.ilkId] = debt_; } balances[vaultId] = balances_; emit VaultPoured(vaultId, vault_.seriesId, vault_.ilkId, ink, art); return balances_; } /// @dev Manipulate a vault, ensuring it is collateralized afterwards. /// To be used by debt management contracts. function pour(bytes12 vaultId, int128 ink, int128 art) external auth returns (DataTypes.Balances memory) { (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); balances_ = _pour(vaultId, vault_, balances_, series_, ink, art); if (balances_.art > 0 && (ink < 0 || art > 0)) // If there is debt and we are less safe require(_level(vault_, balances_, series_) >= 0, "Undercollateralized"); return balances_; } /// @dev Give an uncollateralized vault to another user. /// To be used for liquidation engines. function grab(bytes12 vaultId, address receiver) external auth { (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); require(_level(vault_, balances_, series_) < 0, "Not undercollateralized"); _give(vaultId, receiver); } /// @dev Reduce debt and collateral from a vault, ignoring collateralization checks. /// To be used by liquidation engines. function slurp(bytes12 vaultId, uint128 ink, uint128 art) external auth returns (DataTypes.Balances memory) { (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); balances_ = _pour(vaultId, vault_, balances_, series_, -(ink.i128()), -(art.i128())); return balances_; } /// @dev Change series and debt of a vault. /// The module calling this function also needs to buy underlying in the pool for the new series, and sell it in pool for the old series. function roll(bytes12 vaultId, bytes6 newSeriesId, int128 art) external auth returns (DataTypes.Vault memory, DataTypes.Balances memory) { (DataTypes.Vault memory vault_, DataTypes.Series memory oldSeries_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); DataTypes.Series memory newSeries_ = series[newSeriesId]; require (oldSeries_.baseId == newSeries_.baseId, "Mismatched bases in series"); // Change the vault series vault_.seriesId = newSeriesId; _tweak(vaultId, vault_); // Change the vault balances balances_ = _pour(vaultId, vault_, balances_, newSeries_, 0, art); require(_level(vault_, balances_, newSeries_) >= 0, "Undercollateralized"); emit VaultRolled(vaultId, newSeriesId, balances_.art); return (vault_, balances_); } // ==== Accounting ==== /// @dev Return the collateralization level of a vault. It will be negative if undercollateralized. function level(bytes12 vaultId) external returns (int256) { (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); return _level(vault_, balances_, series_); } /// @dev Record the borrowing rate at maturity for a series function mature(bytes6 seriesId) external { require (ratesAtMaturity[seriesId] == 0, "Already matured"); DataTypes.Series memory series_ = series[seriesId]; _mature(seriesId, series_); } /// @dev Record the borrowing rate at maturity for a series function _mature(bytes6 seriesId, DataTypes.Series memory series_) internal { require (uint32(block.timestamp) >= series_.maturity, "Only after maturity"); IOracle rateOracle = lendingOracles[series_.baseId]; (uint256 rateAtMaturity,) = rateOracle.get(series_.baseId, bytes32("rate"), 0); // The value returned is an accumulator, it doesn't need an input amount ratesAtMaturity[seriesId] = rateAtMaturity; emit SeriesMatured(seriesId, rateAtMaturity); } /// @dev Retrieve the rate accrual since maturity, maturing if necessary. function accrual(bytes6 seriesId) external returns (uint256) { DataTypes.Series memory series_ = series[seriesId]; return _accrual(seriesId, series_); } /// @dev Retrieve the rate accrual since maturity, maturing if necessary. /// Note: Call only after checking we are past maturity function _accrual(bytes6 seriesId, DataTypes.Series memory series_) private returns (uint256 accrual_) { uint256 rateAtMaturity = ratesAtMaturity[seriesId]; if (rateAtMaturity == 0) { // After maturity, but rate not yet recorded. Let's record it, and accrual is then 1. _mature(seriesId, series_); } else { IOracle rateOracle = lendingOracles[series_.baseId]; (uint256 rate,) = rateOracle.get(series_.baseId, bytes32("rate"), 0); // The value returned is an accumulator, it doesn't need an input amount accrual_ = rate.wdiv(rateAtMaturity); } accrual_ = accrual_ >= 1e18 ? accrual_ : 1e18; // The accrual can't be below 1 (with 18 decimals) } /// @dev Return the collateralization level of a vault. It will be negative if undercollateralized. function _level( DataTypes.Vault memory vault_, DataTypes.Balances memory balances_, DataTypes.Series memory series_ ) internal returns (int256) { DataTypes.SpotOracle memory spotOracle_ = spotOracles[series_.baseId][vault_.ilkId]; uint256 ratio = uint256(spotOracle_.ratio) * 1e12; // Normalized to 18 decimals (uint256 inkValue,) = spotOracle_.oracle.get(vault_.ilkId, series_.baseId, balances_.ink); // ink * spot if (uint32(block.timestamp) >= series_.maturity) { uint256 accrual_ = _accrual(vault_.seriesId, series_); return inkValue.i256() - uint256(balances_.art).wmul(accrual_).wmul(ratio).i256(); } return inkValue.i256() - uint256(balances_.art).wmul(ratio).i256(); } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "erc3156/contracts/interfaces/IERC3156FlashBorrower.sol"; import "erc3156/contracts/interfaces/IERC3156FlashLender.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/vault-interfaces/IJoinFactory.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/token/TransferHelper.sol"; import "@yield-protocol/utils-v2/contracts/math/WMul.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; contract Join is IJoin, IERC3156FlashLender, AccessControl() { using TransferHelper for IERC20; using WMul for uint256; using CastU256U128 for uint256; event FlashFeeFactorSet(uint256 indexed fee); bytes32 constant internal FLASH_LOAN_RETURN = keccak256("ERC3156FlashBorrower.onFlashLoan"); uint256 constant FLASH_LOANS_DISABLED = type(uint256).max; address public immutable override asset; uint256 public storedBalance; uint256 public flashFeeFactor = FLASH_LOANS_DISABLED; // Fee on flash loans, as a percentage in fixed point with 18 decimals. Flash loans disabled by default. constructor(address asset_) { asset = asset_; } /// @dev Set the flash loan fee factor function setFlashFeeFactor(uint256 flashFeeFactor_) external auth { flashFeeFactor = flashFeeFactor_; emit FlashFeeFactorSet(flashFeeFactor_); } /// @dev Take `amount` `asset` from `user` using `transferFrom`, minus any unaccounted `asset` in this contract. function join(address user, uint128 amount) external override auth returns (uint128) { return _join(user, amount); } /// @dev Take `amount` `asset` from `user` using `transferFrom`, minus any unaccounted `asset` in this contract. function _join(address user, uint128 amount) internal returns (uint128) { IERC20 token = IERC20(asset); uint256 _storedBalance = storedBalance; uint256 available = token.balanceOf(address(this)) - _storedBalance; // Fine to panic if this underflows storedBalance = _storedBalance + amount; unchecked { if (available < amount) token.safeTransferFrom(user, address(this), amount - available); } return amount; } /// @dev Transfer `amount` `asset` to `user` function exit(address user, uint128 amount) external override auth returns (uint128) { return _exit(user, amount); } /// @dev Transfer `amount` `asset` to `user` function _exit(address user, uint128 amount) internal returns (uint128) { IERC20 token = IERC20(asset); storedBalance -= amount; token.safeTransfer(user, amount); return amount; } /// @dev Retrieve any tokens other than the `asset`. Useful for airdropped tokens. function retrieve(IERC20 token, address to) external auth { require(address(token) != address(asset), "Use exit for asset"); token.safeTransfer(to, token.balanceOf(address(this))); } /** * @dev From ERC-3156. The amount of currency available to be lended. * @param token The loan currency. It must be a FYDai contract. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view override returns (uint256) { return token == asset ? storedBalance : 0; } /** * @dev From ERC-3156. The fee to be charged for a given loan. * @param token The loan currency. It must be the asset. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view override returns (uint256) { require(token == asset, "Unsupported currency"); return _flashFee(amount); } /** * @dev The fee to be charged for a given loan. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function _flashFee(uint256 amount) internal view returns (uint256) { return amount.wmul(flashFeeFactor); } /** * @dev From ERC-3156. Loan `amount` `asset` to `receiver`, which needs to return them plus fee to this contract within the same transaction. * If the principal + fee are transferred to this contract, they won't be pulled from the receiver. * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface. * @param token The loan currency. Must be a fyDai contract. * @param amount The amount of tokens lent. * @param data A data parameter to be passed on to the `receiver` for any custom use. */ function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes memory data) external override returns(bool) { require(token == asset, "Unsupported currency"); uint128 _amount = amount.u128(); uint128 _fee = _flashFee(amount).u128(); _exit(address(receiver), _amount); require(receiver.onFlashLoan(msg.sender, token, _amount, _fee, data) == FLASH_LOAN_RETURN, "Non-compliant borrower"); _join(address(receiver), _amount + _fee); return true; } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/vault-interfaces/IFYToken.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/vault-interfaces/ICauldron.sol"; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "@yield-protocol/vault-interfaces/DataTypes.sol"; import "@yield-protocol/yieldspace-interfaces/IPool.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC2612.sol"; import "dss-interfaces/src/dss/DaiAbstract.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/token/TransferHelper.sol"; import "@yield-protocol/utils-v2/contracts/math/WMul.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256I128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol"; import "./LadleStorage.sol"; /// @dev Ladle orchestrates contract calls throughout the Yield Protocol v2 into useful and efficient user oriented features. contract Ladle is LadleStorage, AccessControl() { using WMul for uint256; using CastU256U128 for uint256; using CastU256I128 for uint256; using CastU128I128 for uint128; using TransferHelper for IERC20; using TransferHelper for address payable; constructor (ICauldron cauldron, IWETH9 weth) LadleStorage(cauldron, weth) { } // ---- Data sourcing ---- /// @dev Obtains a vault by vaultId from the Cauldron, and verifies that msg.sender is the owner /// If bytes(0) is passed as the vaultId it tries to load a vault from the cache function getVault(bytes12 vaultId_) internal view returns (bytes12 vaultId, DataTypes.Vault memory vault) { if (vaultId_ == bytes12(0)) { // We use the cache require (cachedVaultId != bytes12(0), "Vault not cached"); vaultId = cachedVaultId; } else { vaultId = vaultId_; } vault = cauldron.vaults(vaultId); require (vault.owner == msg.sender, "Only vault owner"); } /// @dev Obtains a series by seriesId from the Cauldron, and verifies that it exists function getSeries(bytes6 seriesId) internal view returns(DataTypes.Series memory series) { series = cauldron.series(seriesId); require (series.fyToken != IFYToken(address(0)), "Series not found"); } /// @dev Obtains a join by assetId, and verifies that it exists function getJoin(bytes6 assetId) internal view returns(IJoin join) { join = joins[assetId]; require (join != IJoin(address(0)), "Join not found"); } /// @dev Obtains a pool by seriesId, and verifies that it exists function getPool(bytes6 seriesId) internal view returns(IPool pool) { pool = pools[seriesId]; require (pool != IPool(address(0)), "Pool not found"); } // ---- Administration ---- /// @dev Add or remove an integration. function addIntegration(address integration, bool set) external auth { _addIntegration(integration, set); } /// @dev Add or remove an integration. function _addIntegration(address integration, bool set) private { integrations[integration] = set; emit IntegrationAdded(integration, set); } /// @dev Add or remove a token that the Ladle can call `transfer` or `permit` on. function addToken(address token, bool set) external auth { _addToken(token, set); } /// @dev Add or remove a token that the Ladle can call `transfer` or `permit` on. function _addToken(address token, bool set) private { tokens[token] = set; emit TokenAdded(token, set); } /// @dev Add a new Join for an Asset, or replace an existing one for a new one. /// There can be only one Join per Asset. Until a Join is added, no tokens of that Asset can be posted or withdrawn. function addJoin(bytes6 assetId, IJoin join) external auth { address asset = cauldron.assets(assetId); require (asset != address(0), "Asset not found"); require (join.asset() == asset, "Mismatched asset and join"); joins[assetId] = join; bool set = (join != IJoin(address(0))) ? true : false; _addToken(asset, set); // address(0) disables the token emit JoinAdded(assetId, address(join)); } /// @dev Add a new Pool for a Series, or replace an existing one for a new one. /// There can be only one Pool per Series. Until a Pool is added, it is not possible to borrow Base. function addPool(bytes6 seriesId, IPool pool) external auth { IFYToken fyToken = getSeries(seriesId).fyToken; require (fyToken == pool.fyToken(), "Mismatched pool fyToken and series"); require (fyToken.underlying() == address(pool.base()), "Mismatched pool base and series"); pools[seriesId] = pool; bool set = (pool != IPool(address(0))) ? true : false; _addToken(address(fyToken), set); // address(0) disables the token _addToken(address(pool), set); // address(0) disables the token _addIntegration(address(pool), set); // address(0) disables the integration emit PoolAdded(seriesId, address(pool)); } /// @dev Add or remove a module. // SWC-Delegatecall to Untrusted Callee: L145 - L151 function addModule(address module, bool set) external auth { modules[module] = set; emit ModuleAdded(module, set); } /// @dev Set the fee parameter function setFee(uint256 fee) external auth { borrowingFee = fee; emit FeeSet(fee); } // ---- Call management ---- /// @dev Allows batched call to self (this contract). /// @param calls An array of inputs for each call. function batch(bytes[] calldata calls) external payable returns(bytes[] memory results) { results = new bytes[](calls.length); for (uint256 i; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); if (!success) revert(RevertMsgExtractor.getRevertMsg(result)); results[i] = result; } // build would have populated the cache, this deletes it cachedVaultId = bytes12(0); } /// @dev Allow users to route calls to a contract, to be used with batch function route(address integration, bytes calldata data) external payable returns (bytes memory result) { require(integrations[integration], "Unknown integration"); return router.route(integration, data); } // SWC-Delegatecall to Untrusted Callee: L187 - L198 /// @dev Allow users to use functionality coded in a module, to be used with batch /// @notice Modules must not do any changes to the vault (owner, seriesId, ilkId), /// it would be disastrous in combination with batch vault caching function moduleCall(address module, bytes calldata data) external payable returns (bytes memory result) { require (modules[module], "Unregistered module"); bool success; (success, result) = module.delegatecall(data); if (!success) revert(RevertMsgExtractor.getRevertMsg(result)); } // ---- Token management ---- /// @dev Execute an ERC2612 permit for the selected token function forwardPermit(IERC2612 token, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external payable { require(tokens[address(token)], "Unknown token"); token.permit(msg.sender, spender, amount, deadline, v, r, s); } /// @dev Execute a Dai-style permit for the selected token function forwardDaiPermit(DaiAbstract token, address spender, uint256 nonce, uint256 deadline, bool allowed, uint8 v, bytes32 r, bytes32 s) external payable { require(tokens[address(token)], "Unknown token"); token.permit(msg.sender, spender, nonce, deadline, allowed, v, r, s); } /// @dev Allow users to trigger a token transfer from themselves to a receiver through the ladle, to be used with batch function transfer(IERC20 token, address receiver, uint128 wad) external payable { require(tokens[address(token)], "Unknown token"); token.safeTransferFrom(msg.sender, receiver, wad); } /// @dev Retrieve any token in the Ladle function retrieve(IERC20 token, address to) external payable returns (uint256 amount) { require(tokens[address(token)], "Unknown token"); amount = token.balanceOf(address(this)); token.safeTransfer(to, amount); } /// @dev The WETH9 contract will send ether to BorrowProxy on `weth.withdraw` using this function. receive() external payable { require (msg.sender == address(weth), "Only receive from WETH"); } /// @dev Accept Ether, wrap it and forward it to the WethJoin /// This function should be called first in a batch, and the Join should keep track of stored reserves /// Passing the id for a join that doesn't link to a contract implemnting IWETH9 will fail function joinEther(bytes6 etherId) external payable returns (uint256 ethTransferred) { ethTransferred = address(this).balance; IJoin wethJoin = getJoin(etherId); weth.deposit{ value: ethTransferred }(); IERC20(address(weth)).safeTransfer(address(wethJoin), ethTransferred); } /// @dev Unwrap Wrapped Ether held by this Ladle, and send the Ether /// This function should be called last in a batch, and the Ladle should have no reason to keep an WETH balance function exitEther(address payable to) external payable returns (uint256 ethTransferred) { ethTransferred = weth.balanceOf(address(this)); weth.withdraw(ethTransferred); to.safeTransferETH(ethTransferred); } // ---- Vault management ---- /// @dev Generate a vaultId. A keccak256 is cheaper than using a counter with a SSTORE, even accounting for eventual collision retries. function _generateVaultId(uint8 salt) private view returns (bytes12) { return bytes12(keccak256(abi.encodePacked(msg.sender, block.timestamp, salt))); } /// @dev Create a new vault, linked to a series (and therefore underlying) and a collateral function build(bytes6 seriesId, bytes6 ilkId, uint8 salt) external payable returns(bytes12, DataTypes.Vault memory) { return _build(seriesId, ilkId, salt); } /// @dev Create a new vault, linked to a series (and therefore underlying) and a collateral function _build(bytes6 seriesId, bytes6 ilkId, uint8 salt) private returns(bytes12 vaultId, DataTypes.Vault memory vault) { vaultId = _generateVaultId(salt); while (cauldron.vaults(vaultId).seriesId != bytes6(0)) vaultId = _generateVaultId(++salt); // If the vault exists, generate other random vaultId vault = cauldron.build(msg.sender, vaultId, seriesId, ilkId); // Store the vault data in the cache cachedVaultId = vaultId; } /// @dev Change a vault series or collateral. function tweak(bytes12 vaultId_, bytes6 seriesId, bytes6 ilkId) external payable returns(DataTypes.Vault memory vault) { (bytes12 vaultId, ) = getVault(vaultId_); // getVault verifies the ownership as well // tweak checks that the series and the collateral both exist and that the collateral is approved for the series vault = cauldron.tweak(vaultId, seriesId, ilkId); } /// @dev Give a vault to another user. function give(bytes12 vaultId_, address receiver) external payable returns(DataTypes.Vault memory vault) { (bytes12 vaultId, ) = getVault(vaultId_); vault = cauldron.give(vaultId, receiver); } /// @dev Destroy an empty vault. Used to recover gas costs. function destroy(bytes12 vaultId_) external payable { (bytes12 vaultId, ) = getVault(vaultId_); cauldron.destroy(vaultId); } // ---- Asset and debt management ---- /// @dev Move collateral and debt between vaults. function stir(bytes12 from, bytes12 to, uint128 ink, uint128 art) external payable { if (ink > 0) require (cauldron.vaults(from).owner == msg.sender, "Only origin vault owner"); if (art > 0) require (cauldron.vaults(to).owner == msg.sender, "Only destination vault owner"); cauldron.stir(from, to, ink, art); } /// @dev Add collateral and borrow from vault, pull assets from and push borrowed asset to user /// Or, repay to vault and remove collateral, pull borrowed asset from and push assets to user /// Borrow only before maturity. function _pour(bytes12 vaultId, DataTypes.Vault memory vault, address to, int128 ink, int128 art) private { DataTypes.Series memory series; if (art != 0) series = getSeries(vault.seriesId); int128 fee; if (art > 0 && vault.ilkId != series.baseId && borrowingFee != 0) fee = ((series.maturity - block.timestamp) * uint256(int256(art)).wmul(borrowingFee)).i128(); // Update accounting cauldron.pour(vaultId, ink, art + fee); // Manage collateral if (ink != 0) { IJoin ilkJoin = getJoin(vault.ilkId); if (ink > 0) ilkJoin.join(vault.owner, uint128(ink)); if (ink < 0) ilkJoin.exit(to, uint128(-ink)); } // Manage debt tokens if (art != 0) { if (art > 0) series.fyToken.mint(to, uint128(art)); else series.fyToken.burn(msg.sender, uint128(-art)); } } /// @dev Add collateral and borrow from vault, pull assets from and push borrowed asset to user /// Or, repay to vault and remove collateral, pull borrowed asset from and push assets to user /// Borrow only before maturity. function pour(bytes12 vaultId_, address to, int128 ink, int128 art) external payable { (bytes12 vaultId, DataTypes.Vault memory vault) = getVault(vaultId_); _pour(vaultId, vault, to, ink, art); } /// @dev Add collateral and borrow from vault, so that a precise amount of base is obtained by the user. /// The base is obtained by borrowing fyToken and buying base with it in a pool. /// Only before maturity. function serve(bytes12 vaultId_, address to, uint128 ink, uint128 base, uint128 max) external payable returns (uint128 art) { (bytes12 vaultId, DataTypes.Vault memory vault) = getVault(vaultId_); IPool pool = getPool(vault.seriesId); art = pool.buyBasePreview(base); _pour(vaultId, vault, address(pool), ink.i128(), art.i128()); pool.buyBase(to, base, max); } /// @dev Repay vault debt using underlying token at a 1:1 exchange rate, without trading in a pool. /// It can add or remove collateral at the same time. /// The debt to repay is denominated in fyToken, even if the tokens pulled from the user are underlying. /// The debt to repay must be entered as a negative number, as with `pour`. /// Debt cannot be acquired with this function. function close(bytes12 vaultId_, address to, int128 ink, int128 art) external payable returns (uint128 base) { require (art < 0, "Only repay debt"); // When repaying debt in `frob`, art is a negative value. Here is the same for consistency. // Calculate debt in fyToken terms (bytes12 vaultId, DataTypes.Vault memory vault) = getVault(vaultId_); DataTypes.Series memory series = getSeries(vault.seriesId); base = cauldron.debtToBase(vault.seriesId, uint128(-art)); // Update accounting cauldron.pour(vaultId, ink, art); // Manage collateral if (ink != 0) { IJoin ilkJoin = getJoin(vault.ilkId); if (ink > 0) ilkJoin.join(vault.owner, uint128(ink)); if (ink < 0) ilkJoin.exit(to, uint128(-ink)); } // Manage underlying IJoin baseJoin = getJoin(series.baseId); baseJoin.join(msg.sender, base); } /// @dev Repay debt by selling base in a pool and using the resulting fyToken /// The base tokens need to be already in the pool, unaccounted for. /// Only before maturity. After maturity use close. function repay(bytes12 vaultId_, address to, int128 ink, uint128 min) external payable returns (uint128 art) { (bytes12 vaultId, DataTypes.Vault memory vault) = getVault(vaultId_); DataTypes.Series memory series = getSeries(vault.seriesId); IPool pool = getPool(vault.seriesId); art = pool.sellBase(address(series.fyToken), min); _pour(vaultId, vault, to, ink, -(art.i128())); } /// @dev Repay all debt in a vault by buying fyToken from a pool with base. /// The base tokens need to be already in the pool, unaccounted for. The surplus base will be returned to msg.sender. /// Only before maturity. After maturity use close. function repayVault(bytes12 vaultId_, address to, int128 ink, uint128 max) external payable returns (uint128 base) { (bytes12 vaultId, DataTypes.Vault memory vault) = getVault(vaultId_); DataTypes.Series memory series = getSeries(vault.seriesId); IPool pool = getPool(vault.seriesId); DataTypes.Balances memory balances = cauldron.balances(vaultId); base = pool.buyFYToken(address(series.fyToken), balances.art, max); _pour(vaultId, vault, to, ink, -(balances.art.i128())); pool.retrieveBase(msg.sender); } /// @dev Change series and debt of a vault. function roll(bytes12 vaultId_, bytes6 newSeriesId, uint8 loan, uint128 max) external payable returns (DataTypes.Vault memory vault, uint128 newDebt) { bytes12 vaultId; (vaultId, vault) = getVault(vaultId_); DataTypes.Balances memory balances = cauldron.balances(vaultId); DataTypes.Series memory series = getSeries(vault.seriesId); DataTypes.Series memory newSeries = getSeries(newSeriesId); { IPool pool = getPool(newSeriesId); IFYToken fyToken = IFYToken(newSeries.fyToken); IJoin baseJoin = getJoin(series.baseId); // Calculate debt in fyToken terms uint128 base = cauldron.debtToBase(vault.seriesId, balances.art); // Mint fyToken to the pool, as a kind of flash loan fyToken.mint(address(pool), base * loan); // Loan is the size of the flash loan relative to the debt amount, 2 should be safe most of the time // Buy the base required to pay off the debt in series 1, and find out the debt in series 2 newDebt = pool.buyBase(address(baseJoin), base, max); baseJoin.join(address(baseJoin), base); // Repay the old series debt pool.retrieveFYToken(address(fyToken)); // Get the surplus fyToken fyToken.burn(address(fyToken), (base * loan) - newDebt); // Burn the surplus } if (vault.ilkId != newSeries.baseId && borrowingFee != 0) newDebt += ((newSeries.maturity - block.timestamp) * uint256(newDebt).wmul(borrowingFee)).u128(); // Add borrowing fee, also stops users form rolling to a mature series (vault,) = cauldron.roll(vaultId, newSeriesId, newDebt.i128() - balances.art.i128()); // Change the series and debt for the vault return (vault, newDebt); } // ---- Ladle as a token holder ---- /// @dev Use fyToken in the Ladle to repay debt. Return unused fyToken to `to`. function repayFromLadle(bytes12 vaultId_, address to) external payable returns (uint256 repaid) { (bytes12 vaultId, DataTypes.Vault memory vault) = getVault(vaultId_); DataTypes.Series memory series = getSeries(vault.seriesId); DataTypes.Balances memory balances = cauldron.balances(vaultId); uint256 amount = series.fyToken.balanceOf(address(this)); if (amount == 0 || balances.art == 0) return 0; repaid = amount <= balances.art ? amount : balances.art; // Update accounting cauldron.pour(vaultId, 0, -(repaid.i128())); series.fyToken.burn(address(this), repaid); // Return remainder if (repaid < amount) IERC20(address(series.fyToken)).safeTransfer(to, repaid - amount); } /// @dev Use base in the Ladle to repay debt. Return unused base to `to`. function closeFromLadle(bytes12 vaultId_, address to) external payable returns (uint256 repaid) { (bytes12 vaultId, DataTypes.Vault memory vault) = getVault(vaultId_); DataTypes.Series memory series = getSeries(vault.seriesId); DataTypes.Balances memory balances = cauldron.balances(vaultId); IERC20 base = IERC20(cauldron.assets(series.baseId)); uint256 amount = base.balanceOf(address(this)); if (amount == 0 || balances.art == 0) return 0; uint256 debtInBase = cauldron.debtToBase(vault.seriesId, balances.art); uint128 repaidInBase = ((amount <= debtInBase) ? amount : debtInBase).u128(); repaid = (repaidInBase == debtInBase) ? balances.art : cauldron.debtFromBase(vault.seriesId, repaidInBase); // Update accounting cauldron.pour(vaultId, 0, -(repaid.i128())); // Manage underlying IJoin baseJoin = getJoin(series.baseId); base.safeTransfer(address(baseJoin), repaidInBase); baseJoin.join(address(this), repaidInBase); // Return remainder if (repaidInBase < amount) base.safeTransfer(to, repaidInBase - amount); } /// @dev Allow users to redeem fyToken, to be used with batch. /// If 0 is passed as the amount to redeem, it redeems the fyToken balance of the Ladle instead. function redeem(bytes6 seriesId, address to, uint256 wad) external payable returns (uint256) { IFYToken fyToken = getSeries(seriesId).fyToken; return fyToken.redeem(to, wad != 0 ? wad : fyToken.balanceOf(address(this))); } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/vault-interfaces/ILadle.sol"; import "@yield-protocol/vault-interfaces/ICauldron.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/vault-interfaces/DataTypes.sol"; import "@yield-protocol/utils-v2/contracts/math/WMul.sol"; import "@yield-protocol/utils-v2/contracts/math/WDiv.sol"; import "@yield-protocol/utils-v2/contracts/math/WDivUp.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U32.sol"; contract Witch is AccessControl() { using WMul for uint256; using WDiv for uint256; using WDivUp for uint256; using CastU256U128 for uint256; using CastU256U32 for uint256; event Point(bytes32 indexed param, address value); event IlkSet(bytes6 indexed ilkId, uint32 duration, uint64 initialOffer, uint128 dust); event Bought(bytes12 indexed vaultId, address indexed buyer, uint256 ink, uint256 art); event Auctioned(bytes12 indexed vaultId, uint256 indexed start); struct Auction { address owner; uint32 start; } struct Ilk { bool initialized; // Set to true if set, as we might want all parameters set to zero uint32 duration; // Time that auctions take to go to minimal price and stay there. uint64 initialOffer; // Proportion of collateral that is sold at auction start (1e18 = 100%) uint128 dust; // Minimum collateral that must be left when buying, unless buying all } // uint32 public duration = 4 * 60 * 60; // Time that auctions take to go to minimal price and stay there. // uint64 public initialOffer = 5e17; // Proportion of collateral that is sold at auction start (1e18 = 100%) // uint128 public dust; // Minimum collateral that must be left when buying, unless buying all ICauldron immutable public cauldron; ILadle public ladle; mapping(bytes12 => Auction) public auctions; mapping(bytes6 => Ilk) public ilks; constructor (ICauldron cauldron_, ILadle ladle_) { cauldron = cauldron_; ladle = ladle_; } /// @dev Point to a different ladle function point(bytes32 param, address value) external auth { if (param == "ladle") ladle = ILadle(value); else revert("Unrecognized parameter"); emit Point(param, value); } /// @dev Set: /// - the auction duration to calculate liquidation prices /// - the proportion of the collateral that will be sold at auction start /// - the minimum collateral that must be left when buying, unless buying all function setIlk(bytes6 ilkId, uint32 duration, uint64 initialOffer, uint128 dust) external auth { require (initialOffer <= 1e18, "Only at or under 100%"); ilks[ilkId] = Ilk({ initialized: true, duration: duration, initialOffer: initialOffer, dust: dust }); emit IlkSet(ilkId, duration, initialOffer, dust); } /// @dev Put an undercollateralized vault up for liquidation. function auction(bytes12 vaultId) external { require (auctions[vaultId].start == 0, "Vault already under auction"); DataTypes.Vault memory vault = cauldron.vaults(vaultId); auctions[vaultId] = Auction({ owner: vault.owner, start: block.timestamp.u32() }); cauldron.grab(vaultId, address(this)); emit Auctioned(vaultId, block.timestamp.u32()); } /// @dev Pay `base` of the debt in a vault in liquidation, getting at least `min` collateral. function buy(bytes12 vaultId, uint128 base, uint128 min) external returns (uint256 ink) { DataTypes.Balances memory balances_ = cauldron.balances(vaultId); DataTypes.Vault memory vault_ = cauldron.vaults(vaultId); DataTypes.Series memory series_ = cauldron.series(vault_.seriesId); Auction memory auction_ = auctions[vaultId]; Ilk memory ilk_ = ilks[vault_.ilkId]; require (balances_.art > 0, "Nothing to buy"); // Cheapest way of failing gracefully if given a non existing vault uint256 art = cauldron.debtFromBase(vault_.seriesId, base); { uint256 elapsed = uint32(block.timestamp) - auction_.start; // Auctions will malfunction on the 7th of February 2106, at 06:28:16 GMT, we should replace this contract before then. uint256 price = inkPrice(balances_, ilk_.initialOffer, ilk_.duration, elapsed); ink = uint256(art).wmul(price); // Calculate collateral to sell. Using divdrup stops rounding from leaving 1 stray wei in vaults. require (ink >= min, "Not enough bought"); require (ink == balances_.ink || balances_.ink - ink >= ilk_.dust, "Leaves dust"); } cauldron.slurp(vaultId, ink.u128(), art.u128()); // Remove debt and collateral from the vault settle(msg.sender, vault_.ilkId, series_.baseId, ink.u128(), base); // Move the assets if (balances_.art - art == 0) { // If there is no debt left, return the vault with the collateral to the owner cauldron.give(vaultId, auction_.owner); delete auctions[vaultId]; } emit Bought(vaultId, msg.sender, ink, art); } /// @dev Pay all debt from a vault in liquidation, getting at least `min` collateral. function payAll(bytes12 vaultId, uint128 min) external returns (uint256 ink) { DataTypes.Balances memory balances_ = cauldron.balances(vaultId); DataTypes.Vault memory vault_ = cauldron.vaults(vaultId); DataTypes.Series memory series_ = cauldron.series(vault_.seriesId); Auction memory auction_ = auctions[vaultId]; Ilk memory ilk_ = ilks[vault_.ilkId]; require (balances_.art > 0, "Nothing to buy"); // Cheapest way of failing gracefully if given a non existing vault { uint256 elapsed = uint32(block.timestamp) - auction_.start; // Auctions will malfunction on the 7th of February 2106, at 06:28:16 GMT, we should replace this contract before then. uint256 price = inkPrice(balances_, ilk_.initialOffer, ilk_.duration, elapsed); ink = uint256(balances_.art).wmul(price); // Calculate collateral to sell. Using divdrup stops rounding from leaving 1 stray wei in vaults. require (ink >= min, "Not enough bought"); require (ink == balances_.ink || balances_.ink - ink >= ilk_.dust, "Leaves dust"); } cauldron.slurp(vaultId, ink.u128(), balances_.art); // Remove debt and collateral from the vault settle(msg.sender, vault_.ilkId, series_.baseId, ink.u128(), cauldron.debtToBase(vault_.seriesId, balances_.art)); // Move the assets cauldron.give(vaultId, auction_.owner); delete auctions[vaultId]; emit Bought(vaultId, msg.sender, ink, balances_.art); // Still the initially read `art` value, not the updated one } /// @dev Move base from the buyer to the protocol, and collateral from the protocol to the buyer function settle(address user, bytes6 ilkId, bytes6 baseId, uint128 ink, uint128 art) private { if (ink != 0) { // Give collateral to the user IJoin ilkJoin = ladle.joins(ilkId); require (ilkJoin != IJoin(address(0)), "Join not found"); ilkJoin.exit(user, ink); } if (art != 0) { // Take underlying from user IJoin baseJoin = ladle.joins(baseId); require (baseJoin != IJoin(address(0)), "Join not found"); baseJoin.join(user, art); } } /// @dev Price of a collateral unit, in underlying, at the present moment, for a given vault /// ink min(auction, elapsed) /// price = (------- * (p + (1 - p) * -----------------------)) /// art auction function inkPrice(DataTypes.Balances memory balances, uint256 initialOffer_, uint256 duration_, uint256 elapsed) private pure returns (uint256 price) { uint256 term1 = uint256(balances.ink).wdiv(balances.art); uint256 dividend2 = duration_ < elapsed ? duration_ : elapsed; uint256 divisor2 = duration_; uint256 term2 = initialOffer_ + (1e18 - initialOffer_).wmul(dividend2.wdiv(divisor2)); price = term1.wmul(term2); } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/vault-interfaces/IJoinFactory.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "./Join.sol"; /// @dev The JoinFactory creates new join instances. contract JoinFactory is IJoinFactory, AccessControl { /// @dev Deploys a new join. /// @param asset Address of the asset token. /// @return join The join address. function createJoin(address asset) external override auth returns (address) { Join join = new Join(asset); join.grantRole(ROOT, msg.sender); join.renounceRole(ROOT, address(this)); emit JoinCreated(asset, address(join)); return address(join); } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "erc3156/contracts/interfaces/IERC3156FlashBorrower.sol"; import "erc3156/contracts/interfaces/IERC3156FlashLender.sol"; import "@yield-protocol/utils-v2/contracts/token/ERC20Permit.sol"; import "@yield-protocol/utils-v2/contracts/token/SafeERC20Namer.sol"; import "@yield-protocol/vault-interfaces/IFYToken.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/math/WMul.sol"; import "@yield-protocol/utils-v2/contracts/math/WDiv.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U32.sol"; import "./constants/Constants.sol"; contract FYToken is IFYToken, IERC3156FlashLender, AccessControl(), ERC20Permit, Constants { using WMul for uint256; using WDiv for uint256; using CastU256U128 for uint256; using CastU256U32 for uint256; event Point(bytes32 indexed param, address value); event SeriesMatured(uint256 chiAtMaturity); event Redeemed(address indexed from, address indexed to, uint256 amount, uint256 redeemed); uint256 constant CHI_NOT_SET = type(uint256).max; uint256 constant internal MAX_TIME_TO_MATURITY = 126144000; // seconds in four years bytes32 constant internal FLASH_LOAN_RETURN = keccak256("ERC3156FlashBorrower.onFlashLoan"); IOracle public oracle; // Oracle for the savings rate. IJoin public join; // Source of redemption funds. address public immutable override underlying; bytes6 public immutable underlyingId; // Needed to access the oracle uint256 public immutable override maturity; uint256 public chiAtMaturity = CHI_NOT_SET; // Spot price (exchange rate) between the base and an interest accruing token at maturity constructor( bytes6 underlyingId_, IOracle oracle_, // Underlying vs its interest-bearing version IJoin join_, uint256 maturity_, string memory name, string memory symbol ) ERC20Permit(name, symbol, SafeERC20Namer.tokenDecimals(address(IJoin(join_).asset()))) { // The join asset is this fyToken's underlying, from which we inherit the decimals uint256 now_ = block.timestamp; require( maturity_ > now_ && maturity_ < now_ + MAX_TIME_TO_MATURITY && maturity_ < type(uint32).max, "Invalid maturity" ); underlyingId = underlyingId_; join = join_; maturity = maturity_; underlying = address(IJoin(join_).asset()); oracle = oracle_; } modifier afterMaturity() { require( uint32(block.timestamp) >= maturity, "Only after maturity" ); _; } modifier beforeMaturity() { require( uint32(block.timestamp) < maturity, "Only before maturity" ); _; } /// @dev Point to a different Oracle or Join function point(bytes32 param, address value) external auth { if (param == "oracle") oracle = IOracle(value); else if (param == "join") join = IJoin(value); else revert("Unrecognized parameter"); emit Point(param, value); } /// @dev Mature the fyToken by recording the chi. /// If called more than once, it will revert. function mature() external override afterMaturity { require (chiAtMaturity == CHI_NOT_SET, "Already matured"); _mature(); } /// @dev Mature the fyToken by recording the chi. function _mature() private returns (uint256 _chiAtMaturity) { (_chiAtMaturity,) = oracle.get(underlyingId, CHI, 0); // The value returned is an accumulator, it doesn't need an input amount chiAtMaturity = _chiAtMaturity; emit SeriesMatured(_chiAtMaturity); } /// @dev Retrieve the chi accrual since maturity, maturing if necessary. function accrual() external afterMaturity returns (uint256) { return _accrual(); } /// @dev Retrieve the chi accrual since maturity, maturing if necessary. /// Note: Call only after checking we are past maturity function _accrual() private returns (uint256 accrual_) { if (chiAtMaturity == CHI_NOT_SET) { // After maturity, but chi not yet recorded. Let's record it, and accrual is then 1. _mature(); } else { (uint256 chi,) = oracle.get(underlyingId, CHI, 0); // The value returned is an accumulator, it doesn't need an input amount accrual_ = chi.wdiv(chiAtMaturity); } accrual_ = accrual_ >= 1e18 ? accrual_ : 1e18; // The accrual can't be below 1 (with 18 decimals) } /// @dev Burn fyToken after maturity for an amount that increases according to `chi` /// If `amount` is 0, the contract will redeem instead the fyToken balance of this contract. Useful for batches. function redeem(address to, uint256 amount) external override afterMaturity returns (uint256 redeemed) { uint256 amount_ = (amount == 0) ? _balanceOf[address(this)] : amount; _burn(msg.sender, amount_); redeemed = amount_.wmul(_accrual()); join.exit(to, redeemed.u128()); emit Redeemed(msg.sender, to, amount_, redeemed); } /// @dev Mint fyTokens. function mint(address to, uint256 amount) external override beforeMaturity auth { _mint(to, amount); } /// @dev Burn fyTokens. The user needs to have either transferred the tokens to this contract, or have approved this contract to take them. function burn(address from, uint256 amount) external override auth { _burn(from, amount); } /// @dev Burn fyTokens. /// Any tokens locked in this contract will be burned first and subtracted from the amount to burn from the user's wallet. /// This feature allows someone to transfer fyToken to this contract to enable a `burn`, potentially saving the cost of `approve` or `permit`. function _burn(address from, uint256 amount) internal override returns (bool) { // First use any tokens locked in this contract uint256 available = _balanceOf[address(this)]; if (available >= amount) { return super._burn(address(this), amount); } else { if (available > 0 ) super._burn(address(this), available); unchecked { _decreaseAllowance(from, amount - available); } unchecked { return super._burn(from, amount - available); } } } /** * @dev From ERC-3156. The amount of currency available to be lended. * @param token The loan currency. It must be a FYDai contract. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view override beforeMaturity returns (uint256) { return token == address(this) ? type(uint256).max - _totalSupply : 0; } /** * @dev From ERC-3156. The fee to be charged for a given loan. * @param token The loan currency. It must be a FYDai. * param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256) external view override beforeMaturity returns (uint256) { require(token == address(this), "Unsupported currency"); return 0; } /** * @dev From ERC-3156. Loan `amount` fyDai to `receiver`, which needs to return them plus fee to this contract within the same transaction. * Note that if the initiator and the borrower are the same address, no approval is needed for this contract to take the principal + fee from the borrower. * If the borrower transfers the principal + fee to this contract, they will be burnt here instead of pulled from the borrower. * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface. * @param token The loan currency. Must be a fyDai contract. * @param amount The amount of tokens lent. * @param data A data parameter to be passed on to the `receiver` for any custom use. */ function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes memory data) external override beforeMaturity returns(bool) { require(token == address(this), "Unsupported currency"); _mint(address(receiver), amount); require(receiver.onFlashLoan(msg.sender, token, amount, 0, data) == FLASH_LOAN_RETURN, "Non-compliant borrower"); _burn(address(receiver), amount); return true; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/vault-interfaces/IFYTokenFactory.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "./FYToken.sol"; /// @dev The FYTokenFactory creates new FYToken instances. contract FYTokenFactory is IFYTokenFactory, AccessControl { /// @dev Deploys a new fyToken. /// @return fyToken The fyToken address. function createFYToken( bytes6 baseId, IOracle oracle, IJoin baseJoin, uint32 maturity, string calldata name, string calldata symbol ) external override auth returns (address) { FYToken fyToken = new FYToken( baseId, oracle, baseJoin, maturity, name, // Derive from base and maturity, perhaps symbol // Derive from base and maturity, perhaps ); fyToken.grantRole(ROOT, msg.sender); fyToken.renounceRole(ROOT, address(this)); emit FYTokenCreated(address(fyToken), baseJoin.asset(), maturity); return address(fyToken); } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/vault-interfaces/ICauldronGov.sol"; import "@yield-protocol/vault-interfaces/ILadleGov.sol"; // import "@yield-protocol/vault-interfaces/IWitchGov.sol"; import "@yield-protocol/vault-interfaces/IMultiOracleGov.sol"; import "@yield-protocol/vault-interfaces/IJoinFactory.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/vault-interfaces/IFYTokenFactory.sol"; import "@yield-protocol/vault-interfaces/IFYToken.sol"; import "@yield-protocol/vault-interfaces/DataTypes.sol"; import "@yield-protocol/yieldspace-interfaces/IPoolFactory.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "./constants/Constants.sol"; interface IWitchGov { function ilks(bytes6) external view returns(bool, uint32, uint64, uint128); } /// @dev Ladle orchestrates contract calls throughout the Yield Protocol v2 into useful and efficient governance features. contract Wand is AccessControl, Constants { event Point(bytes32 indexed param, address value); bytes4 public constant JOIN = IJoin.join.selector; // bytes4(keccak256("join(address,uint128)")); bytes4 public constant EXIT = IJoin.exit.selector; // bytes4(keccak256("exit(address,uint128)")); bytes4 public constant MINT = IFYToken.mint.selector; // bytes4(keccak256("mint(address,uint256)")); bytes4 public constant BURN = IFYToken.burn.selector; // bytes4(keccak256("burn(address,uint256)")); ICauldronGov public cauldron; ILadleGov public ladle; IWitchGov public witch; IPoolFactory public poolFactory; IJoinFactory public joinFactory; IFYTokenFactory public fyTokenFactory; constructor ( ICauldronGov cauldron_, ILadleGov ladle_, IWitchGov witch_, IPoolFactory poolFactory_, IJoinFactory joinFactory_, IFYTokenFactory fyTokenFactory_ ) { cauldron = cauldron_; ladle = ladle_; witch = witch_; poolFactory = poolFactory_; joinFactory = joinFactory_; fyTokenFactory = fyTokenFactory_; } /// @dev Point to a different cauldron, ladle, witch, poolFactory, joinFactory or fyTokenFactory function point(bytes32 param, address value) external auth { if (param == "cauldron") cauldron = ICauldronGov(value); else if (param == "ladle") ladle = ILadleGov(value); else if (param == "witch") witch = IWitchGov(value); else if (param == "poolFactory") poolFactory = IPoolFactory(value); else if (param == "joinFactory") joinFactory = IJoinFactory(value); else if (param == "fyTokenFactory") fyTokenFactory = IFYTokenFactory(value); else revert("Unrecognized parameter"); emit Point(param, value); } /// @dev Add an existing asset to the protocol, meaning: /// - Add the asset to the cauldron /// - Deploy a new Join, and integrate it with the Ladle /// - If the asset is a base, integrate its rate source /// - If the asset is a base, integrate a spot source and set a debt ceiling for any provided ilks function addAsset( bytes6 assetId, address asset ) external auth { // Add asset to cauldron, deploy new Join, and add it to the ladle require (address(asset) != address(0), "Asset required"); cauldron.addAsset(assetId, asset); AccessControl join = AccessControl(joinFactory.createJoin(asset)); // We need the access control methods of Join bytes4[] memory sigs = new bytes4[](2); sigs[0] = JOIN; sigs[1] = EXIT; join.grantRoles(sigs, address(ladle)); join.grantRole(ROOT, msg.sender); // join.renounceRole(ROOT, address(this)); // Wand requires ongoing rights to set up permissions to joins ladle.addJoin(assetId, address(join)); } /// @dev Make a base asset out of a generic asset. /// @notice `oracle` must be able to deliver a value for assetId and 'rate' function makeBase(bytes6 assetId, IMultiOracleGov oracle) external auth { require (address(oracle) != address(0), "Oracle required"); cauldron.setLendingOracle(assetId, IOracle(address(oracle))); AccessControl baseJoin = AccessControl(address(ladle.joins(assetId))); baseJoin.grantRole(JOIN, address(witch)); // Give the Witch permission to join base } /// @dev Make an ilk asset out of a generic asset. /// @notice `oracle` must be able to deliver a value for baseId and ilkId function makeIlk(bytes6 baseId, bytes6 ilkId, IMultiOracleGov oracle, uint32 ratio, uint96 max, uint24 min, uint8 dec) external auth { require (address(oracle) != address(0), "Oracle required"); (bool ilkInitialized,,,) = witch.ilks(ilkId); require (ilkInitialized == true, "Initialize ilk in Witch"); cauldron.setSpotOracle(baseId, ilkId, IOracle(address(oracle)), ratio); cauldron.setDebtLimits(baseId, ilkId, max, min, dec); AccessControl ilkJoin = AccessControl(address(ladle.joins(ilkId))); ilkJoin.grantRole(EXIT, address(witch)); // Give the Witch permission to exit ilk } /// @dev Add an existing series to the protocol, by deploying a FYToken, and registering it in the cauldron with the approved ilks /// This must be followed by a call to addPool function addSeries( bytes6 seriesId, bytes6 baseId, uint32 maturity, bytes6[] calldata ilkIds, string memory name, string memory symbol ) external auth { address base = cauldron.assets(baseId); require(base != address(0), "Base not found"); IJoin baseJoin = ladle.joins(baseId); require(address(baseJoin) != address(0), "Join not found"); IOracle oracle = cauldron.lendingOracles(baseId); // The lending oracles in the Cauldron are also configured to return chi require(address(oracle) != address(0), "Chi oracle not found"); AccessControl fyToken = AccessControl(fyTokenFactory.createFYToken( baseId, oracle, baseJoin, maturity, name, // Derive from base and maturity, perhaps symbol // Derive from base and maturity, perhaps )); // Allow the fyToken to pull from the base join for redemption bytes4[] memory sigs = new bytes4[](1); sigs[0] = EXIT; AccessControl(address(baseJoin)).grantRoles(sigs, address(fyToken)); // Allow the ladle to issue and cancel fyToken sigs = new bytes4[](2); sigs[0] = MINT; sigs[1] = BURN; fyToken.grantRoles(sigs, address(ladle)); // Pass ownership of the fyToken to msg.sender fyToken.grantRole(ROOT, msg.sender); fyToken.renounceRole(ROOT, address(this)); // Add fyToken/series to the Cauldron and approve ilks for the series cauldron.addSeries(seriesId, baseId, IFYToken(address(fyToken))); cauldron.addIlks(seriesId, ilkIds); // Create the pool for the base and fyToken poolFactory.createPool(base, address(fyToken)); address pool = poolFactory.calculatePoolAddress(base, address(fyToken)); // Register pool in Ladle ladle.addPool(seriesId, address(pool)); } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/utils/RevertMsgExtractor.sol"; import "@yield-protocol/utils-v2/contracts/utils/IsContract.sol"; /// @dev Router forwards calls between two contracts, so that any permissions /// given to the original caller are stripped from the call. /// This is useful when implementing generic call routing functions on contracts /// that might have ERC20 approvals or AccessControl authorizations. contract Router { using IsContract for address; address immutable public owner; constructor () { owner = msg.sender; } /// @dev Allow users to route calls to a pool, to be used with batch function route(address target, bytes calldata data) external payable returns (bytes memory result) { require(msg.sender == owner, "Only owner"); require(target.isContract(), "Target is not a contract"); bool success; (success, result) = target.call(data); if (!success) revert(RevertMsgExtractor.getRevertMsg(result)); } }// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/vault-interfaces/ICauldron.sol"; import "@yield-protocol/vault-interfaces/IJoin.sol"; import "@yield-protocol/yieldspace-interfaces/IPool.sol"; import "@yield-protocol/utils-v2/contracts/interfaces/IWETH9.sol"; import "./Router.sol"; /// @dev Ladle orchestrates contract calls throughout the Yield Protocol v2 into useful and efficient user oriented features. contract LadleStorage { event JoinAdded(bytes6 indexed assetId, address indexed join); event PoolAdded(bytes6 indexed seriesId, address indexed pool); event ModuleAdded(address indexed module, bool indexed set); event IntegrationAdded(address indexed integration, bool indexed set); event TokenAdded(address indexed token, bool indexed set); event FeeSet(uint256 fee); ICauldron public immutable cauldron; Router public immutable router; IWETH9 public immutable weth; uint256 public borrowingFee; bytes12 cachedVaultId; mapping (bytes6 => IJoin) public joins; // Join contracts available to manage assets. The same Join can serve multiple assets (ETH-A, ETH-B, etc...) mapping (bytes6 => IPool) public pools; // Pool contracts available to manage series. 12 bytes still free. mapping (address => bool) public modules; // Trusted contracts to delegatecall anything on. mapping (address => bool) public integrations; // Trusted contracts to call anything on. mapping (address => bool) public tokens; // Trusted contracts to call `transfer` or `permit` on. constructor (ICauldron cauldron_, IWETH9 weth_) { cauldron = cauldron_; router = new Router(); weth = weth_; } }
                Y i e l d V 2   S e c u r i t y A s s e s s me n t October 19, 2021         Prepared for:   Allan Niemerg   Yield Protocol   Alberto Cuesta Cañada   Yield Protocol     Prepared by:   Natalie Chin and Maximilian Krüger         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 Yield V2   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 has been made public at the request of Yield.   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 Yield V2   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   Executive Summary 8   Project Summary 10   Project Targets 11   Project Coverage 12   Codebase Maturity Evaluation 13   Summary of Findings 16   Detailed Findings 18   1. Lack of contract existence check on delegatecall may lead to unexpected   behavior 18   2. Use of delegatecall in a payable function inside a loop 20   3. Lack of two-step process for critical operations 22   4. Risks associated with use of ABIEncoderV2 23   5. Project dependencies contain vulnerabilities 24   6. Witch’s buy and payAll functions allow users to buy collateral from vaults   not undergoing auctions 25   7. Solidity compiler optimizations can be problematic 26   8. Risks associated with EIP-2612 27   9. Failure to use the batched transaction flow may enable theft through   front-running 29   10. Strategy contract’s balance-tracking system could facilitate theft 32   11. Insufficient protection of sensitive keys 34   12. Lack of limits on the total amount of collateral sold at auction 36   13. Lack of incentives for calls to Witch.auction 37     T r a i l o f B i t s 3 Yield V2   C O N F I D E N T I A L     14. Contracts used as dependencies do not track upstream changes 38   15. Cauldron’s give and tweak functions lack vault existence checks 39   16. Problematic approach to data validation and access controls 41   17. isContract may behave unexpectedly 44   18. Use of multiple repositories 45   A. Vulnerability Categories 46   B. Code Maturity Categories 48   C. Token Integration Checklist 50   D. Whitepaper Variable Representations 53   E. Code Quality Recommendations 54   F. Fix Log 57   Detailed Fix Log 59                 T r a i l o f B i t s 4 Yield V2   C O N F I D E N T I A L     E x e c u t i v e S u m m a r y   O v e r v i e w   Yield engaged Trail of Bits to review the security of its Yield protocol V2 smart contracts.   From September 13 to October 1, 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.   S u m m a r y o f F i n d i n g s   Our review resulted in 18 findings, including 5 of high severity and 4 of medium severity.   One of the high-severity issues has a difficulty level of low, which means that an attacker   would not have to overcome significant obstacles to exploit it. The most severe issue stems   from a lack of access controls and could allow any user to liquidate any vault, draining   funds from the protocol for profit.         T r a i l o f B i t s 5 Yield V2   C O N F I D E N T I A L     E X P O S U R E A N A L Y S I S   C A T E G O R Y B R E A K D O W N           T r a i l o f B i t s 6 Yield V2   C O N F I D E N T I A L  Severity   Count   High    5   Medium   4   Low   1   Informational   6   Undetermined   2  Category   Count   Access Controls   1   Data Validation   8   Patching   4   Configuration   2   Undefined Behavior   2   Timing   1     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.guido@trailofbits.com sam.greenup@trailofbits.com   The following engineers were associated with this project:   Maximilian Krüger , Consultant Natalie Chin , Consultant   max.kruger@trailofbits.com natalie.chin@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 13, 2021 Project pre-kickoff call   September 20, 2021 Status update meeting #1   September 27, 2021 Status update meeting #2   October 4, 2021 Delivery of report draft   October 4, 2021 Report readout meeting   October 18, 2021   Fix Log added ( Appendix F )             T r a i l o f B i t s 7 Yield V2   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.   v a u l t - v 2   Repository   https://github.com/yieldprotocol/vault-v2/   Versions  819a713416249da92c44eb629ed26a49425a4656   9b36585830af03e71798fa86ead9ab4d92b6dd7c (for Witch.sol)   Type   Solidity   Platform   Ethereum   y i e l d s p a c e - v 2   Repository   https://github.com/yieldprotocol/yieldspace-v2   Version   36405150567a247e2819c1ec1d35cf0ab666353a   Type   Solidity   Platform   Ethereum   y i e l d - u t i l s - v 2   Repository   https://github.com/yieldprotocol/yield-utils-v2   Version   a5cfe0c95e22e136e32ef85e5eef171b0cb18cd6   Type   Solidity   Platform   Ethereum   s t r a t e g y - v 2   Repository   https://github.com/yieldprotocol/strategy-v2   Version   fef352a339c19d8a4975de327e65874c5c6b3fa7   Type   Solidity   Platform   Ethereum           T r a i l o f B i t s 8 Yield V2   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:   Cauldron . This non-upgradeable contract is the core accounting system of the protocol   and keeps track of features including vaults, series, asset whitelists, and collateral   whitelists. We checked that the functions are implemented correctly, that proper access   controls are in place, and that inputs are validated correctly.   Ladle . Users interact with the protocol primarily by calling Ladle functions batched   together in a “recipe.” The Ladle serves as a gatekeeper and vault manager, enabling users   to create vaults, add liquidity, transfer tokens, and repay debt. We checked the correctness   of the implementation, the fund-transfer process, and the data validation.    Witch . The Witch contract is the liquidation engine of the protocol. It enables users to   start Dutch auctions for the collateral of undercollateralized vaults and to then buy some or   all of the collateral. We checked the implementation of these Dutch auctions, during which   the price of collateral decreases linearly (for the duration of an auction) to a configurable   fraction of the initial price. We also checked whether vaults that are not undercollateralized   can be liquidated and compared the liquidation engine to the MakerDAO Liquidations 2.0   system, which is a very similar system.   Pool . The Pool contract facilitates the exchange of base tokens for wrapped fyTokens by   maintaining the YieldSpace invariant. We reviewed the flow of funds through the contract   and the preconditions of the minting flow and checked whether fyTokens are minted   properly.   Strategy . This contract allows users to exchange their liquidity provider (LP) tokens for   strategy tokens and additional rewards. We checked that strategy tokens can be minted   only when the contract is connected to a pool and that the distribution of rewards adheres   to the expected schedule.    Join . This contract is deployed each time a new asset is added to the protocol and holds   the protocol’s balance of that asset. We reviewed the correctness of the API’s   implementation, the fund-transfer process, and the access controls.   FYToken . This contract implements the fyToken. This synthetic token can be redeemed at   the price of the underlying asset, which is provided by an oracle, upon its maturity date. We   manually reviewed the implementation and its access controls.       T r a i l o f B i t s 9 Yield V2   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.     T r a i l o f B i t s 10 Yield V2   C O N F I D E N T I A L  Category   Summary   Result   Access Controls   and Data   Validation  We identified one high-severity issue stemming from a   lack of proper access controls, which could allow an   attacker to liquidate any vault ( TOB-YP2-006 ). The access   controls also lack sufficient tests, which could have   caught the high-severity issue. Additionally, many   individual functions lack comprehensive access controls   and data validation; instead, the access controls and   data validation for those functions are implemented   only once per call stack ( TOB-YP2-017 ).    The protocol’s contracts are authorized to call only   certain functions on one another, which limits each   contract’s privileges. However, this makes the   correctness of the access controls highly dependent on   the correctness of the deployment; it also means that   the access controls are difficult to verify from the code   alone.  Weak   Arithmetic   Solidity 0.8’s SafeMath is used throughout the project,   and we did not find any arithmetic issues of medium or   high severity. However, the arithmetic is not tested   through fuzzing or symbolic execution, which would help   ensure its correctness. Additionally, the documentation   on the arithmetic would benefit from further detail.  Satisfactory   Assembly   Use/Low-Level   Calls    The contracts use assembly for optimization purposes   but lack comments documenting its use. We identified   two high-severity issues involving the lack of a contract   existence check prior to execution of a delegatecall   ( TOB-YP2-001 ) and the use of a delegatecall in a  Moderate       T r a i l o f B i t s 11 Yield V2   C O N F I D E N T I A L  payable function, which may cause unexpected behavior   ( TOB-YP2-002 ).   Code Stability   The code underwent frequent changes before and   during the audit and will likely continue to evolve.  Moderate   Decentralization   A couple of externally owned accounts held by the Yield   team have near-total control over the protocol, making it   a centralized system that requires trust in a single entity.   However, the Yield team intends to transfer control to a   governance system operating through a timelock   contract, which will reduce the protocol’s centralization.  Weak   Upgradeability   The core accounting contract, the Cauldron , is not   upgradeable. Other contracts, such as the Ladle and   Witch , can be replaced with new versions authorized to   call the Cauldron . We did not find any issues caused by   this database pattern of upgradeability. The protocol   does not use the complex and error-prone   delegatecall pattern of upgradeability.  Satisfactory   Function   Composition  Many of the system’s functionalities, especially its data   validation functionalities, are broken up into multiple   functions in order to save gas. This makes some of the   code less readable and more difficult to modify   ( TOB-YP2-017 ).  Moderate   Front-Running   We found one high-severity issue related to   front-running ( TOB-YP2-009 ). However, time constraints   prevented us from exhaustively checking the protocol   for front-running and unintended arbitrage   opportunities.  Further   Investigation   Required   Monitoring   The Yield Protocol’s functions emit events for critical   operations. Additionally, Yield indicated that it has an   incident response plan, and the protocol uses Tenderly   to monitor on-chain activity.  Satisfactory           T r a i l o f B i t s 12 Yield V2   C O N F I D E N T I A L  Specification   Yield provided its “Syllabus,” “Cookbook,” and   “Deployment” documents, as well as the Yield Protocol   and YieldSpace whitepapers, as documentation.   However, Trail of Bits recommends creating additional   technical documentation that details the optimizations   in the system and the abilities of privileged users; this   documentation should also include architecture   diagrams showing the flow of funds through the system.  Satisfactory   Testing and   Verification  The codebase contains an adequate number of unit   tests. However, it lacks tests for simple access controls,   which could have caught the high-severity issue outlined   in TOB-YP2-006 . The test suite also lacks advanced   testing methods like fuzzing and symbolic execution,   which are required for proper arithmetic testing.  Moderate     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.     T r a i l o f B i t s 13 Yield V2   C O N F I D E N T I A L  ID  Title   Type   Severity   1   Lack of contract existence check on delegatecall may   lead to unexpected behavior  Data   Validation  High   2   Use of delegatecall in a payable function inside a   loop  Data    Validation  High   3   Lack of two-step process for critical operations   Data   Validation  Medium   4   Risks associated with use of ABIEncoderV2   Patching   Undetermined   5   Project dependencies contain vulnerabilities    Patching   Medium   6   Witch’s buy and payAll functions allow users to buy   collateral from vaults not undergoing auctions  Access   Controls  High   7   Solidity compiler optimizations can be problematic   Undefined   Behavior  Informational   8    Risks associated with EIP-2612   Configuration  Informational   9   Failure to use the batched transaction flow may   enable theft through front-running  Data   Validation  High   10  Strategy contract’s balance-tracking system could   facilitate theft  Data   Validation  High   11  Insufficient protection of sensitive keys   Configuration  Medium   12  Lack of limits on the total amount of collateral sold at   auction  Data   Validation  Medium             T r a i l o f B i t s 14 Yield V2   C O N F I D E N T I A L  13  Lack of incentives for calls to Witch.auction   Timing  Undetermined   14  Contracts used as dependencies do not track   upstream changes  Patching  Low   15  Cauldron’s give and tweak functions lack vault   existence checks  Data   Validation  Informational   16  Problematic approach to data validation and access   controls  Data   Validation  Informational   17  isContract may behave unexpectedly   Undefined   Behavior  Informational   18  Use of multiple repositories   Patching   Informational     D e t a i l e d F i n d i n g s     D e s c r i p t i o n   The Ladle contract uses the delegatecall proxy pattern. If the implementation contract   is incorrectly set or is self-destructed, the contract may not detect failed executions.      The Ladle contract implements the batch and moduleCall functions; users invoke the   former to execute batched calls within a single transaction and the latter to make a call to   an external module. Neither function performs a contract existence check prior to   executing a delegatecall . Figure 1.1 shows the moduleCall function.      Figure 1.1: vault-v2/contracts/Ladle.sol#L186-L197     An external module’s address must be registered by an administrator before the function   calls that module.        T r a i l o f B i t s 15 Yield V2   C O N F I D E N T I A L  1 . 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 m a y l e a d t o 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-YP2-001   Target: vault-v2/contracts/Ladle.sol   /// @dev Allow users to use functionality coded in a module, to be used with batch    /// @notice Modules must not do any changes to the vault (owner, seriesId, ilkId),    /// it would be disastrous in combination with batch vault caching    function moduleCall(address module, bytes calldata data)    external payable    returns (bytes memory result)    {    require (modules[module], "Unregistered module");    bool success;    (success, result) = module.delegatecall(data);    if (!success) revert(RevertMsgExtractor.getRevertMsg(result));    } /// @dev Add or remove a module.    function addModule(address module, bool set)    external      Figure 1.2: vault-v2/contracts/Ladle.sol#L143-L150     If the administrator sets the module to an incorrect address or to the address of a contract   that is subsequently destroyed, a delegatecall to it will still return success. This means   that if one call in a batch does not execute any code, it will still appear to have been   successful, rather than causing the entire batch to fail.      The Solidity documentation includes the following warning:      Figure 1.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   Alice, a privileged member of the Yield team, accidentally sets a module to an incorrect   address. Bob, a user, invokes the moduleCall method to execute a batch of calls. Despite   Alice’s mistake, the delegatecall returns success without making any state changes or   executing any code.      R e c o m m e n d a t i o n s   Short term, implement a contract existence check before a delegatecall . Document the   fact that using suicide or selfdestruct can lead to unexpected behavior, and prevent   future upgrades from introducing these functions.      Long term, carefully review the Solidity documentation , especially the “Warnings” section,   and the pitfalls of using the delegatecall proxy pattern.        T r a i l o f B i t s 16 Yield V2   C O N F I D E N T I A L   auth    {    modules[module] = set;    emit ModuleAdded(module, set);    }    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.           D e s c r i p t i o n   The Ladle contract uses the delegatecall proxy pattern (which takes user-provided call   data) in a payable function within a loop. This means that each delegatecall within the   for loop will retain the msg.value of the transaction :      Figure 2.1: vault-v2/contracts/Ladle.sol#L186-L197     The protocol does not currently use the msg.value in any meaningful way. However, if a   future version or refactor of the core protocol introduced a more meaningful use of it, it   could be exploited to tamper with the system arithmetic.     E x p l o i t S c e n a r i o   Alice, a member of the Yield team, adds a new functionality to the core protocol that   adjusts users’ balances according to the msg.value . Eve, an attacker, uses the batching   functionality to increase her ETH balance without actually sending funds from her account,   thereby stealing funds from the system.      T r a i l o f B i t s 17 Yield V2   C O N F I D E N T I A L  2 . U s e o f d e l e g a t e c a l l i n a p a y a b l e f u n c t i o n i n s i d e a l o o p   Severity: High   Difficulty: High   Type: Data Validation   Finding ID: TOB-YP2-002   Target: vault-v2/contracts/Ladle.sol   /// @dev Allows batched call to self (this contract).    /// @param calls An array of inputs for each call.    function batch(bytes[] calldata calls) external payable returns(bytes[] memory   results) {    results = new bytes[](calls.length);    for (uint256 i; i < calls.length; i++) {    (bool success, bytes memory result) = address(this).delegatecall( calls[i] );    if (!success) revert(RevertMsgExtractor.getRevertMsg(result));    results[i] = result;    }       // build would have populated the cache, this deletes it    cachedVaultId = bytes12(0);    }        R e c o m m e n d a t i o n s   Short term, document the risks associated with the use of msg.value and ensure that all   developers are aware of this potential attack vector.     Long term, detail the security implications of all functions in both the documentation and   the code to ensure that potential attack vectors do not become exploitable when code is   refactored or added.     R e f e r e n c e s   ●”Two Rights Might Make a Wrong,” Paradigm             T r a i l o f B i t s 18 Yield V2   C O N F I D E N T I A L         D e s c r i p t i o n   The _give function in the Cauldron contract transfers the ownership of a vault in a single   step. There is no way to reverse a one-step transfer of ownership to an address without an   owner (i.e., an address with a private key not held by any user). This would not be the case   if ownership were transferred through a two-step process in which an owner proposed a   transfer and the prospective recipient accepted it.     Figure 3.1: vault-v2/contracts/Cauldron.sol#L227-L237     E x p l o i t S c e n a r i o   Alice, a Yield Protocol user, transfers ownership of her vault to her friend Bob. When   entering Bob’s address, Alice makes a typo. As a result, the vault is transferred to an   address with no owner, and Alice’s funds are frozen.     R e c o m m e n d a t i o n s   Short term, use a two-step process for ownership transfers. Additionally, consider adding a   zero-value check of the receiver’s address to ensure that vaults cannot be transferred to   the zero address.     Long term, use a two-step process for all irrevocable critical operations.       T r a i l o f B i t s 19 Yield V2   C O N F I D E N T I A L  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 r i t i c a l o p e r a t i o n s   Severity: Medium   Difficulty: High   Type: Data Validation   Finding ID: TOB-YP2-003   Target: vault-v2/contracts/Cauldron.sol   /// @dev Transfer a vault to another user.    function _give(bytes12 vaultId, address receiver)    internal    returns(DataTypes.Vault memory vault)    {    require (vaultId != bytes12(0), "Vault id is zero");    vault = vaults[vaultId];    vault.owner = receiver;    vaults[vaultId] = vault;    emit VaultGiven(vaultId, receiver);    }          D e s c r i p t i o n   The contracts use Solidity’s ABIEncoderV2 , which is enabled by default in Solidity version   0.8. This encoder has caused numerous issues in the past, and its use may still pose risks.     More than 3% of all GitHub issues for the Solidity compiler are related to current or former   experimental features, primarily ABIEncoderV2 , which was long considered experimental.   Several issues and bug reports are still open and unresolved. ABIEncoderV2 has been   associated with more than 20 high-severity bugs , some of which are so recent that they   have not yet been included in a Solidity release.     For example, in March 2019 a severe bug introduced in Solidity 0.5.5 was found in the   encoder.     E x p l o i t S c e n a r i o   The Yield Protocol smart contracts are deployed. After the deployment, a bug is found in   the encoder, which means that the contracts are broken and can all be exploited in the   same way.      R e c o m m e n d a t i o n s   Short term, use neither ABIEncoderV2 nor any experimental Solidity feature. Refactor the   code such that structs do not need to be passed to or returned from functions.      Long term, integrate static analysis tools like Slither into the continuous integration   pipeline to detect unsafe pragmas.        T r a i l o f B i t s 20 Yield V2   C O N F I D E N T I A L  4 . R i s k s a s s o c i a t e d w i t h u s e o f A B I E n c o d e r V 2   Severity: Undetermined   Difficulty: Low   Type: Patching   Finding ID: TOB-YP2-004   Target: Throughout the codebase         D e s c r i p t i o n   Although dependency scans did not yield a direct threat to the project under review, 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.     Figure 5.1: NPM Advisories affecting project dependencies     E x p l o i t S c e n a r i o   Alice installs the dependencies of an 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 21 Yield V2   C O N F I D E N T I A L  5 . 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: Medium   Difficulty: Low   Type: Patching   Finding ID: TOB-YP2-005   Target: package.json   NPM Advisory   Description   Dependency   1674   Arbitrary Code Execution  underscore   1755   Regular Expression Denial of   Service  normalize-url   1770   Arbitrary File Creation/Overwrite   due to insufficient absolute path   sanitization  tar         D e s c r i p t i o n   The buy and payAll functions in the Witch contract enable users to buy collateral at an   auction. However, neither function checks whether there is an active auction for the   collateral of a vault. As a result, anyone can buy collateral from any vault. This issue also   creates an arbitrage opportunity, as the collateral of an overcollateralized vault can be   bought at a below-market price. An attacker could drain vaults of their funds and turn a   profit through repeated arbitrage.     E x p l o i t S c e n a r i o   Alice, a user of the Yield Protocol, opens an overcollateralized vault. Attacker Bob calls   payAll on Alice’s vault. As a result, Alice’s vault is liquidated, and she loses the excess   collateral (the portion that made the vault overcollateralized).     R e c o m m e n d a t i o n s   Short term, ensure that buy and payAll fail if they are called on a vault for which there is   no active auction.     Long term, ensure that all functions revert if the system is in a state in which they are not   allowed to be called.             T r a i l o f B i t s 22 Yield V2   C O N F I D E N T I A L  6 . W i t c h ’ s b u y a n d p a y A l l f u n c t i o n s a l l o w u s e r s t o b u y c o l l a t e r a l f r o m v a u l t s   n o t u n d e r g o i n g a u c t i o n s   Severity: High   Difficulty: Low   Type: Access Controls   Finding ID: TOB-YP2-006   Target: vault-v2/contracts/Witch.sol         D e s c r i p t i o n   The Yield Protocol V2 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 Yield Protocol V2 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 23 Yield V2   C O N F I D E N T I A L  7 . 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-YP2-007   Target: hardhat.config.js         D e s c r i p t i o n   The use of EIP-2612 increases the risk of permit function front-running as well as phishing   attacks.      EIP-2612 uses signatures as an alternative to the traditional approve and transferFrom   flow. These signatures allow a third party to transfer tokens on behalf of a user, with   verification of a signed message.     The use of EIP-2612 makes it possible for an external party to front-run the permit   function by submitting the signature first. Then, since the signature has already been used   and the funds have been transferred, the actual caller's transaction will fail. This could also   affect external contracts that rely on a successful permit() call for execution.      EIP-2612 also makes it easier for an attacker to steal a user’s tokens through phishing by   asking for signatures in a context unrelated to the Yield Protocol contracts. The hash   message may look benign and random to the user.     E x p l o i t S c e n a r i o   Bob has 1,000 iTokens. Eve creates an ERC20 token with a malicious airdrop called   ProofOfSignature . To claim the tokens, participants must sign a hash. Eve generates a   hash to transfer 1,000 iTokens from Bob. Eve asks Bob to sign the hash to get free tokens.   Bob signs the hash, and Eve uses it to steal Bob’s tokens.     R e c o m m e n d a t i o n s   Short term, develop user documentation on edge cases in which the signature-forwarding   process can be front-run or an attacker can steal a user’s tokens via phishing .     Long term, document best practices for Yield Protocol users. In addition to taking other   precautions, users must do the following:     ●Be extremely careful when signing a message    ●Avoid signing messages from suspicious sources     T r a i l o f B i t s 24 Yield V2   C O N F I D E N T I A L  8 . R i s k s a s s o c i a t e d w i t h E I P - 2 6 1 2   Severity: Informational   Difficulty: High   Type: Configuration   Finding ID: TOB-YP2-008   Target: yield-utils-v2     ●Always require hashing schemes to be public      References    ●EIP-2612 Security Considerations         T r a i l o f B i t s 25 Yield V2   C O N F I D E N T I A L         D e s c r i p t i o n   The Yield Protocol relies on users interacting with the Ladle contract to batch their   transactions (e.g., to transfer funds and then mint/burn the corresponding tokens in the   same series of transactions). When they deviate from the batched transaction flow, users   may lose their funds through front-running.     For example, an attacker could front-run the startPool() function to steal the initial mint   of strategy tokens. The function relies on liquidity provider (LP) tokens to be transferred to   the Strategy contract and then used to mint strategy tokens. The first time that strategy   tokens are minted, they are minted directly to the caller:        T r a i l o f B i t s 26 Yield V2   C O N F I D E N T I A L  9 . F a i l u r e t o u s e t h e b a t c h e d t r a n s a c t i o n fl o w m a y e n a b l e t h e f t t h r o u g h   f r o n t - r u n n i n g   Severity: High   Difficulty: Medium   Type: Data Validation   Finding ID: TOB-YP2-009   Target: strategy-v2/contracts/Strategy.sol   /// @dev Start the strategy investments in the next pool    /// @notice When calling this function for the first pool, some underlying needs to   be transferred to the strategy first, using a batchable router.    function startPool()    external    poolNotSelected    {    [...]      // Find pool proportion p = tokenReserves/(tokenReserves + fyTokenReserves)    // Deposit (investment * p) base to borrow (investment * p) fyToken    // (investment * p) fyToken + (investment * (1 - p)) base = investment    // (investment * p) / ((investment * p) + (investment * (1 - p))) = p    // (investment * (1 - p)) / ((investment * p) + (investment * (1 - p))) = 1 -   p       uint256 baseBalance = base.balanceOf(address(this));      Figure 9.1: strategy-v2/contracts/Strategy.sol#L146-L194     E x p l o i t S c e n a r i o   Bob adds underlying tokens to the Strategy contract without using the router.   Governance calls setNextPool() with a new pool address. Eve, an attacker, front-runs the   call to the startPool() function to secure the strategy tokens initially minted for Bob’s   underlying tokens.     R e c o m m e n d a t i o n s   Short term, to limit the impact of function front-running, avoid minting tokens to the callers   of the protocol’s functions.       T r a i l o f B i t s 27 Yield V2   C O N F I D E N T I A L   require(baseBalance > 0, "No funds to start with");       uint256 baseInPool = base.balanceOf(address(pool_));    uint256 fyTokenInPool = fyToken_.balanceOf(address(pool_));       uint256 baseToPool = (baseBalance * baseInPool) / (baseInPool + fyTokenInPool);   // Rounds down    uint256 fyTokenToPool = baseBalance - baseToPool; // fyTokenToPool is   rounded up       // Mint fyToken with underlying    base.safeTransfer(baseJoin, fyTokenToPool);    fyToken.mintWithUnderlying(address(pool_), fyTokenToPool);       // Mint LP tokens with (investment * p) fyToken and (investment * (1 - p)) base    base.safeTransfer(address(pool_), baseToPool);    (,, cached) = pool_.mint(address(this), true, 0); // We don't care about   slippage, because the strategy holds to maturity and profits from sandwiching       if (_totalSupply == 0) _mint(msg.sender, cached); // Initialize the strategy if   needed       invariants[address(pool_)] = pool_.invariant(); // Cache the invariant to   help the frontend calculate profits    emit PoolStarted(address(pool_));    }      Long term, document the expectations around the use of the router to batch transactions;   that way, users will be aware of the front-running risks that arise when it is not used.   Additionally, analyze the implications of all uses of msg.sender in the system, and ensure   that users cannot leverage it to obtain tokens that they do not deserve; otherwise, they   could be incentivized to engage in front-running.           T r a i l o f B i t s 28 Yield V2   C O N F I D E N T I A L         D e s c r i p t i o n   Strategy contract functions use the contract’s balance to determine how many liquidity or   base tokens to provide to a user minting or burning tokens.     The Strategy contract inherits from the ERC20Rewards contract, which defines a reward   token and a reward distribution schedule. An admin must send reward tokens to the   Strategy contract to fund its reward payouts. This flow relies on an underlying   assumption that the reward token will be different from the base token.      Figure 10.1: yield-utils-v2/contracts/token/ERC20Rewards.sol#L58-L67     The burnForBase() function tracks the Strategy contract’s base token balance. If the   base token is used as the reward token, the contract’s base token balance will be inflated to   include the reward token balance (and the balance tracked by the function will be   incorrect). As a result, when attempting to burn strategy tokens, a user may receive more   base tokens than he or she deserves for the number of strategy tokens being burned:        T r a i l o f B i t s 29 Yield V2   C O N F I D E N T I A L  1 0 . S t r a t e g y c o n t r a c t ’ s b a l a n c e - t r a c k i n g s y s t e m c o u l d f a c i l i t a t e t h e f t   Severity: High   Difficulty: Medium   Type: Data Validation   Finding ID: TOB-YP2-010   Target: strategy-v2/contracts/Strategy.sol   /// @dev Set a rewards token.    /// @notice Careful, this can only be done once.    function setRewardsToken(IERC20 rewardsToken_)    external    auth    {    require(rewardsToken == IERC20(address(0)), "Rewards token already set");    rewardsToken = rewardsToken_;    emit RewardsTokenSet(rewardsToken_);    }    /// @dev Burn strategy tokens to withdraw base tokens. It can be called only when a   pool is not selected.      Figure 10.2: strategy-v2/contracts/Strategy.sol#L258-L271     E x p l o i t S c e n a r i o   Bob deploys the Strategy contract; DAI is set as a base token of that contract and is also   defined as the reward token in the ERC20Rewards contract. After a pool has officially been   closed, Eve uses burnWithBase() to swap base tokens for strategy tokens. Because the   calculation takes into account the base token’s balance, she receives more base tokens   than she should.     R e c o m m e n d a t i o n s   Short term, add checks to verify that the reward token is not set to the base token, liquidity   token, fyToken, or strategy token. These checks will ensure that users cannot leverage   contract balances that include reward token balances to turn a profit.      Long term, analyze all token interactions in the contract to ensure they do not introduce   unexpected behavior into the system.        T r a i l o f B i t s 30 Yield V2   C O N F I D E N T I A L   /// @notice The strategy tokens that the user burns need to have been transferred   previously, using a batchable router.    function burnForBase(address to)    external    poolNotSelected    returns (uint256 withdrawal)    {    // strategy * burnt/supply = withdrawal    uint256 burnt = _balanceOf[address(this)];    withdrawal = base.balanceOf(address(this)) * burnt / _totalSupply;       _burn(address(this), burnt);    base.safeTransfer(to, withdrawal);    }          D e s c r i p t i o n   Sensitive information such as Etherscan keys, API keys, and an owner private key used in   testing is stored in the process environment. This method of storage could make it easier   for an attacker to compromise the keys; compromise of the owner key, for example, could   enable an attacker to gain owner privileges and steal funds from the protocol.     The following portion of the hardhat.config.js file uses secrets from the process   environment:      Figure 11.1: vault-v2/hardhat.config.ts#L67-L82       T r a i l o f B i t s 31 Yield V2   C O N F I D E N T I A L  1 1 . I n s u
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 in the smart contract (line 5) 2.b Fix (one line with code reference) - Remove the unused code (line 5) Moderate - None Major - None Critical - None Observations - No critical, major, or moderate issues were found in the smart contract. - Two minor issues were identified. Conclusion - The smart contract is secure and ready for deployment. Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 5 - Major: 2 - Critical: 1 Minor Issues - Problem: Lack of contract existence check on delegatecall may lead to unexpected behavior (18) - Fix: Add a check to ensure that the contract exists before calling delegatecall (18) Moderate Issues - Problem: Use of delegatecall in a payable function inside a loop (20) - Fix: Refactor the code to use a for loop instead of a while loop (20) Major Issues - Problem: Lack of two-step process for critical operations (22) - Fix: Implement a two-step process for critical operations (22) Critical Issues - Problem: Risks associated with use of ABIEncoderV2 (23) - Fix: Refactor the code to use ABIEncoderV1 (23) Observations - The report provides a comprehensive list of security issues, flaws, and defects in the target system or codebase. - The report also provides a code maturity evaluation, summary of findings, detailed findings, vulnerability categories, code maturity categories, token integration checklist Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 4 - Major: 5 - Critical: 0 Minor Issues 2.a Problem: Lack of access controls 2.b Fix: Implement access controls Moderate Issues 3.a Problem: Data validation issues 3.b Fix: Implement data validation Major Issues 4.a Problem: Any user can liquidate any vault 4.b Fix: Implement access controls Critical Issues: None Observations: - Project Scope: Focused on identification of flaws that could result in compromise or lapse of confidentiality, integrity, or availability of the target system - Project Summary: Dan Guido and Sam Greenup were the account and project managers respectively, while Maximilian Krüger and Natalie Chin were the consultants - Project Timeline: Significant events and milestones of the project were listed Conclusion: The security review of Yield protocol V2 smart contracts resulted in 18 findings, including 5 of high severity and 4 of medium severity. Access controls were identified as the main issue, and data validation was identified as the main fix.
// 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; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; library Constants { /// @notice the denominator for basis points granularity (10,000) uint256 public constant BASIS_POINTS_GRANULARITY = 10_000; /// @notice WETH9 address IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice USD stand-in address address public constant USD = 0x1111111111111111111111111111111111111111; }
Fei Protocol v2 Phase 1 Fei Protocol v2 Phase 1 Date Date September 2021 Auditors Auditors Sergii Kravchenko, Heiko Fisch, Eli Leers, Martin Ortner, Bernhard Gomig 1 Executive Summary 1 Executive Summary This report presents the results of our engagement with Fei Protocol Fei Protocol to review Fei v2 Fei v2 Phase 1 Phase 1 . 1.1 Stage 1 1.1 Stage 1 The review was conducted over two weeks, from September 13–24, 2021. A total of 30 person- days were spent. During the first week, the team ramped up on understanding the system and the significant changes that are introduced. These efforts continued into the second week where the team followed up on potential threats to specific components. It should be noted that a two-week engagement is likely not enough for the risk profile and size of the system and that this review is a best effort for the time allotted. Scope Our review focused on the commit hash 5e3e2ab889f06831f4fe2e8460066ded40ccf0a8 . The list of files in scope can be found in the Appendix . 1.2 Stage 2 1.2 Stage 2 The time spent during the first stage of the review was not enough to sufficiently review the system. Because of that, we dedicated one more week with a limited scope to check some of the most critical properties. The main focus of the review was targeted at the launch of the Tribe buyback pipeline. Here are some of the critical risks that we are aming to check: Minting more FEI than it should be by the PCVEquityMinter . Converting FEI to Tribe at a wrong price in the Balancer contract. Locking up or stealing funds directly from one of the contracts.Potential risks that were NOT checked: Incorrect data from the Collateralization oracle. The PCVEquityMinter uses this data to determine the amount of FEI to be minted for the buyback. The main risk is that many FEI tokens will be minted if somebody can attack the system and increase the collateralization rate. The potential attack is mitigated by the fact that there is a cap that limits the maximum amount of minted FEI. We recommend setting this cap to a relatively small amount initially. That will decrease the risk and will help to test the system in practice. Balancer contract malfunction. The Balancer contracts were not in the scope due to the time limits. There may be some potential risk related to the Balancer contracts that we did not check in this review. Scope The second stage of the review was focused on the commit hash ababe68db266922dda927bf756f44b05dc08f873 . The scope was limited to the following contracts: pcv/balancer/* token/PCVEquityMinter.sol token/FeiTimedMinter.sol utils/RateLimitedMinter.sol utils/RateLimited.sol token/IFeiTimedMinter.sol token/IPCVEquityMinter.sol 2 System Overview 2 System Overview The following diagram shows the FEIv2 Phase1 deployment procedure. It outlines from left to right which contracts are instantiated first and whether a contract is initialized with another contracts address. Assuming that if one contract is configured with another contracts address both contracts interact with each other it is possible to derive a high- level interaction diagram that somewhat outlines the flow of data. The purpose of this diagram is to quickly get a high-level understanding of how components may interact with each other. It does not necessarily need to be complete. UniswapPCVDeposit Replacement Contracts dpiUniswapPCVDeposit (ETH) bondingCurve ratioPCVController CollateralizationOracle deposits tokens oracles CollateralizationOracleKeeper init OZ Transparent Proxy CollateralizationOracleWrapper collateralizationOracleWrapperImpl deposits tokens oracles Oracles (Collateralization) ConstantOracle ZERO ConstantOracle ONE chainlinkDaiUSDOracle chainlinkDpiUsdOracle chainlinkEthUsdOracle chainlinkRaiUsdCompositOracle PCV Deposit Contracts PCVDeposit Contracts daiBondingCurveWrapper compoundDaiPCVDepositWrapper raiBondingCurveWrapper ... FEI PCVDeposit Contracts rariPool25FeiPCVDepositWrapper ... creamFeiPCVDepositWrapper staticPcvDepositWrapper chainlinkTribeEthOracleWrapper chainlinkTribeUsdCompositeOracle oracleA oracleB tribeReserveStabilizer tribeOracle backupOracle (NULL) collateralizationOracle tribeSplitter (ERC20Splitter) token (TRIBE) PCVDeposits ratios chainlinkEthUsdOracleWrapper ERC20 Dripper Core CREATE feiTribeLBPSwapper ( BalancerLBSwapper) mainOracle backupOracle (ZERO) tokenSpent (FEI) tokenReceived (TRIBE) tokenReceivingAddress LBP_SLIPPAGE_BPS (100) balancerLBPoolFactory name ( FEI->TRIBE Auction Pool symbol ( apFEI-TRIBE) tokens (FEI,TRIBE) weights (99:1) swapFeePercentage (30) owner swapEnableOnStart (true) feiTribeLBPSwapper ( BalancerLBSwapper) INIT WeightPool PCVEquityMinter target incentive frequency ( 604800) collateralizationOracle aprBasisPoints external constructor init() mint FEI? (timelocked) is FeiTimedMinter mint() afterMint --> feiTribeLBSwapper.swap() Fei v2 setup (v2Phase1) initialization chain grouped by contract type initialization flow from left to right |-->FEI v2 Phase 1 deployment procedure Main Components: PCVDeposits OracleWrapper and Composite Oracles CollateralizationOracle EquityMinter FeiTribeLBSwapper TribeSplitter TribeReserveStabilizer Another incomplete incomplete view on the system is provided with the following diagram that depicts high-level contract interaction and reachable contract interfaces. The diagram is not complete due to time constraints, however, we chose to include it as it might help verify the clients model of the system. ChainlinkOracleWrapper IOracle CoreRef Decimal __constr__
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) The FeiTimedMinter contract does not check the return value of the transferFrom function in the FeiToken contract. (token/FeiTimedMinter.sol:L90) 2.b Fix (one line with code reference) Add a check for the return value of the transferFrom function. (token/FeiTimedMinter.sol:L90) Moderate: 0 Major: 0 Critical: 0 Observations The Fei Protocol v2 Phase 1 system is well designed and implemented. The code is well structured and follows best practices. Conclusion The Fei Protocol v2 Phase 1 system is secure and ready for deployment. No major or critical issues were found during the review. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: - Assuming that if one contract is configured with another contracts address both contracts interact with each other it is possible to derive a high-level interaction diagram that somewhat outlines the flow of data. - A high-level view on the system is provided with the diagram that depicts high-level contract interaction and reachable contract interfaces. Conclusion: No issues were found in the report. The diagram provided gives a high-level view of the system and its contract interactions.
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; /******************************************************************************\ * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import {IDiamondCut} from '../interfaces/IDiamondCut.sol'; import './utils/Storage.sol'; contract DiamondCutFacet is IDiamondCut { /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { PositionManagerStorage.enforceIsGovernance(); PositionManagerStorage.diamondCut(_diamondCut, _init, _calldata); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import './PositionManager.sol'; import '../interfaces/IPositionManagerFactory.sol'; import '../interfaces/IDiamondCut.sol'; contract PositionManagerFactory is IPositionManagerFactory { address public governance; address public diamondCutFacet; address uniswapAddressHolder; address aaveAddressHolder; address public registry; address[] public positionManagers; IDiamondCut.FacetCut[] public actions; mapping(address => address) public override userToPositionManager; ///@notice emitted when a new position manager is created ///@param positionManager address of PositionManager ///@param user address of user event PositionManagerCreated(address indexed positionManager, address user); modifier onlyGovernance() { require(msg.sender == governance, 'PositionManagerFactory::onlyGovernance: Only governance can add actions'); _; } constructor( address _governance, address _registry, address _diamondCutFacet, address _uniswapAddressHolder, address _aaveAddressHolder ) public { governance = _governance; registry = _registry; diamondCutFacet = _diamondCutFacet; uniswapAddressHolder = _uniswapAddressHolder; aaveAddressHolder = _aaveAddressHolder; } ///@notice changes the address of the governance ///@param _governance address of the new governance function changeGovernance(address _governance) external onlyGovernance { governance = _governance; } ///@notice adds a new action to the factory ///@param actionAddress address of the action ///@param selectors action selectors function pushActionData(address actionAddress, bytes4[] calldata selectors) external onlyGovernance { require(actionAddress != address(0), 'PositionManagerFactory::pushActionData: Action address cannot be 0'); actions.push( IDiamondCut.FacetCut({ facetAddress: actionAddress, action: IDiamondCut.FacetCutAction.Add, functionSelectors: selectors }) ); } ///@notice deploy new positionManager and assign to userAddress ///@return address[] return array of PositionManager address updated with the last deployed PositionManager function create() public override returns (address[] memory) { require( userToPositionManager[msg.sender] == address(0), 'PositionManagerFactory::create: User already has a PositionManager' ); PositionManager manager = new PositionManager(msg.sender, diamondCutFacet, registry); positionManagers.push(address(manager)); userToPositionManager[msg.sender] = address(manager); manager.init(msg.sender, uniswapAddressHolder, registry, aaveAddressHolder); bytes memory _calldata; IDiamondCut(address(manager)).diamondCut(actions, 0x0000000000000000000000000000000000000000, _calldata); emit PositionManagerCreated(address(manager), msg.sender); return positionManagers; } ///@notice get all positionManager array of address ///@dev array need to return with a custom function to get all the array ///@return address[] return the array of positionManager // SWC-Code With No Effects: L87-90 function getAllPositionManagers() public view override returns (address[] memory) { return positionManagers; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import '@openzeppelin/contracts/math/SafeMath.sol'; /// @title Locks the registry for a minimum period of time contract Timelock { using SafeMath for uint256; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 6 hours; uint256 public constant MAXIMUM_DELAY = 30 days; uint256 public delay; address public admin; address public pendingAdmin; mapping(address => bool) public pendingAdminAccepted; mapping(bytes32 => bool) public queuedTransactions; constructor(address _admin, uint256 _delay) { 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; } /// @notice Sets the minimum time delay /// @param _delay the new delay function setDelay(uint256 _delay) public onlyAdmin { 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); } /// @notice Sets a new address as pending admin /// @param _pendingAdmin the pending admin function setNewPendingAdmin(address _pendingAdmin) public onlyAdmin { pendingAdmin = _pendingAdmin; pendingAdminAccepted[_pendingAdmin] = false; emit NewPendingAdmin(pendingAdmin); } /// @notice Pending admin accepts its role of new admin function acceptAdminRole() public { require(msg.sender == pendingAdmin, 'Timelock::acceptAdminRole: Call must come from pendingAdmin.'); pendingAdminAccepted[msg.sender] = true; } /// @notice Confirms the pending admin as new admin after he accepted the role function confirmNewAdmin() public onlyAdmin { require( pendingAdminAccepted[pendingAdmin], 'Timelock::confirmNewAdmin: Pending admin must accept admin role first.' ); admin = pendingAdmin; pendingAdmin = address(0); pendingAdminAccepted[pendingAdmin] = false; emit NewAdmin(admin); } /// @notice queues a transaction to be executed after the delay passed /// @param target the target contract address /// @param value the value to be sent /// @param signature the signature of the transaction to be enqueued /// @param data the data of the transaction to be enqueued /// @param eta the minimum timestamp at which the transaction can be executed /// @return the hash of the transaction in bytes function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public onlyAdmin returns (bytes32) { 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; } /// @notice cancels a transaction that has been queued /// @param target the target contract address /// @param value the value to be sent /// @param signature the signature of the transaction to be enqueued /// @param data the data of the transaction to be enqueued /// @param eta the minimum timestamp at which the transaction can be executed function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public onlyAdmin { bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } /// @notice executes a transaction that has been queued /// @param target the target contract address /// @param value the value to be sent /// @param signature the signature of the transaction to be enqueued /// @param data the data of the transaction to be enqueued /// @param eta the minimum timestamp at which the transaction can be executed /// @return the bytes returned by the call method function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable onlyAdmin returns (bytes memory) { 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); } (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; } /// @notice gets the current block timestamp /// @return the current block timestamp function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } /// @notice modifier to check if the sender is the admin modifier onlyAdmin() { require(msg.sender == admin, 'Timelock::onlyAdmin: Call must come from admin.'); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import '../interfaces/IRegistry.sol'; /// @title Stores all the contract addresses contract Registry is IRegistry { address public override governance; address public override positionManagerFactoryAddress; address[] public whitelistedKeepers; mapping(bytes32 => Entry) public modules; bytes32[] public moduleKeys; ///@notice emitted when governance address is changed ///@param newGovernance the new governance address event GovernanceChanged(address newGovernance); ///@notice emitted when a contract is added to registry ///@param newContract address of the new contract ///@param moduleId keccak of module name event ContractCreated(address newContract, bytes32 moduleId); ///@notice emitted when a contract address is updated ///@param oldContract address of the contract before update ///@param newContract address of the contract after update ///@param moduleId keccak of contract name event ContractChanged(address oldContract, address newContract, bytes32 moduleId); ///@notice emitted when a module is switched on/off ///@param moduleId keccak of module name ///@param isActive true if module is switched on, false otherwise event ModuleSwitched(bytes32 moduleId, bool isActive); constructor(address _governance) { governance = _governance; } ///@notice sets the Position manager factory address ///@param _positionManagerFactory the address of the position manager factory function setPositionManagerFactory(address _positionManagerFactory) external onlyGovernance { positionManagerFactoryAddress = _positionManagerFactory; } ///@notice change the address of the governance ///@param _governance the address of the new governance function changeGovernance(address _governance) external onlyGovernance { governance = _governance; emit GovernanceChanged(_governance); } ///@notice Register a contract ///@param _id keccak256 of contract name ///@param _contractAddress address of the new module ///@param _defaultValue default value of the module ///@param _activatedByDefault true if the module is activated by default, false otherwise function addNewContract( bytes32 _id, address _contractAddress, bytes32 _defaultValue, bool _activatedByDefault ) external onlyGovernance { require(modules[_id].contractAddress == address(0), 'Registry::addNewContract: Entry already exists.'); modules[_id] = Entry({ contractAddress: _contractAddress, activated: true, defaultData: _defaultValue, activatedByDefault: _activatedByDefault }); moduleKeys.push(_id); emit ContractCreated(_contractAddress, _id); } ///@notice Changes a module's address ///@param _id keccak256 of module id string ///@param _newContractAddress address of the new module function changeContract(bytes32 _id, address _newContractAddress) external onlyGovernance { require(modules[_id].contractAddress != address(0), 'Registry::changeContract: Entry does not exist.'); //Begin timelock emit ContractChanged(modules[_id].contractAddress, _newContractAddress, _id); modules[_id].contractAddress = _newContractAddress; } ///@notice Toggle global state of a module ///@param _id keccak256 of module id string ///@param _activated boolean to activate or deactivate module function switchModuleState(bytes32 _id, bool _activated) external onlyGovernance { require(modules[_id].contractAddress != address(0), 'Registry::switchModuleState: Entry does not exist.'); modules[_id].activated = _activated; emit ModuleSwitched(_id, _activated); } ///@notice adds a new whitelisted keeper ///@param _keeper address of the new keeper function addKeeperToWhitelist(address _keeper) external override onlyGovernance { require(!isWhitelistedKeeper(_keeper), 'Registry::addKeeperToWhitelist: Keeper is already whitelisted.'); whitelistedKeepers.push(_keeper); } ///@notice Get the keys for all modules ///@return bytes32[] all module keys function getModuleKeys() external view override returns (bytes32[] memory) { return moduleKeys; } ///@notice Set default value for a module ///@param _id keccak256 of module id string ///@param _defaultData default data for the module function setDefaultValue(bytes32 _id, bytes32 _defaultData) external onlyGovernance { require(modules[_id].contractAddress != address(0), 'Registry::setDefaultValue: Entry does not exist.'); modules[_id].defaultData = _defaultData; } ///@notice Set default activation for a module ///@param _id keccak256 of module id string ///@param _activatedByDefault default activation bool for the module function setDefaultActivation(bytes32 _id, bool _activatedByDefault) external onlyGovernance { require(modules[_id].contractAddress != address(0), 'Registry::setDefaultValue: Entry does not exist.'); modules[_id].activatedByDefault = _activatedByDefault; } ///@notice Get the address of a module for a given key ///@param _id keccak256 of module id string ///@return address of the module ///@return bool true if module is activated, false otherwise ///@return bytes memory default data for the module ///@return bool true if module is activated by default, false otherwise function getModuleInfo(bytes32 _id) external view override returns ( address, bool, bytes32, bool ) { return ( modules[_id].contractAddress, modules[_id].activated, modules[_id].defaultData, modules[_id].activatedByDefault ); } ///@notice checks if an address is whitelisted as a keeper ///@param _keeper address to check ///@return bool true if whitelisted, false otherwise function isWhitelistedKeeper(address _keeper) public view override returns (bool) { for (uint256 i = 0; i < whitelistedKeepers.length; i++) { if (whitelistedKeepers[i] == _keeper) { return true; } } return false; } ///@notice modifier to check if the sender is the governance contract modifier onlyGovernance() { require(msg.sender == governance, 'Registry::onlyGovernance: Call must come from governance.'); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/ERC721Holder.sol'; import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol'; import './helpers/ERC20Helper.sol'; import './utils/Storage.sol'; import '../interfaces/IPositionManager.sol'; import '../interfaces/DataTypes.sol'; import '../interfaces/IUniswapAddressHolder.sol'; import '../interfaces/IAaveAddressHolder.sol'; import '../interfaces/IDiamondCut.sol'; import '../interfaces/IRegistry.sol'; import '../interfaces/ILendingPool.sol'; /** * @title Position Manager * @notice A vault that provides liquidity on Uniswap V3. * @notice User can Deposit here its Uni-v3 position * @notice If user does so, he is sure that idle liquidity will always be employed in protocols * @notice User will pay fee to external keepers * @notice vault works for multiple positions */ contract PositionManager is IPositionManager, ERC721Holder { uint256[] private uniswapNFTs; mapping(uint256 => mapping(address => ModuleInfo)) public activatedModules; ///@notice emitted when a position is withdrawn ///@param to address of the user ///@param tokenId ID of the withdrawn NFT event PositionWithdrawn(address to, uint256 tokenId); ///@notice emitted when a ERC20 is withdrawn ///@param tokenAddress address of the ERC20 ///@param to address of the user ///@param amount of the ERC20 event ERC20Withdrawn(address tokenAddress, address to, uint256 amount); ///@notice emitted when a module is activated/deactivated ///@param module address of module ///@param tokenId position on which change is made ///@param isActive true if module is activated, false if deactivated event ModuleStateChanged(address module, uint256 tokenId, bool isActive); ///@notice modifier to check if the msg.sender is the owner modifier onlyOwner() { StorageStruct storage Storage = PositionManagerStorage.getStorage(); require(msg.sender == Storage.owner, 'PositionManager::onlyOwner: Only owner can call this function'); _; } ///@notice modifier to check if the msg.sender is whitelisted modifier onlyWhitelisted() { require( _calledFromRecipe(msg.sender) || _calledFromActiveModule(msg.sender) || msg.sender == address(this), 'PositionManager::fallback: Only whitelisted addresses can call this function' ); _; } ///@notice modifier to check if the msg.sender is the PositionManagerFactory modifier onlyFactory(address _registry) { require( IRegistry(_registry).positionManagerFactoryAddress() == msg.sender, 'PositionManager::init: Only PositionManagerFactory can init this contract' ); _; } ///@notice modifier to check if the position is owned by the positionManager modifier onlyOwnedPosition(uint256 tokenId) { StorageStruct storage Storage = PositionManagerStorage.getStorage(); require( INonfungiblePositionManager(Storage.uniswapAddressHolder.nonfungiblePositionManagerAddress()).ownerOf( tokenId ) == address(this), 'PositionManager::onlyOwnedPosition: positionManager is not owner of the token' ); _; } constructor( address _owner, address _diamondCutFacet, address _registry ) payable onlyFactory(_registry) { PositionManagerStorage.setContractOwner(_owner); // Add the diamondCut external function from the diamondCutFacet IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](1); bytes4[] memory functionSelectors = new bytes4[](1); functionSelectors[0] = IDiamondCut.diamondCut.selector; cut[0] = IDiamondCut.FacetCut({ facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors }); PositionManagerStorage.diamondCut(cut, address(0), ''); } function init( address _owner, address _uniswapAddressHolder, address _registry, address _aaveAddressHolder ) public onlyFactory(_registry) { StorageStruct storage Storage = PositionManagerStorage.getStorage(); Storage.owner = _owner; Storage.uniswapAddressHolder = IUniswapAddressHolder(_uniswapAddressHolder); Storage.registry = IRegistry(_registry); Storage.aaveAddressHolder = IAaveAddressHolder(_aaveAddressHolder); } ///@notice middleware to manage the deposit of the position ///@param tokenId ID of the position function middlewareDeposit(uint256 tokenId) public override onlyOwnedPosition(tokenId) { _setDefaultDataOfPosition(tokenId); pushPositionId(tokenId); } ///@notice remove awareness of tokenId UniswapV3 NFT ///@param tokenId ID of the NFT to remove function removePositionId(uint256 tokenId) public override onlyWhitelisted { for (uint256 i = 0; i < uniswapNFTs.length; i++) { if (uniswapNFTs[i] == tokenId) { if (uniswapNFTs.length > 1) { uniswapNFTs[i] = uniswapNFTs[uniswapNFTs.length - 1]; uniswapNFTs.pop(); } else { delete uniswapNFTs; } return; } } } ///@notice add tokenId in the uniswapNFTs array ///@param tokenId ID of the added NFT function pushPositionId(uint256 tokenId) public override onlyOwnedPosition(tokenId) { uniswapNFTs.push(tokenId); } ///@notice return the IDs of the uniswap positions ///@return array of IDs function getAllUniPositions() external view override returns (uint256[] memory) { uint256[] memory uniswapNFTsMemory = uniswapNFTs; return uniswapNFTsMemory; } ///@notice set default data for every module ///@param tokenId ID of the position function _setDefaultDataOfPosition(uint256 tokenId) internal { StorageStruct storage Storage = PositionManagerStorage.getStorage(); bytes32[] memory moduleKeys = Storage.registry.getModuleKeys(); for (uint32 i = 0; i < moduleKeys.length; i++) { (address moduleAddress, , bytes32 defaultData, bool activatedByDefault) = Storage.registry.getModuleInfo( moduleKeys[i] ); activatedModules[tokenId][moduleAddress].isActive = activatedByDefault; activatedModules[tokenId][moduleAddress].data = defaultData; } } ///@notice toggle module state, activated (true) or not (false) ///@param tokenId ID of the NFT ///@param moduleAddress address of the module ///@param activated state of the module function toggleModule( uint256 tokenId, address moduleAddress, bool activated ) external override onlyOwner onlyOwnedPosition(tokenId) { activatedModules[tokenId][moduleAddress].isActive = activated; emit ModuleStateChanged(moduleAddress, tokenId, activated); } ///@notice sets the data of a module strategy for tokenId position ///@param tokenId ID of the position ///@param moduleAddress address of the module ///@param data data for the module function setModuleData( uint256 tokenId, address moduleAddress, bytes32 data ) external override onlyOwner onlyOwnedPosition(tokenId) { uint256 moduleData = uint256(data); require(moduleData > 0, 'PositionManager::setModuleData: moduleData must be greater than 0%'); activatedModules[tokenId][moduleAddress].data = data; } ///@notice get info for a module strategy for tokenId position ///@param _tokenId ID of the position ///@param _moduleAddress address of the module ///@return isActive is module activated ///@return data of the module function getModuleInfo(uint256 _tokenId, address _moduleAddress) external view override returns (bool isActive, bytes32 data) { return (activatedModules[_tokenId][_moduleAddress].isActive, activatedModules[_tokenId][_moduleAddress].data); } ///@notice stores old position data when liquidity is moved to aave ///@param token address of the token ///@param id ID of the position ///@param tokenId of the position function pushTokenIdToAave( address token, uint256 id, uint256 tokenId ) public override onlyWhitelisted { StorageStruct storage Storage = PositionManagerStorage.getStorage(); require( Storage.aaveUserReserves[token].positionShares[id] > 0, 'PositionManager::pushOldPositionData: positionShares does not exist' ); Storage.aaveUserReserves[token].tokenIds[id] = tokenId; } ///@notice returns the old position data of an aave position ///@param token address of the token ///@param id ID of aave position ///@return tokenId of the position function getTokenIdFromAavePosition(address token, uint256 id) public view override onlyWhitelisted returns (uint256) { StorageStruct storage Storage = PositionManagerStorage.getStorage(); require( Storage.aaveUserReserves[token].positionShares[id] > 0, 'PositionManager::getOldPositionData: positionShares does not exist' ); return Storage.aaveUserReserves[token].tokenIds[id]; } ///@notice return the address of this position manager owner ///@return address of the owner function getOwner() external view override returns (address) { StorageStruct storage Storage = PositionManagerStorage.getStorage(); return Storage.owner; } ///@notice return the all tokens of tokenAddress in the positionManager ///@param tokenAddress address of the token to be withdrawn function withdrawERC20(address tokenAddress) external override onlyOwner { ERC20Helper._approveToken(tokenAddress, address(this), 2**256 - 1); uint256 amount = ERC20Helper._withdrawTokens(tokenAddress, msg.sender, 2**256 - 1); emit ERC20Withdrawn(tokenAddress, msg.sender, amount); } ///@notice function to check if an address corresponds to an active module (or this contract) ///@param _address input address ///@return isCalledFromActiveModule boolean function _calledFromActiveModule(address _address) internal view returns (bool isCalledFromActiveModule) { StorageStruct storage Storage = PositionManagerStorage.getStorage(); bytes32[] memory keys = Storage.registry.getModuleKeys(); for (uint256 i = 0; i < keys.length; i++) { (address moduleAddress, bool isActive, , ) = Storage.registry.getModuleInfo(keys[i]); if (moduleAddress == _address && isActive == true) { isCalledFromActiveModule = true; break; } } } function _calledFromRecipe(address _address) internal view returns (bool isCalledFromRecipe) { StorageStruct storage Storage = PositionManagerStorage.getStorage(); bytes32[] memory recipeKeys = PositionManagerStorage.getRecipesKeys(); for (uint256 i = 0; i < recipeKeys.length; i++) { (address moduleAddress, , , ) = Storage.registry.getModuleInfo(recipeKeys[i]); if (moduleAddress == _address) { isCalledFromRecipe = true; break; } } } fallback() external payable onlyWhitelisted { StorageStruct storage Storage; bytes32 position = PositionManagerStorage.key; ///@dev get diamond storage position assembly { Storage.slot := position } address facet = Storage.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), 'PositionManager::Fallback: Function does not exist'); ///@dev Execute external function from facet using delegatecall and return any value. assembly { // copy function selector and any arguments calldatacopy(0, 0, calldatasize()) // execute function call using the facet let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) // get any return value returndatacopy(0, 0, returndatasize()) // return any return value or error back to the caller switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable { revert(); //we need to decide what to do when the contract receives ether //for now we just revert } }
Orbit DeFi May 29, 2022 1. Preface The developers of Orbit DeFi contracted byterocket to conduct a smart contract audit of their token contract suite. Orbit is “ a DeFi smart vault Optimizer that automates and rebalances your LP strategies effortlessly, starting with Uniswap V3 ”. The team of byterocket reviewed and audited the above smart contracts in the course of this audit. We started on the 6th of May and finished on the 29th of May 2022. The audit included the following services: Manual Multi-Pass Code Review Protocol/Logic Analysis Automated Code Review Formal Report byterocket gained access to the code via a public GitHub repository . We based the audit on the main branch’s state on May 12th, 2022 ( commit hash 541460999b7d8fa80c4a4a86383f583392436b67 ). The updated version was provided to us via multiple new commits to the repository, addressing our findings. The last and most recent commit hash that we audited is 3c6ed8c356be28b2e059a2a7f0171ba31f216bb7 . 2. Manual Code Review We conducted a manual multi-pass code review of the smart contracts mentioned in section (1). Three different people went through the smart contract independently and compared their results in multiple concluding discussions. The manual review and analysis were additionally supported by multiple automated reviewing tools, like Slither , GasGauge , Manticore , and different fuzzing tools. 2.1 Severity Categories We are categorizing our findings into four different levels of severity: 2.2 Summary On the code level, we found 39 bugs or flaws, with 39 of them being fixed in a subsequent update . Prior to this, there have been 19 non-critical and 6 low, 9 medium and 5 high severity findings. Additionally, we found 9 gas improvements , which have all been implemented . The contracts are written according to the latest standard used within the Ethereum community and the Solidity community’s best practices. The naming of variables is very logical and understandable, which results in the contract being easy to understand. The code is well documented. The developers provided us with a test suite as well as proper deployment scripts. 2.3 Findings H.1 - Prevent contract to be initialized multiple times [HIGH SEVERITY] [FIXED] Location: PositionManager.sol - Line 105 - 116 Description: ​ The PositionManager can be re-inititialized countless times, as the init() function as well as the construction function does not implement any way to check whether the contract has been initialized already. This way, ownership can easily be claimed via the init() function. Recommendation: ​ Consider adding a flag to ensure that the contracts can only be initialized once. Additionally, we suggest making use of the OpenZeppelin libraries for initialization processes. Update on the 13th of June 2022: ​ The developers have update the implementation to make use of OpenZeppelin’s initializer, preventing multiple initializations. H.2 - SwapToPositionRatio function can be called by anyone [HIGH SEVERITY] [FIXED] Location: actions/SwapToPositionRatio.sol - Line 34 - 75 Description: ​ The swapToPositionRatio() function has no checks on authorization, hence it can be called and executed by anyone at any time. There might be cases, where this is not in the best interest of the user, especially during sudden price swings out of the current range. ​ The same applies to the following functions: modules/AaveModule.sol - depositIfNeeded() in line 37 modules/AaveModule.sol - withdrawIfNeeded() in line 55 modules/AutoCompoundModule.sol - autoCompoundFees() in line 30 modules/IdleLiquidityModule.sol - rebalance() in line 31 (Can not be called by anyone, but might still not be good !) Recommendation: ​ Consider adding a proper check for the correct authorization of the swapToPosition- Ratio() function. Update on the 14th of June 2022: The developers have updated their implementation to include the onlyWhitelisted- Keepers modifier, except for the swapToPositionRatio() function, where it is not necessary to do so. This action function is - as the developers told us - only being called via a fallback function that is properly protected. Subsequently, we consider this finding fixed. H.3 - LendingPoolAddress can be set by anyone [HIGH SEVERITY] [FIXED] Location: utils/AaveAddressHolder.sol - Line 16 - 18 Description: ​ The setLendingPoolAddress() function has no limitations on who can call and execute it and thus change the lending pools address. ​ These are the affected lines of code: function setLendingPoolAddress(address newAddress) external override { lendingPoolAddress = newAddress; } Recommendation: ​ Consider adding a proper check to ensure that only the right addresses can change the lending pool address. Update on the 13th of June 2022: ​ The developers have update the implementation to only allow governance to change these variables. H.4 - LendingPoolAddress can be set by anyone [HIGH SEVERITY] [FIXED] Location: actions/AaveDeposit.sol - Line 28 - 30 Description: ​ As the lending pool address of the Aave action can be set by anyone (due to (H.3)), users may deposit into a malicious lending pool or the lending pool of an attacker without knowing so. ​ These are the affected lines of code: PositionManagerStorage.getStorage().aave[...].lendingPoolAddress() Recommendation: ​ Consider addressing (H.3) or finding another way to ensure that the original lending address that a user defined can not be changed without them noticing or them intending to do so. Update on the 13th of June 2022: ​ As the developers have properly address finding (H.3), this finding has subsequently been addressed as well. H.5 - UniswapAddressHolder variables can be set by anyone [HIGH SEVERITY] [FIXED] Location: utils/UniswapAddressHolder.sol - Lines 25, 31, 37 Description: ​ The variables (nonfungiblePositionManagerAddress, uniswapV3FactoryAddress, and swapRouterAddress) have no limitations on who can set them - thus anyone can do it at any time. ​ This is one of the affected functions: function setNonFungibleAddress(address newAddress) external override { nonfungiblePositionManagerAddress = newAddress; } Recommendation: ​ Consider adding a proper check to ensure that only the right addresses can change the variables. Update on the 13th of June 2022: ​ The developers have update the implementation to only allow governance to change these variables.M.1 - Access protection is not working in modifier [MEDIUM SEVERITY] [FIXED] Location: PositionManager.sol - Line 90 Description: ​ The onlyFactory(_registry) modifier is not working as intended, as its input can be controlled by the caller. The calling address can deploy its own registry with registry.positionManagerFactoryAddress == msg.sender. Furthermore, the user might be able to deploy their own address this way, but still make use of the official one. ​ These are the affected lines of code: constructor( address _owner, address _diamondCutFacet, address _registry ) payable onlyFactory(_registry) { [...] } Recommendation: ​ Consider changing the access control to the PositionManager to be safe and not have any user-controlled inputs that can change its authorization. Update on the 13th of June 2022: ​ The developers have revamped the constructor-flow as well as the initialization process. The new flow does not contain any user-controller inputs as far as authorization goes, which now leads to the initialization to work as expected. ​ M.2 - False approval mechanism in AaveDeposit [MEDIUM SEVERITY] [FIXED] Location: actions/AaveDeposit.sol - Line 41 - 43 Description: ​ The deposit function of the Aave action contains a false approval/allowance mechanism. Firstly, it is important to first set the allowance to zero before changing it to a custom value, since some tokens enforce it (see here ). Secondly, we would suggest only approving the correct amount (diff) instead of the full amount. ​ This subsequently also occurs in helpers/ERC20Helper.sol in lines 22 to 25. ​ These are the affected lines of code: if (IERC20(token).allowance(address(this), address(lendingPool)) < amount) { IERC20(token).approve(address(lendingPool), amount); } Recommendation: ​ Consider changing the approval mechanism to first set the allowance to zero before changing it, as well as only approving the diff instead of the full amount. Update on the 13th of June 2022: ​ The developers have update the implementation to first set the allowance to zero before updating it to the required amount. ​ M.3 - Swap is not safe for front-runs [MEDIUM SEVERITY] [FIXED] Location: actions/Swap.sol - Line 50 Description: ​ During the swap, the call defines the input as well as the expected output. Setting the expected output to zero opens the door to a huge front-running opportunity as the arbitrageur has maximum room for price changes for this trade. Setting the proper expected output with a sensible slippage applied is within the best practice. ​ This also occurs in the following places: actions/SwapToPositionRatio.sol - Line 101 actions/ZapOut.sol - Line 97 ( with 1 Wei instead of 0 ) ​ These are the affected lines of code: ISwapRouter.ExactInputSingleParams memory swapParams = ISwapRouter.ExactInputSingleParams({ tokenIn: token0Address, tokenOut: token1Address, fee: fee, recipient: address(this), deadline: block.timestamp + 120, amountIn: amount0In, amountOutMinimum: 0, sqrtPriceLimitX96: 0 });Recommendation: ​ Consider making use of a proper amount for the expected out tokens instead of setting it to 0. ​ Update on the 14th of June 2022: ​ The developers have implemented a new time-weighted average pricing deviation check in the SwapHelper file, which they are using to ensure that the swaps are not carried out when they would incur a loss that is bigger than the accepted deviation. Subsequently, we consider this finding fixed. ​ M.4 - Logic to find best pool does not find best one [MEDIUM SEVERITY] [FIXED] Location: actions/ZapOut.sol - Line 111 - 120 Description: ​ The corresponding section in the _findBestFee() function intended to find the best pool is actually just returning the pool with the most liquidity at the given slot . However, if the impact of the swap leads to the liquidity of the current slot being used up, the rest of the swap is being facilitated in a slot whose liquidity is unknown to the function. ​ This also occurs in modules/AaveModule.sol in lines 214 to 222. ​ These are the affected lines of code: for (uint8 i = 0; i < 4; i++) { try this.getPoolLiquidity(token0, token1, uint24(fees[i])) returns (uint128 nextLiquidity) { if (nextLiquidity > bestLiquidity) { bestLiquidity = nextLiquidity; fee = fees[i]; } } catch { //pass } } Recommendation: ​ Consider either documenting this behaviour or simulating the trade in each of the pools to really find out, which of the offers the best circumstances for the corresponding trade. Update on the 13th of June 2022: ​ The developers have update the documentation to reflect the described behaviour. ​ M.5 - Missing liquidity in Aave deposit [MEDIUM SEVERITY] [FIXED] Location: modules/AaveModule.sol - Line 103 - 128 Description: ​ The amountToAave that is being calculated in the corresponding code section only accounts for the collected fees, not for the liquidity received by “closing” the position. Recommendation: ​ Consider including the liquidity that has been received as well, instead of just handling the fees. Update on the 14th of June 2022: The developers have responded to our finding, stating that the liquidity is included. It is taken into account by being stored in the tokensOwed variable after a call to decreaseLiquidity(). Afterwards, the liquidity is considered for the collectFees() call. Subsequently, we consider this finding fixed. ​ M.6 - Relying on external security promises for ticks [MEDIUM SEVERITY] [FIXED] Location: modules/IdleLiquidityModule.sol - Line 114 - 118 Description: ​ The result of the call to the NonfungiblePositionManager returns the lower and upper ticks. These are not checked and can lead to the calculation in line 111 to over- or underflow, without erroring as no SafeMath is used. They could be in the wrong order as well if not properly checked. ​ These are the affected lines of code: (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = INonfungiblePositionManager(uniswapAddressHolder.nonfungiblePositionManagerAddress()).positions(tokenId); int24 tickDelta = tickUpper - tickLower ; ​ Recommendation: ​ Consider verifying whether the ticks are actually ordered correctly as well as making use of SafeMath in this case as well to ensure that no under- or overflow can occur unnoticed. Update on the 13th of June 2022:The developers have update the implementation to make use of SafeMath, ensuring that no unnoticed under- or overflows can occur. ​ M.7 - Unsafe cast to int24 [MEDIUM SEVERITY] [FIXED] Location: modules/IdleLiquidityModule.sol - Line 129 Description: ​ The cast of a uint24 to int24 is dangerous and should be properly executed and verified, which is not the case here. This can lead to severely wrong values that are being subsequently used. ​ These are the affected lines of code: int24 tickSpacing = int24(fee) / 50; Recommendation: ​ Consider properly verifying whether the outcome of the unsafe cast is correct. Update on the 13th of June 2022: The developers have update the implementation to include a library, which handles the safe casting between int24 and uint24. This library is now being used. M.8 - Severe over-/underflow risk without SafeMath [MEDIUM SEVERITY] [FIXED] Location: modules/IdleLiquidityModule.sol - Line 131 Description: ​ As SafeMath is not used, there are several risks (see (L.3)). In this case, there is a severe risk of under- and/or overflows due to the nature of the calculation. Additionally, (in the latter part of the calculation) dividing by tickSpacing and then multiplying by tickSpacing only reduces accuracy without doing anything meaningful, which might not be the desired behavior. ​ The same occurs in utils/WithdrawRecipes.sol in lines 49 - 50 and in modules/AutoCompoundModule.sol in lines 72 - 73. ​ These are the affected lines of code: return (((tick - tickDelta) / tickSpacing) * tickSpacing, ((tick + tickDelta) / tickSpacing) * tickSpacing); Recommendation: ​ Consider making use of SafeMath and removing unnecessary parts of the calculation. Update on the 13th of June 2022: The developers have update the implementation to make use of SafeMath. M.9 - Empty data doesn’t always revert [MEDIUM SEVERITY] [FIXED] Location: modules/IdleLiquidityModule.sol - Line 40 Description: ​ With the modules and actions generally reverting in case of the data being non-existent, this is mostly fine. However, in this case, a definitive rebalance is being facilitated as the values here might still pass the if-checks. Recommendation: ​ Consider properly checking whether the module’s data has been correctly set. ​ Update on the 13th of June 2022: ​ The developers have update the implementation to ensure that the data of the module is not set to zero. L.1 - Wrong comparison operator [LOW SEVERITY] [FIXED] Location: helpers/ERC20Helper.sol - Line 54 Description: ​ During the check on whether the balance is greater than the required amount, a less than (<) is used, instead of making use of a less than equal (<=). ​ These are the affected lines of code: if (amount - balance < _getBalance(token, from)) { needed = amount - balance; IERC20(token).safeTransferFrom(from, address(this), needed); } Recommendation: ​ Consider changing the comparison to reflect a less than equal (<=) instead of a less than (<) to correct it. ​ Update on the 13th of June 2022:The developers have update the implementation to use a less than equal (<=) instead of a less than (<). L.2 - Misleading or wrong documentation [LOW SEVERITY] [FIXED] Location: Multiple occurrences throughout the project Description: Certain parts of the documentation are misleading or wrong: helpers/ERC20Helper.sol - Line 62 - 65 -> The function does not withdraw the specified amount if the user does not have that many tokens modules/IdleLiquidityModule.sol - Line 39 -> tickDistance can be smaller than zero utils/Storage.sol - Line 190 -> The function does not return but instead reverts in this case Recommendation: ​ Consider correcting the documentation to ensure that they are correct and not misleading. Update on the 13th of June 2022: ​ The developers have update the documentation to better represent the actual logic of the code. L.3 - Not making use of SafeMath where appropriate [LOW SEVERITY] [FIXED] Location: Multiple occurrences throughout the project Description: ​ In certain locations, calculations are facilitated without SafeMath in a Solidity version that is lower than 0.8: helpers/SwapHelper.sol -> Throughout the whole contract actions/ZapIn.sol - Lines 53 - 54 ​ Recommendation: ​ Consider using SafeMath functionalities in the corresponding occurrences to ensure their required safety guarantees. Update on the 13th of June 2022: ​ The developers have update the implementation to make use of SafeMath in the corresponding occurrences. L.4 - Faulty reliance on data to be present [LOW SEVERITY] [FIXED] Location: Multiple occurrences throughout the project Description: ​ As modules currently do not require any data to be set, it is not the best idea to rely on the data being present. In the cases that we found, the call would still revert, but we do not recommend this handling of missing data. This occurs in the following cases: modules/AaveModule.sol - depositIfNeeded() in line 37 modules/AutoCompoundModule.sol - _checkIfCompoundIsNeeded() in line 50 modules/IdleLiquidityModule.sol - rebalance() in line 31 Recommendation: ​ Consider adding a proper handling to functions that interact with a module while relying on its data to be present. This can also just be a proper require statement. Update on the 13th of June 2022: ​ The developers have update the implementation to ensure that the data of the module is not zero. L.5 - Use of 32 bits does not save gas [LOW SEVERITY] [FIXED] Location: utils/DepositRecipes.sol - Line 36 Description: ​ The use of a uint32 variable does not save gas in this case, as you can see here . ​ The same also applies to the use of uint8 for the i-variable in for-loops, like in modules/AaveModule.sol in line 213. These are the affected lines of code: for (uint32 i = 0; i < tokenIds.length; i++) { [...]} Recommendation: ​ Consider reverting the counter back to uint256 to ensure that it can not overflow. ​ Update on the 13th of June 2022: The developers have update the implementation to use uint256 variables instead of uint32. L.6 - Use of unsafe ERC20 transfers [LOW SEVERITY] [FIXED] Location: Multiple occurrences throughout the project Description: ​ Throughout the project, the unsafe versions of ERC20 transfers are used. With the variety of todays tokens, especially malicious ones, this is never recommended. This occurs in the following cases: utils/DepositRecipes.sol - Lines 69 - 70 actions/AaveDeposit.sol - Line 42 ( approve ) helpers/ERC20Helper.sol - Line 25 ( approve ) Recommendation: ​ Consider making use of SafeERC20 mechanics to ensure a safe transfer of ERC20 tokens. Update on the 13th of June 2022: The developers have update the implementation to make use of SafeERC20 in all of the corresponding occurrences. NC.1 - Non-standard delete from array pattern [NO SEVERITY] [FIXED] Location: PositionManager.sol - Line 128 - 137 Description: ​ A non-standard way of “delete from array” pattern is being used here, which we do not usually recommend. ​ These are the affected lines of code: for (uint256 i = 0; i < uniswapNFTs.length; i++) { if (uniswapNFTs[i] == tokenId) { if (uniswapNFTs.length > 1) { uniswapNFTs[i] = uniswapNFTs[uniswapNFTs.length - 1]; uniswapNFTs.pop(); } else { delete uniswapNFTs; } return; } } Recommendation: ​ Consider changing the pattern to be more standardized to be safe, like in the example below: for (uint256 i = 0; i < uniswapNFTs.length; i++) { if (uniswapNFTs[i] == tokenId) { if (i + 1 != uniswapNFTs.length) { uniswapNFTs[i] = uniswapNFTs[uniswapNFTs.length - 1]; } uniswapNFTs.pop(); return; } } Update on the 13th of June 2022: ​ The developers have update the implementation to make use of more a standardized pattern to remove an element from the array. NC.2 - Key should be private to enforce proper use [NO SEVERITY] [FIXED] Location: utils/Storage.sol - Line 38 Description: ​ To ensure a proper usage of the getStorage() function, the key variable should be set to private, so it can not be accessed on accident. ​ These are the affected lines of code: bytes32 constant key = keccak256('position-manager-storage-location'); ​ Recommendation: ​ Consider adding the private keyword to the key variable to ensure a proper use of the getStorage() function.Update on the 13th of June 2022: ​ The developers have update the variable to be private, enforcing the proper use of their function. NC.3 - Undocumented constant value [NO SEVERITY] [FIXED] Location: modules/IdleLiquidityModule.sol - Line 70 Description: ​ There is an undocumented value of 10 being deducted from the swapped token amounts. Furthermore, this value is not being defined as a global (constant) variable for better readability. ​ These are the affected lines of code: IMint.MintInput(token0, token1, fee, tickLower, tickUpper, token0Swapped - 10 , token1Swapped - 10 ) Recommendation: ​ Consider documenting the value of 10 and possibly converting it to a global (constant) variable. ​ Update on the 13th of June 2022: ​ The developers have update the variable itself as well as its documentation to make sure that it can be properly understood. NC.4 - Invalid documentation [NO SEVERITY] [FIXED] Location: PositionManager.sol - Line 257 - 258 Description: ​ The documentation of the withdrawERC20() function does state that it returns tokens, while in reality it transfers them to the msg.sender. Recommendation: ​ Consider correcting the documentation to reflect the actual function. Update on the 13th of June 2022: ​ The developers have update the documentation to reflect the actual logic of the function. NC.5 - Wrong use of allowance [NO SEVERITY] [FIXED] Location: PositionManager.sol - Line 260 Description: ​ The withdrawERC20() function includes an approveToken call, which is (a) not required at all, (b) approving the wrong address, as well as (c) using the wrong amount for the approval. Additionally, using type(uint256).max is best practice instead of using 2**256 - 1. These are the affected lines of code: ERC20Helper._approveToken(tokenAddress, address(this), 2**256 - 1); uint256 amount = ERC20Helper._withdrawTokens(tokenAddress, msg.sender, 2**256 - 1); ​ Recommendation: ​ Consider removing the approve-call and change the uint256 maximum value to reflect the best practice of Solidity. We would suggest a change like the following: ​ uint amount = ERC20Helper._getBalance(tokenAddress, address(this)); uint got = ERC20Helper._withdrawTokens(tokenAddress, msg.sender, amount); require(amount == got, "ERC20 Transfer failed"); emit ERC20Withdrawn(tokenAddress, msg.sender, got); Update on the 13th of June 2022: ​ The developers have update the implementation, removing the unnecessary approval statement and making use of our suggested change. NC.6 - Use underscores for large numerals [NO SEVERITY] [FIXED] Location: utils/WithdrawRecipes.sol - Line 31, 49, 50 Description: ​ It is best practice to write numerals that are 1,000 or higher with underscores, like so: 1_000 instead of 1000 17_521_395 instead of 17521395This highly increases its readability. ​ Recommendation: ​ Consider adding underscores to numerals to that are 1,000 or higher. ​ Update on the 13th of June 2022: ​ The developers have update the implementation, adding underscored to the corresponding numerals. NC.7 - Not using the getStorage function [NO SEVERITY] [FIXED] Location: PositionManager.sol - Line 294 Description: ​ The fallback() function retrieves the storage manually instead of making use of the provided getStorage() function. ​ These are the affected lines of code: StorageStruct storage Storage; bytes32 position = PositionManagerStorage.key; ///@dev get diamond storage position assembly { Storage.slot := position } Recommendation: ​ Consider making use of the getStorage() function instead of doing it manually. Update on the 13th of June 2022: The developers have update the implementation to enforce the proper use of the getStorage() function. NC.8 - Unnecessary double function exposed [NO SEVERITY] ACKNOWLEDGED Location: PositionManagerFactory.sol - Line 86 - 88 Description: ​ The getAllPositionManagers() function merely returns the positionManagers array, which is unnecessary as the array is public anyways. This is increasing the contract size without any benefit. ​ The same also applies to the moduleKeys array in the Registry, with the getModuleKeys() function in line 102 being implemented as well. ​ Recommendation: Consider either removing the getAllPositionManagers() function or changing the array to be private to prevent two exposed functions to exist. Update on the 14th of June 2022: The developers have stated that they have a good reason to keep the extra function, which is perfectly fine for us. There is no security implication be keeping it. NC.9 - Unnecessary deadline extension [NO SEVERITY] [FIXED] Location: PositionManagerFactory.sol - Line 46 - 49 Description: ​ The changeGovernance() function has two slight problems that we see: it does not validate its input, which - in this case - might be crucial. Additionally, it might emit the event in cases where there has been no change to the state. ​ The same also applies to the same function in the Registry.sol contract in line 47 - 50. ​ Recommendation: ​ Consider validating the input of crucial functions like this one to be valid. Additionally, ensure that events for state-changing functions are only emitted if the state variable has actually been changed. Update on the 13th of June 2022: ​ The developers have update the implementation to validate whether the supplied address is not zero. NC.10 - Insufficient state-modifying function [NO SEVERITY] [FIXED] Location: actions/ClosePosition.sol - Line 46 Description: ​ The deadline of the swap is being extended by 120 seconds, even though it is being executed by a contract instead of an EOA, in which case it is unnecessary. ​ The same occurs in the following places: actions/CollectFees.sol - Line 59actions/DecreaseLiquidity.sol - Line 76 actions/IncreaseLiquidity.sol - Line 58 actions/Mint.sol - Line 57 actions/SwapToPositionRatio.sol - Line 99 actions/ZapOut.sol - Line 43 actions/ZapOut.sol - Line 95 These are the affected lines of code: deadline: block.timestamp + 120 Recommendation: ​ Consider removing the 120 second addition, as it is unnecessary in this case. Update on the 13th of June 2022: ​ The developers have update the implementation, removing the unnecessary 120 second addition to the deadline. NC.11 - Wrong type used for Uniswap V3 [NO SEVERITY] [FIXED] Location: actions/ClosePosition.sol - Line 50 - 52 Description: ​ The token0Closed and token1Closed variables are of type uint128, as defined in the Uniswap V3 contracts . However, in your implementation, you are using the uint256 type instead, which leads to an implicit conversion. ​ These are the affected lines of code: (, , , , , , , , , , uint256 token0Closed, uint256 token1Closed) = nonfungiblePositionManager.positions(tokenId); Recommendation: ​ Consider changing the type of the two variables to be uin128 and then (if required) convert it to uint256 to ensure that no side-effect occur. During our internal tests, this still worked as intended, but we can’t guarantee it in any case. Update on the 13th of June 2022: The developers have update the implementation to work with uint128 for the return values of the Uniswap V3 calls. NC.12 - Not using the default method for maximum values [NO SEVERITY] [FIXED] Location: actions/ClosePosition.sol - Line 57 - 58 Description: ​ Solidity has a default way to ensure a clean and error-free way of setting the maximum value of a type with type(uint128).max instead of doing a manual calculation. This is not being used here. ​ The same occurs in the following places: actions/Swap.sol - Lines 40 - 41 actions/SwapToPositionRatio - Lines 91 - 92 actions/ZapOut.sol - Lines 51 - 52 ​ These are the affected lines of code: INonfungiblePositionManager.CollectParams memory collectparams = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: returnTokenToUser ? Storage.owner : address(this), amount0Max: 2**128 - 1, amount1Max: 2**128 - 1 ​ }); Recommendation: ​ Consider making use of type(uint128).max instead of 2**128-1. Update on the 13th of June 2022: The developers have update the implementation throughout the project to make use of the type(uint).max flow instead of manually calculations. NC.13 - Making use of undocumented side-effect [NO SEVERITY] ACKNOWLEDGED Location: actions/CollectFees.sol - Line 51 - 64 Description: ​ The _updateUncollectedFees() function does look like a rather costly way of updating the uncollected fee through an undocumented side-effect. This is usually not within the best practice, but does certainaly not cause any harm here.Recommendation: ​ We leave it up to the developers on whether they want to keep using this behaviour. We just wanted to point it out in case this behaviour changes over time. Update on the 14th of June 2022: ​ The developers have acknowledged the finding and are open to find a better solution. As there is currently no better solution that is known to either of us, it is perfectly fine to stay like this. NC.14 - Only emit events if the state changed [NO SEVERITY] [FIXED] Location: actions/SwapToPositionRatio.sol - Line 74 Description: ​ It is best practice to only emit an event if the state has actually been changed. This usually does require an additional if- statement to be added, but is generally accepted to be more consistent in terms of the on-chain history. ​ This also occurs in the following locations: utils/Storage.sol - Line 62 Recommendation: ​ Consider adding an if-statement to ensure that the event is only emitted, if something was actually changed. Update on the 13th of June 2022: ​ The developers have update the implementation to only emit events in cases where something was actually changed. NC.15 - Relying on false guarantees [NO SEVERITY] [FIXED] Location: actions/ZapIn.sol - Line 45 Description: ​ The _pullTokensIfNeeded() function does not guarantee that any tokens have actually been pulled. In this case, it does not look like anything would happen, but this is not within the best practice. Recommendation: ​ Consider calls to functions like _pullTokensIfNeeded() when writing your logic and keep in mind that they are not required to actually do what they say. We would suggest that an additional require statement may be used to ensure that everything has worked out. Update on the 13th of June 2022: ​ The developers have update the implementation to ensure that any call to _pullTokensIfNeeded() only succeeds if it really did its job properly. NC.16 - Use of transferFrom instead of transfer [NO SEVERITY] [FIXED] Location: helpers/ERC20Helper.sol - Line 77 Description: ​ The _withdrawTokens() function transfers tokens from itselfv to an address via transferFrom, which is not correct. This can be handled with a regular transfer. ​ These are the affected lines of code: IERC20(token).safeTransferFrom(address(this), to, amountOut); Recommendation: ​ Consider changing the transferFrom to a regular transfer. Update on the 13th of June 2022: The developers have update the implementation to make use of a regular transfer instead of a transferFrom. NC.17 - Unchangeable global variables should be immutable [NO SEVERITY] [FIXED] Location: Throughout the project Description: ​ There are certain occurrences of global variables that should never change, hence should be immutable to ensure that this is the case as well as saving some gas. These occurrences are: PositionManager.sol - Line 12 - 15 modules/AaveModule.sol - Lines 21 - 22 modules/AutoCompoundModule.sol - Line 17 modules/IdleLiquidityModule.sol - Line 19utils/DepositRecipes.sol - Line 17 - 18 utils/WithdrawRecipes.sol - Line 18 - 19 modules/BaseModule..sol - Line 10 Recommendation: ​ Consider adding the immutable keyword to the corresponding global variables that qualify. Update on the 13th of June 2022: The developers have update the implementation, setting the corresponding unchangeable global variables to be immutable. NC.18 - Missing visibility keyword [NO SEVERITY] [FIXED] Location: Throughout the project ​ Description: ​ There are certain occurrences of global variables that are missing a visibility keyword, which leads to them being private, which is often not the desired behaviour. These occurrences are: PositionManager.sol - Line 13 - 14 modules/AaveModule.sol - Line 22 modules/AutoCompoundModule.sol - Line 17 utils/DepositRecipes.sol - Line 17 - 18 utils/WithdrawRecipes.sol - Line 18 - 19 Recommendation: ​ Consider adding the correct visibility keyword to the corresponding global variables that are missing one. Update on the 13th of June 2022: ​ The developers have update the implementation, adding a visibility keyword to the corresponding global variables. NC.19 - Function can be exported to library [NO SEVERITY] [FIXED] Location: modules/AaveModule.sol - Line 173 Description: ​ The code of the distance check is a near duplicate of the code in the _getTokens() function of the UniswapNFTHelper contract. This code can be exported into a library Recommendation: ​ Consider introducing a library to prevent unnecessary code duplication. Update on the 13th of June 2022: The developers have moved the logic into the UniswapNFTHelper contract. ​ 2.4 Gas Optimizations DONE - GO.1 - Cache array length if accessed inside of for-loop Location: Throughout the project Description: ​ There are several for-loops that can benefit from caching the length of the used array, which is often the case if it is being accessed outside of the declaration of the loop itself. Caching the array length outside a loop saves reading it on each iteration, as long as the array's length is not changed during the loop. ​ The affected for-loops are: PositionManager.sol - Line 128 PositionManager.sol - Line 271 PositionManager.sol - Line 284 utils/DepositRecipes.sol - Line 36 utils/Storage.sol - Line 81 utils/Storage.sol - Line 106 utils/Storage.sol - Line 177 utils/Storage.sol - Line 192​ This is an example of an affected loop: for (uint256 i = 0; i < uniswapNFTs.length ; i++) { if (uniswapNFTs[i] == tokenId) { if (uniswapNFTs.length > 1) { uniswapNFTs[i] = uniswapNFTs[ uniswapNFTs.length - 1]; uniswapNFTs.pop(); } else { delete uniswapNFTs; } return; } } Recommendation: ​ Consider moving the length of the used array into a cached variable like in the example below: uint256 nfts = uniswapNFTs.length; for (uint256 i = 0; i < nfts ; i++) { if (uniswapNFTs[i] == tokenId) { if (uniswapNFTs.length > 1) { uniswapNFTs[i] = uniswapNFTs[ nfts - 1]; [...] } Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. DONE - GO.2 - Optimize loops to be more efficient Location: Throughout the project Description: ​ All of the for-loops in the project are using the standard way of declaring them, which is slightly inefficient gas-wise. ​ This is an example of an unoptimized for-loop: for ( uint256 i = 0 ; i < array.length; i ++ ) { [...] } Recommendation: ​ Consider optimizing the for-loops in each contract to be more efficient in terms of its gas usage, including: Not initializing variables with their default value Using the more efficient way to increment a variable for ( uint256 i ; i < array.length; ++ i) { [...] } Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. DONE - GO.3 - Don’t initialize variables with default value Location: Throughout the project Description: ​ Initializing variables with their default values uses more gas than necessary as it involves an unnecessary MSTORE or SSTORE operation. ​ The affected variables are: actions/ZapOut.sol - Line 108 helpers/ERC20Helper.sol - Line 51 modules/AaveModule.sol - Line 113 modules/AaveModule.sol - Line 222 ​ This is an example of an affected variable: uint128 bestLiquidity = 0; Recommendation: ​ Consider removing occasions where the default value is being used to initialize a variable to save some gas, as shown in the example below:​ uint128 bestLiquidity; Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. DONE - GO.4 - Use !=0 instead of >0 for uint comparisons Location: Throughout the project Description: ​ In require statements, it is cheaper to check for != 0 instead of > 0, if the unsigned integer is being validated to not be zero. Changing this will save some gas. ​ The affected variables are: PositionManager.sol - Line 237 helpers/SwapHelper.sol - Line 46 utils/Storage.sol - Line 98 utils/Storage.sol - Line 169 utils/Storage.sol - Line 188 utils/Storage.sol - Line 203 utils/WithdrawRecipes.sol - Line 34 ​ This is an example of an affected require statement check: require(amount0In > 0 || amount1In > 0); Recommendation: ​ Consider changing all of the require statements that involved a zero check for a unsigned integer to be more gas efficient, like in the example below: ​ require(amount0In != 0 || amount1In != 0); Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. DONE - GO.5 - Cache certain variables to save gas Location: Throughout the project Description: ​ In certain circumstances, it saves gas to cache variables that are read often, especially if they are stored in storage and not in memory. The affected variables are: PositionManager.sol - Line 237 ( aaveUserReserves ) actions/AaveDeposit.sol - Line 33 ( aTokenAddress ) actions/DecreaseLiquidity.sol - Line 44 ( nonfungiblePositionManagerAddress ) actions/IncreaseLiquidity.sol - Line 37 ( nonfungiblePositionManagerAddress ) actions/Mint.sol - Line 37 ( nonfungiblePositionManagerAddress ) actions/ZapIn.sol - Line 123 ( nonfungiblePositionManagerAddress ) actions/ZapOut.sol - Line 86 ( swapRouterAddress ) modules/AaveModule.sol - Line 71 ( nonfungiblePositionManagerAddress ) modules/AaveModule.sol - Line 95 ( nonfungiblePositionManagerAddress ) modules/AutoCompoundModule.sol - Line 59 ( nonfungiblePositionManagerAddress ) modules/IdleLiquidityModule.sol - Line 126 ( nonfungiblePositionManagerAddress ) utils/DepositRecipes.sol - Line 41 - 47 (cache tokenIds outside of the loop) Recommendation: ​ Consider caching the affected variables and reading from the cached version instead of doing costly read actions. Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration.DONE - GO.6 - Save a storage slot by earlier cast Location: actions/SwapToPositionRatio.sol - Lines 41 - 47 Description: ​ The pool variable is being obtained in two steps, with the outcome of the first step never being used again. To safe a storage slot and save gas, this can be optimized by directly casting the outcome of the first operation to IUniswapV3Pool. ​ Recommendation: ​ Consider directly casting the outcome of poolAddress to IUniswapV3Pool. Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. DONE - GO.7 - Unnecessary multiple approvals Location: actions/ZapIn.sol - Lines 56 Description: ​ During the zapIn() call, the approveToken() function is called twice with the same inputs, hence wasting gas which is not necessary. ​ These are the affected lines of code: ERC20Helper._approveToken(tokenIn, Storage.uniswapAddressHolder.swapRouterAddress(), amountIn); [...] ERC20Helper._approveToken(tokenIn, Storage.uniswapAddressHolder.swapRouterAddress(), amountIn); Recommendation: ​ Consider removing one of the approval calls to save gas. Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. DONE - GO.8 - Possible caching opportunity Location: modules/IdleLiquidityModule.sol - Lines 36 - 72 Description: ​ The result of the call to the NonfungiblePositionManager is already done in the _checkDistanceFromRange() function. It could be cached to prevent a double calling, saving some gas. Recommendation: ​ Consider obtaining the required values from the _checkDistanceFromRange() function, caching them instead of calling the underlying function twice. Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. DONE - GO.9 - Possible caching opportunity Location: Registry.sol - Lines 11 Description: ​ The access to the whitelistedKeepers array gets more and more expensive as the array size increases, with the cost of the access being O (n). Making use of a hashmap (mapping) would bring this down to O (1), which is way more efficient and cheaper. Recommendation: ​ Consider switching from an array layout to a mapping/hashmap to make the access way more efficient (especially deletions). Update on the 14th of June 2022: ​ The developers have updated their implementation, taking our suggestion for gas improvements into consideration. 3. Protocol/Logic Review Part of our audits are also analyses of the protocol and its logic. The byterocket team went through the implementation and documentation of the implemented protocol. The repository itself contained tests and documentation. We found the provided unit tests that are coming with the repository execute without any issues and cover the most important parts of the protocol. According to our analysis, the protocol and logic are working as intended, given that any findings with a severity level arefixed. When making use of the Mainnet forking method, we were able to successfully execute the protocol and its modules. We were not able to discover any additional problems in the protocol implemented in the smart contract. 4 . Summary During our code review ( which was done manually and automated ), we found 39 bugs or flaws, with 39 of them being fixed in a subsequent update . Prior to this, there have been 19 non-critical and 6 low, 9 medium and 5 high severity findings. Additionally, we found 9 gas improvements , which have all been implemented . The protocol review and analysis did neither uncover any game-theoretical nature problems nor any other functions prone to abuse besides the ones that have been uncovered in our findings. In general, there are some improvements that can be made, but we are very happy with the overall quality of the code and its documentation. The developers have been very responsive and were able to answer any questions that we had. 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-ChainLEGAL Imprint Terms & Conditions Privacy Policy Contact © 2022 byterocket GmbH 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 - 19 Non-Critical - 6 Low - 9 Medium - 5 High Minor Issues - No Minor Issues Moderate Issues - H.1 - Prevent contract to be initialized multiple times [MODERATE SEVERITY] [FIXED] Problem: The PositionManager can be re-inititialized countless times, as the init() function as well as the construction function does not implement any way to check whether the contract has been initialized already. Fix: Consider adding a flag to ensure that the contracts can only be initialized once. Major Issues - No Major Issues Critical Issues - No Critical Issues Observations - The contracts are written according to the latest standard used within the Ethereum community and the Solidity community’s best practices. - The naming of variables is very logical and understandable, which results in the contract being easy to understand. - The code is well documented. - The developers provided us with a test suite as well as proper deployment scripts. Conclusion The audit of Orbit DeFi's token contract suite revealed 39 bugs or flaws, with 39 of them being Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 1 Minor Issues: 2.a Problem: No checks on authorization for swapToPositionRatio() function. 2.b Fix: Consider adding a proper check for the correct authorization of the swapToPosition- Ratio() function. Moderate: None Major: None Critical: 5.a Problem: No onlyWhitelisted- Keepers modifier for swapToPositionRatio() function. 5.b Fix: Updated implementation to include the onlyWhitelisted- Keepers modifier, except for the swapToPositionRatio() function, where it is not necessary to do so. Observations: The developers have update the implementation to make use of OpenZeppelin’s initializer, preventing multiple initializations. Conclusion: The developers have updated their implementation to include the onlyWhitelisted- Keepers modifier, except for the swapToPositionRatio() function, where it is not necessary to do so. Consider adding a proper check for the correct authorization of the swapToPosition- Ratio() function. Issues Count of Minor/Moderate/Major/Critical: Minor: 0 Moderate: 0 Major: 0 Critical: 0 Observations: The developers have updated the implementation to only allow governance to change the variables. Conclusion: The report has been addressed and fixed.
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IUniswapV2ERC20 { 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; } interface IUniswapV2Pair is IUniswapV2ERC20 { // event Approval(address indexed owner, address indexed spender, uint value); // event Transfer(address indexed from, address indexed to, uint value); event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); // 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; 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; } library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } 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 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // 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); } // 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); } // decode a uq112x112 into a uint with 18 decimals of precision function decode112with18(uq112x112 memory self) internal pure returns (uint) { // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous // instead, get close to: // (x * 1e18) >> 112 // without risk of overflowing, e.g.: // (x) / 2 ** (112 - lg(1e18)) return uint(self._x) / 5192296858534827; } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // 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, "DIV_BY_ZERO"); // return uq112x112((uint224(numerator) << 112) / denominator); // } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // lossy if either numerator or denominator is greater than 112 bits function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } 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. */ 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } /* * Expects percentage to be trailed by 00, */ function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) { return div( mul( total_, percentage_ ), 1000 ); } /* * Expects percentage to be trailed by 00, */ function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) { return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) ); } function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) { return div( mul(part_, 100) , total_ ); } /** * Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol * @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); } function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) { return sqrrt( mul( multiplier_, payment_ ) ); } function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) { return mul( multiplier_, supply_ ); } } ///////////////////////////////////////// End of flatten \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ interface ITreasury { function getManagedToken() external returns ( address ); } interface IBondingCalculator { function calcPrincipleValuation( uint k_, uint amountDeposited_, uint totalSupplyOfTokenDeposited_ ) external pure returns ( uint principleValuation_ ); function principleValuation( address principleTokenAddress_, uint amountDeposited_ ) external view returns ( uint principleValuation_ ); } contract OlympusBondingCalculator is IBondingCalculator { using FixedPoint for *; using SafeMath for uint; using SafeMath for uint112; event BondPremium( uint debtRatio_, uint bondScalingValue_, uint premium_ ); event PrincipleValuation( uint k_, uint amountDeposited_, uint totalSupplyOfTokenDeposited_, uint principleValuation_ ); event BondInterest( uint k_, uint amountDeposited_, uint totalSupplyOfTokenDeposited_, uint pendingDebtDue_, uint managedTokenTotalSupply_, uint bondScalingValue_, uint interestDue_ ); // Values LP share based on formula // returns principleValuation = 2sqrt(constant product) * (% ownership of total LP) // uint k_ = constant product of liquidity pool // uint amountDeposited_ = amount of LP token // uint totalSupplyOfTokenDeposited = total amount of LP function _principleValuation( uint k_, uint amountDeposited_, uint totalSupplyOfTokenDeposited_ ) internal pure returns ( uint principleValuation_ ) { // *** When deposit amount is small does not pick up principle valuation *** \\ principleValuation_ = k_.sqrrt().mul(2).mul( FixedPoint.fraction( amountDeposited_, totalSupplyOfTokenDeposited_ ).decode112with18().div( 1e10 ).mul( 10 ) ); } // External function to get value of an amount of LP // uint k_ = constant product of liquidity pool // uint amountDeposited_ = amount of LP token // uint totalSupplyOfTokenDeposited = total amount of LP function calcPrincipleValuation( uint k_, uint amountDeposited_, uint totalSupplyOfTokenDeposited_ ) external pure override returns ( uint principleValuation_ ) { principleValuation_ = _principleValuation( k_, amountDeposited_, totalSupplyOfTokenDeposited_ ); } // View function for principle value // address principleTokenAddress = LP token address // uint amountDeposited_ = amount of LP to value function principleValuation( address principleTokenAddress_, uint amountDeposited_ ) external view override returns ( uint principleValuation_ ) { uint k_ = _getKValue(principleTokenAddress_); uint principleTokenTotalSupply_ = IUniswapV2Pair( principleTokenAddress_ ).totalSupply(); principleValuation_ = _principleValuation( k_, amountDeposited_, principleTokenTotalSupply_ ); } // Gets constant product of pool // k = x * y function _getKValue( address principleTokenAddress_ ) internal view returns( uint k_ ) { (uint reserve0, uint reserve1, ) = IUniswapV2Pair( principleTokenAddress_ ).getReserves(); k_ = reserve0.mul(reserve1).div(1e9); // Accounts for decimals (DAI = 18; OHM = 9) } } /** *Submitted for verification at Etherscan.io on 2021-03-20 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IOwnable { function owner() external view returns (address); function renounceOwnership() external; function transferOwnership( address newOwner_ ) external; } 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) { 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 SafeMathInt { function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } library Address { 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is IOwnable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipTransferred( address(0), _owner ); } function owner() public view override returns (address) { return _owner; } modifier onlyOwner() { require( _owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceOwnership() public virtual override onlyOwner() { emit OwnershipTransferred( _owner, address(0) ); _owner = address(0); } function transferOwnership( address newOwner_ ) public virtual override onlyOwner() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred( _owner, newOwner_ ); _owner = newOwner_; } } interface IERC20 { function decimals() external view returns (uint8); /** * @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); } 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 _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "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"); } } } interface IERC20Mintable { function mint( uint256 amount_ ) external; function mint( address account_, uint256 ammount_ ) external; } ///////////////////////////////////////// End of flatten \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ interface IBondingCalculator { function calcDebtRatio( uint pendingDebtDue_, uint managedTokenTotalSupply_ ) external pure returns ( uint debtRatio_ ); function calcBondPremium( uint debtRatio_, uint bondScalingFactor ) external pure returns ( uint premium_ ); function calcPrincipleValuation( uint k_, uint amountDeposited_, uint totalSupplyOfTokenDeposited_ ) external pure returns ( uint principleValuation_ ); function principleValuation( address principleTokenAddress_, uint amountDeposited_ ) external view returns ( uint principleValuation_ ); function calculateBondInterest( address treasury_, address principleTokenAddress_, uint amountDeposited_, uint bondScalingFactor ) external returns ( uint interestDue_ ); } interface ITreasury { function getBondingCalculator() external returns ( address ); function getTimelockEndBlock() external returns ( uint ); function getManagedToken() external returns ( address ); } contract Vault is ITreasury, Ownable { using SafeMath for uint; using SafeMathInt for int; using SafeERC20 for IERC20; event TimelockStarted( uint timelockEndBlock ); bool public isInitialized; uint public timelockDurationInBlocks; uint public override getTimelockEndBlock; address public daoWallet; address public LPRewardsContract; // Pool 2 rewards contract address public stakingContract; uint public LPProfitShare; // % = (1 / LPProfitShare) address public override getManagedToken; // OHM address public getReserveToken; // DAI address public getPrincipleToken; // OHM-DAI LP address public override getBondingCalculator; mapping( address => bool ) public isPrincipleDepositor; mapping( address => bool ) public isReserveDepositor; modifier notInitialized() { require( !isInitialized ); _; } modifier isTimelockExpired() { require( getTimelockEndBlock != 1 ); require( timelockDurationInBlocks > 1 ); require( block.number >= getTimelockEndBlock ); _; } modifier isTimelockStarted() { if( getTimelockEndBlock != 0 ) { emit TimelockStarted( getTimelockEndBlock ); } _; } function setDAOWallet( address newDAOWallet_ ) external onlyOwner() returns ( bool ) { daoWallet = newDAOWallet_; return true; } function setStakingContract( address newStakingContract_ ) external onlyOwner() returns ( bool ) { stakingContract = newStakingContract_; return true; } function setLPRewardsContract( address newLPRewardsContract_ ) external onlyOwner() returns ( bool ) { LPRewardsContract = newLPRewardsContract_; return true; } function setLPProfitShare( uint newDAOProfitShare_ ) external onlyOwner() returns ( bool ) { LPProfitShare = newDAOProfitShare_; return true; } function initialize( address newManagedToken_, address newReserveToken_, address newBondingCalculator_ ) external onlyOwner() notInitialized() returns ( bool ) { getManagedToken = newManagedToken_; // OHM address getReserveToken = newReserveToken_; // DAI address getBondingCalculator = newBondingCalculator_; timelockDurationInBlocks = 1; isInitialized = true; return true; } // Approves an address to deposit LP and receive OHM function setPrincipleDepositor( address newDepositor_ ) external onlyOwner() returns ( bool ) { isPrincipleDepositor[newDepositor_] = true; return true; } // Approves an address to deposit DAI and receive OHM function setReserveDepositor( address newDepositor_ ) external onlyOwner() returns ( bool ) { isReserveDepositor[newDepositor_] = true; return true; } // Disapproves an address from depositing LP to receive OHM function removePrincipleDepositor( address depositor_ ) external onlyOwner() returns ( bool ) { isPrincipleDepositor[depositor_] = false; return true; } // Disapproves an address from depositing DAI to receive OHM function removeReserveDepositor( address depositor_ ) external onlyOwner() returns ( bool ) { isReserveDepositor[depositor_] = false; return true; } // Allows an approved depositor to deposit LP to create OHM // New OHM is sent to LPRewardsContract and the staking contract function rewardsDepositPrinciple( uint depositAmount_ ) external returns ( bool ) { require(isPrincipleDepositor[msg.sender] == true, "Not allowed to deposit"); address principleToken = getPrincipleToken; IERC20( principleToken ).safeTransferFrom( msg.sender, address(this), depositAmount_ ); // Must remove 9 decimals to account for OHM token decimals uint value = IBondingCalculator( getBondingCalculator ).principleValuation( principleToken, depositAmount_ ).div( 1e9 ); uint forLP = value.div( LPProfitShare ); // Amount to give LP rewards contract IERC20Mintable( getManagedToken ).mint( stakingContract, value.sub( forLP ) ); IERC20Mintable( getManagedToken ).mint( LPRewardsContract, forLP ); return true; } // Allows approved depositor to deposit amount_ DAI and receive OHM 1:1 function depositReserves( uint amount_ ) external returns ( bool ) { require( isReserveDepositor[msg.sender] == true, "Not allowed to deposit" ); IERC20( getReserveToken ).safeTransferFrom( msg.sender, address(this), amount_ ); IERC20Mintable( getManagedToken ).mint( msg.sender, amount_.div( 10 ** IERC20( getManagedToken ).decimals() ) ); return true; } // Allows approved depositor to deposit amount_ LP and receive OHM 1:1 with calculated value function depositPrinciple( uint amount_ ) external returns ( bool ) { require( isPrincipleDepositor[msg.sender] == true, "Not allowed to deposit" ); IERC20( getPrincipleToken ).safeTransferFrom( msg.sender, address(this), amount_ ); uint value = IBondingCalculator( getBondingCalculator ).principleValuation( getPrincipleToken, amount_ ).div( 1e9 ); IERC20Mintable( getManagedToken ).mint( msg.sender, value ); return true; } // Sends assets to DAO if timelock has expired (facilitates migrating to new vault contract) function migrateReserveAndPrinciple() external onlyOwner() isTimelockExpired() returns ( bool saveGas_ ) { IERC20( getReserveToken ).safeTransfer( daoWallet, IERC20( getReserveToken ).balanceOf( address( this ) ) ); IERC20( getPrincipleToken ).safeTransfer( daoWallet, IERC20( getPrincipleToken ).balanceOf( address( this ) ) ); return true; } // Sets timelock for migration function setTimelock( uint newTimelockDurationInBlocks_ ) external onlyOwner() returns ( bool ) { require( newTimelockDurationInBlocks_ > timelockDurationInBlocks, "Can only extend timelock" ); timelockDurationInBlocks = newTimelockDurationInBlocks_; return true; } // Starts timelock for migration function startTimelock() external onlyOwner() returns ( bool ) { require( timelockDurationInBlocks > 1, "Timelock Not Set"); getTimelockEndBlock = block.number.add( timelockDurationInBlocks ); emit TimelockStarted( getTimelockEndBlock ); return true; } }// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; /** * @dev Intended to update the TWAP for a token based on accepting an update call from that token. * expectation is to have this happen in the _beforeTokenTransfer function of ERC20. * Provides a method for a token to register its price sourve adaptor. * Provides a function for a token to register its TWAP updater. Defaults to token itself. * Provides a function a tokent to set its TWAP epoch. * Implements automatic closeing and opening up a TWAP epoch when epoch ends. * Provides a function to report the TWAP from the last epoch when passed a token address. */ interface ITWAPOracle { function uniV2CompPairAddressForLastEpochUpdateBlockTimstamp( address ) external returns ( uint32 ); function priceTokenAddressForPricingTokenAddressForLastEpochUpdateBlockTimstamp( address tokenToPrice_, address tokenForPriceComparison_, uint epochPeriod_ ) external returns ( uint32 ); function pricedTokenForPricingTokenForEpochPeriodForPrice( address, address, uint ) external returns ( uint ); function pricedTokenForPricingTokenForEpochPeriodForLastEpochPrice( address, address, uint ) external returns ( uint ); function updateTWAP( address uniV2CompatPairAddressToUpdate_, uint eopchPeriodToUpdate_ ) external returns ( bool ); } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } function _getValues( Set storage set_ ) private view returns ( bytes32[] storage ) { return set_._values; } // TODO needs insert function that maintains order. // TODO needs NatSpec documentation comment. /** * Inserts new value by moving existing value at provided index to end of array and setting provided value at provided index */ function _insert(Set storage set_, uint256 index_, bytes32 valueToInsert_ ) private returns ( bool ) { require( set_._values.length > index_ ); require( !_contains( set_, valueToInsert_ ), "Remove value you wish to insert if you wish to reorder array." ); bytes32 existingValue_ = _at( set_, index_ ); set_._values[index_] = valueToInsert_; return _add( set_, existingValue_); } struct Bytes4Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes4Set storage set, bytes4 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes4Set storage set, bytes4 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes4Set storage set, bytes4 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values on the set. O(1). */ function length(Bytes4Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes4Set storage set, uint256 index) internal view returns ( bytes4 ) { return bytes4( _at( set._inner, index ) ); } function getValues( Bytes4Set storage set_ ) internal view returns ( bytes4[] memory ) { bytes4[] memory bytes4Array_; for( uint256 iteration_ = 0; _length( set_._inner ) > iteration_; iteration_++ ) { bytes4Array_[iteration_] = bytes4( _at( set_._inner, iteration_ ) ); } return bytes4Array_; } function insert( Bytes4Set storage set_, uint256 index_, bytes4 valueToInsert_ ) internal returns ( bool ) { return _insert( set_._inner, index_, valueToInsert_ ); } struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns ( bytes32 ) { return _at(set._inner, index); } function getValues( Bytes32Set storage set_ ) internal view returns ( bytes4[] memory ) { bytes4[] memory bytes4Array_; for( uint256 iteration_ = 0; _length( set_._inner ) >= iteration_; iteration_++ ){ bytes4Array_[iteration_] = bytes4( at( set_, iteration_ ) ); } return bytes4Array_; } function insert( Bytes32Set storage set_, uint256 index_, bytes32 valueToInsert_ ) internal returns ( bool ) { return _insert( set_._inner, index_, valueToInsert_ ); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } /** * TODO Might require explicit conversion of bytes32[] to address[]. * Might require iteration. */ function getValues( AddressSet storage set_ ) internal view returns ( address[] memory ) { address[] memory addressArray; for( uint256 iteration_ = 0; _length(set_._inner) >= iteration_; iteration_++ ){ addressArray[iteration_] = at( set_, iteration_ ); } return addressArray; } function insert(AddressSet storage set_, uint256 index_, address valueToInsert_ ) internal returns ( bool ) { return _insert( set_._inner, index_, bytes32(uint256(valueToInsert_)) ); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } struct UInt256Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UInt256Set storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UInt256Set storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UInt256Set storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UInt256Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UInt256Set storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } 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); } 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. */ 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } /* * Expects percentage to be trailed by 00, */ function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) { return div( mul( total_, percentage_ ), 1000 ); } /* * Expects percentage to be trailed by 00, */ function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) { return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) ); } function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) { return div( mul(part_, 100) , total_ ); } /** * Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol * @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); } function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) { return sqrrt( mul( multiplier_, payment_ ) ); } function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) { return mul( multiplier_, supply_ ); } } abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); // Present in ERC777 mapping (address => uint256) internal _balances; // Present in ERC777 mapping (address => mapping (address => uint256)) internal _allowances; // Present in ERC777 uint256 internal _totalSupply; // Present in ERC777 string internal _name; // Present in ERC777 string internal _symbol; // Present in ERC777 uint8 internal _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } /** * @dev Returns the name of the token. */ // Present in ERC777 function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ // Present in ERC777 function symbol() public view 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 {_setupDecimals} is * called. * * 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}. */ // Present in ERC777 function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ // Present in ERC777 function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ // Present in ERC777 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`. */ // Overrideen in ERC777 // Confirm that this behavior changes function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ // Present in ERC777 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. */ // Present in ERC777 function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, 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`. */ // Present in ERC777 function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); 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(msg.sender, spender, _allowances[msg.sender][spender].add(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) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(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: * * - `to` cannot be the zero address. */ // Present in ERC777 function _mint(address account_, uint256 amount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, amount_); _totalSupply = _totalSupply.add(amount_); _balances[account_] = _balances[account_].add(amount_); emit Transfer(address( this ), 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. */ // Present in ERC777 function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(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. */ // Present in ERC777 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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ // Considering deprication to reduce size of bytecode as changing _decimals to internal acheived the same functionality. // function _setupDecimals(uint8 decimals_) internal { // _decimals = decimals_; // } /** * @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 to 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]. */ // Present in ERC777 function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } interface IERC2612Permit { /** * @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: * * - `owner` cannot be the zero address. * - `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 ERC2612 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); } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } /** * @dev See {IERC2612Permit-permit}. * */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } /** * @dev See {IERC2612Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } interface IOwnable { function owner() external view returns (address); function renounceOwnership() external; function transferOwnership( address newOwner_ ) external; } contract Ownable is IOwnable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = msg.sender; emit OwnershipTransferred( address(0), _owner ); } /** * @dev Returns the address of the current owner. */ function owner() public view override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require( _owner == msg.sender, "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 virtual override 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 virtual override onlyOwner() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred( _owner, newOwner_ ); _owner = newOwner_; } } ///////////////////////////////////////// End of flatten \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ contract VaultOwned is Ownable { address internal _vault; function setVault( address vault_ ) external onlyOwner() returns ( bool ) { _vault = vault_; return true; } /** * @dev Returns the address of the current vault. */ function vault() public view returns (address) { return _vault; } /** * @dev Throws if called by any account other than the vault. */ modifier onlyVault() { require( _vault == msg.sender, "VaultOwned: caller is not the Vault" ); _; } } //SWC-Code With No Effects: L1245-L1303 contract TWAPOracleUpdater is ERC20Permit, VaultOwned { using EnumerableSet for EnumerableSet.AddressSet; event TWAPOracleChanged( address indexed previousTWAPOracle, address indexed newTWAPOracle ); event TWAPEpochChanged( uint previousTWAPEpochPeriod, uint newTWAPEpochPeriod ); event TWAPSourceAdded( address indexed newTWAPSource ); event TWAPSourceRemoved( address indexed removedTWAPSource ); EnumerableSet.AddressSet private _dexPoolsTWAPSources; ITWAPOracle public twapOracle; uint public twapEpochPeriod; constructor( string memory name_, string memory symbol_, uint8 decimals_ ) ERC20(name_, symbol_, decimals_) { } function changeTWAPOracle( address newTWAPOracle_ ) external onlyOwner() { emit TWAPOracleChanged( address(twapOracle), newTWAPOracle_); twapOracle = ITWAPOracle( newTWAPOracle_ ); } function changeTWAPEpochPeriod( uint newTWAPEpochPeriod_ ) external onlyOwner() { require( newTWAPEpochPeriod_ > 0, "TWAPOracleUpdater: TWAP Epoch period must be greater than 0." ); emit TWAPEpochChanged( twapEpochPeriod, newTWAPEpochPeriod_ ); twapEpochPeriod = newTWAPEpochPeriod_; } function addTWAPSource( address newTWAPSourceDexPool_ ) external onlyOwner() { require( _dexPoolsTWAPSources.add( newTWAPSourceDexPool_ ), "OlympusERC20TOken: TWAP Source already stored." ); emit TWAPSourceAdded( newTWAPSourceDexPool_ ); } function removeTWAPSource( address twapSourceToRemove_ ) external onlyOwner() { require( _dexPoolsTWAPSources.remove( twapSourceToRemove_ ), "OlympusERC20TOken: TWAP source not present." ); emit TWAPSourceRemoved( twapSourceToRemove_ ); } function _uodateTWAPOracle( address dexPoolToUpdateFrom_, uint twapEpochPeriodToUpdate_ ) internal { if ( _dexPoolsTWAPSources.contains( dexPoolToUpdateFrom_ )) { twapOracle.updateTWAP( dexPoolToUpdateFrom_, twapEpochPeriodToUpdate_ ); } } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal override virtual { if( _dexPoolsTWAPSources.contains( from_ ) ) { _uodateTWAPOracle( from_, twapEpochPeriod ); } else { if ( _dexPoolsTWAPSources.contains( to_ ) ) { _uodateTWAPOracle( to_, twapEpochPeriod ); } } } } contract Divine is TWAPOracleUpdater { constructor( string memory name_, string memory symbol_, uint8 decimals_ ) TWAPOracleUpdater(name_, symbol_, decimals_) { } } contract OlympusERC20Token is Divine { using SafeMath for uint256; constructor() Divine("Olympus", "OHM", 9) { } function mint(address account_, uint256 amount_) external onlyVault() { _mint(account_, amount_); } function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account_, uint256 amount_) public virtual { _burnFrom(account_, amount_); } function _burnFrom(address account_, uint256 amount_) public virtual { uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub( amount_, "ERC20: burn amount exceeds allowance" ); _approve(account_, msg.sender, decreasedAllowance_); _burn(account_, amount_); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.4; interface IOwnable { function owner() external view returns (address); function renounceOwnership() external; function transferOwnership( address newOwner_ ) external; } contract Ownable is IOwnable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipTransferred( address(0), _owner ); } function owner() public view override returns (address) { return _owner; } modifier onlyOwner() { require( _owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceOwnership() public virtual override onlyOwner() { emit OwnershipTransferred( _owner, address(0) ); _owner = address(0); } function transferOwnership( address newOwner_ ) public virtual override onlyOwner() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred( _owner, newOwner_ ); _owner = newOwner_; } } 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) { 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; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) { return div( mul( total_, percentage_ ), 1000 ); } function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) { return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) ); } function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) { return div( mul(part_, 100) , total_ ); } 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); } function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) { return sqrrt( mul( multiplier_, payment_ ) ); } function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) { return mul( multiplier_, supply_ ); } } library Address { 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present 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(errorMessage); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present 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(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _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) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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); _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 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address( this ), account_, ammount_); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _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 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); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } interface IERC2612Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } 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 { 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "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"); } } } interface IUniswapV2ERC20 { 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; } library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } 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 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // 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); } // 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); } // decode a uq112x112 into a uint with 18 decimals of precision function decode112with18(uq112x112 memory self) internal pure returns (uint) { // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous // instead, get close to: // (x * 1e18) >> 112 // without risk of overflowing, e.g.: // (x) / 2 ** (112 - lg(1e18)) return uint(self._x) / 5192296858534827; } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // 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, "DIV_BY_ZERO"); // return uq112x112((uint224(numerator) << 112) / denominator); // } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // lossy if either numerator or denominator is greater than 112 bits function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } ///////////////////////////////////////// End of flatten \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ interface IPrincipleDepository { function getDepositorInfo( address _depositorAddress_ ) external view returns ( uint principleAmount_, uint interestDue_, uint maturationBlock_ ); function depositBondPrinciple( uint256 amountToDeposit_ ) external returns ( bool ); function depositBondPrincipleWithPermit( uint256 amountToDeposit_, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external returns ( bool ); function redeemBond() external returns ( bool ); function withdrawPrincipleAndForfeitInterest() external returns ( bool ); function calculateBondInterest( uint principleValue_ ) external view returns ( uint interestDue_ ); function calculatePremium() external view returns ( uint _premium ); } interface IBondingCalculator { function principleValuation( address principleTokenAddress_, uint amountDeposited_ ) external view returns ( uint principleValuation_ ); } interface ITreasury { function depositPrinciple( uint depositAmount_ ) external returns ( bool ); } contract OlympusPrincipleDepository is IPrincipleDepository, Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; struct DepositInfo { uint principleAmount; // Amount of LP deposited uint interestDue; // OHM due for bond uint maturationBlock; // Block at which bond matures } mapping( address => DepositInfo ) public depositorInfo; uint public bondControlVariable; // Scaling variable for bond premium uint public bondingPeriodInBlocks; // Length for bonds to vest uint public minPremium; // Minimum premium on bonds address public treasury; // Vault contract address public bondCalculator; address public principleToken; // LP share address public OHM; // Native token uint256 public totalDebt; // Total amount of OHM to be created by bonds address public stakingContract; address public DAOWallet; uint public DAOShare; // DAO share of profits ( % = (1 / DAOshare) ) constructor( address principleToken_, address OHM_ ) { principleToken = principleToken_; OHM = OHM_; } function setAddresses( address bondCalculator_, address treasury_, address stakingContract_, address DAOWallet_, uint DAOShare_ ) external onlyOwner() returns ( bool ) { bondCalculator = bondCalculator_; treasury = treasury_; stakingContract = stakingContract_; DAOWallet = DAOWallet_; DAOShare = DAOShare_; return true; } function setBondTerms( uint bondControlVariable_, uint bondingPeriodInBlocks_, uint minPremium_ ) external onlyOwner() returns ( bool ) { bondControlVariable = bondControlVariable_; bondingPeriodInBlocks = bondingPeriodInBlocks_; minPremium = minPremium_; return true; } // Gets info about depositorAddress's bond deposit // uint _principleAmount = LP deposited // uint _interestDue = OHM due at vesting // uint _maturationBlock = block after which bond matures function getDepositorInfo( address depositorAddress_ ) external view override returns ( uint _principleAmount, uint _interestDue, uint _maturationBlock ) { DepositInfo memory depositorInfo_ = depositorInfo[ depositorAddress_ ]; _principleAmount = depositorInfo_.principleAmount; _interestDue = depositorInfo_.interestDue; _maturationBlock = depositorInfo_.maturationBlock; } // Creates a bond with amountToDeposit LP function depositBondPrinciple( uint amountToDeposit_ ) external override returns ( bool ) { _depositBondPrinciple( amountToDeposit_ ) ; return true; } function depositBondPrincipleWithPermit( uint amountToDeposit_, uint deadline, uint8 v, bytes32 r, bytes32 s ) external override returns ( bool ) { ERC20Permit( principleToken ).permit( msg.sender, address(this), amountToDeposit_, deadline, v, r, s ); _depositBondPrinciple( amountToDeposit_ ) ; return true; } // Values the LP with bonding calculator // Calculates OHM due for that LP // Adds value of LP to totalDebt // Stores bond info function _depositBondPrinciple( uint amountToDeposit_ ) internal returns ( bool ){ IERC20( principleToken ).safeTransferFrom( msg.sender, address(this), amountToDeposit_ ); uint principleValue_ = IBondingCalculator( bondCalculator ) .principleValuation( principleToken, amountToDeposit_ ).div( 1e9 ); uint interestDue_ = _calculateBondInterest( principleValue_ ); require( interestDue_ >= 10000000, "Bond too small" ); totalDebt = totalDebt.add( principleValue ); depositorInfo[msg.sender] = DepositInfo({ principleAmount: depositorInfo[msg.sender].principleAmount.add( amountToDeposit_ ), interestDue: depositorInfo[msg.sender].interestDue.add( interestDue_ ), maturationBlock: block.number.add( bondingPeriodInBlocks ) }); return true; } // Allows user to redeem their bond after it has vested // Calculates profit due to stakers and the DAO // Sends OHM to bonder, stakers, and DAO // Removes bond from total debt function redeemBond() external override returns ( bool ) { require( depositorInfo[msg.sender].interestDue > 0, "Sender is not due any interest." ); require( block.number >= depositorInfo[msg.sender].maturationBlock, "Bond has not matured." ); uint principleAmount_ = depositorInfo[msg.sender].principleAmount; uint interestDue_ = depositorInfo[msg.sender].interestDue; delete depositorInfo[msg.sender]; uint principleValue_ = IBondingCalculator( bondCalculator ) .principleValuation( principleToken, principleAmount_ ).div( 1e9 ); uint profit_ = principleValue.sub( interestDue_ ); uint DAOProfit_ = FixedPoint.fraction( profit_, DAOShare ).decode(); IUniswapV2ERC20( principleToken ).approve( address( treasury ), principleAmount_ ); ITreasury( treasury ).depositPrinciple( principleAmount_ ); IERC20( OHM ).safeTransfer( msg.sender, interestDue_ ); IERC20( OHM ).safeTransfer( stakingContract, profit_.sub( DAOProfit_ ) ); IERC20( OHM ).safeTransfer( DAOWallet, DAOProfit_ ); totalDebt = totalDebt.sub( principleValue_ ); return true; } // Allows user to reclaim their principle by deleting their bond // Removes bond from total debt function withdrawPrincipleAndForfeitInterest() external override returns ( bool ) { uint amountToWithdraw_ = depositorInfo[msg.sender].principleAmount; uint principleValue_ = IBondingCalculator( bondCalculator ) .principleValuation( principleToken, principleAmount_ ).div( 1e9 ); require( amountToWithdraw_ > 0, "user has no principle to withdraw" ); delete depositorInfo[msg.sender]; totalDebt = totalDebt.sub( principleValue_ ); IERC20( principleToken ).safeTransfer( msg.sender, amountToWithdraw_ ); return true; } // Values amountToDeposit LP and calculates interest due (in OHM) for it function calculateBondInterest( uint amountToDeposit_ ) external view override returns ( uint _interestDue ) { uint principleValue_ = IBondingCalculator( bondCalculator ).principleValuation( principleToken, amountToDeposit_ ).div( 1e9 ); _interestDue = _calculateBondInterest( principleValue_ ); } // calculates interest due for a given principleValue (a constant DAI value) // interestDue = (principleValue / premium) function _calculateBondInterest( uint principleValue_ ) internal view returns ( uint _interestDue ) { _interestDue = FixedPoint.fraction( principleValue_, _calcPremium() ).decode112with18().div( 1e16 ); } // View function for calculating the premium function calculatePremium() external view override returns ( uint _premium ) { _premium = _calcPremium(); } // Calculates the premium for bonds // premium = 1 + (debt ratio * bondControlVariable) function _calcPremium() internal view returns ( uint _premium ) { _premium = bondControlVariable.mul( _calcDebtRatio() ).add( uint(1000000000) ).div( 1e7 ); if ( _premium < minPremium ) { _premium = minPremium; } } // Calculates the debt ratio of the system // debt ratio = total debt outstanding / OHM supply function _calcDebtRatio() internal view returns ( uint _debtRatio ) { _debtRatio = FixedPoint.fraction( // Must move the decimal to the right by 9 places to avoid math underflow error totalDebt.mul( 1e9 ), IERC20( OHM ).totalSupply() ).decode112with18().div(1e18); // Must move the decimal tot he left 18 places to account for the 9 places added above and the 19 signnificant digits added by FixedPoint. } }// SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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. */ 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } /* * Expects percentage to be trailed by 00, */ function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) { return div( mul( total_, percentage_ ), 1000 ); } /* * Expects percentage to be trailed by 00, */ function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) { return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) ); } function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) { return div( mul(part_, 100) , total_ ); } /** * Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol * @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); } function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) { return sqrrt( mul( multiplier_, payment_ ) ); } function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) { return mul( multiplier_, supply_ ); } } library Address { /** * @dev Returns true if `account` is 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. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @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]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ // function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { // require(address(this).balance >= value, "Address: insufficient balance for call"); // return _functionCallWithValue(target, data, value, errorMessage); // } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present 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(errorMessage); } } } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present 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(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } interface IOwnable { function owner() external view returns (address); function renounceOwnership() external; function transferOwnership( address newOwner_ ) external; } contract Ownable is IOwnable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = msg.sender; emit OwnershipTransferred( address(0), _owner ); } /** * @dev Returns the address of the current owner. */ function owner() public view override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require( _owner == msg.sender, "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 virtual override 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 virtual override onlyOwner() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred( _owner, newOwner_ ); _owner = newOwner_; } } 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); } abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); // Present in ERC777 mapping (address => uint256) internal _balances; // Present in ERC777 mapping (address => mapping (address => uint256)) internal _allowances; // Present in ERC777 uint256 internal _totalSupply; // Present in ERC777 string internal _name; // Present in ERC777 string internal _symbol; // Present in ERC777 uint8 internal _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } /** * @dev Returns the name of the token. */ // Present in ERC777 function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ // Present in ERC777 function symbol() public view 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 {_setupDecimals} is * called. * * 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}. */ // Present in ERC777 function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ // Present in ERC777 function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ // Present in ERC777 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`. */ // Overrideen in ERC777 // Confirm that this behavior changes function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ // Present in ERC777 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. */ // Present in ERC777 function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, 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`. */ // Present in ERC777 function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); 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(msg.sender, spender, _allowances[msg.sender][spender].add(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) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(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: * * - `to` cannot be the zero address. */ // Present in ERC777 function _mint(address account_, uint256 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address( this ), account_, ammount_); } /** * @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. */ // Present in ERC777 function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(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. */ // Present in ERC777 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 Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ // Considering deprication to reduce size of bytecode as changing _decimals to internal acheived the same functionality. // function _setupDecimals(uint8 decimals_) internal { // _decimals = decimals_; // } /** * @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 to 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]. */ // Present in ERC777 function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } interface IERC2612Permit { /** * @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: * * - `owner` cannot be the zero address. * - `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 ERC2612 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); } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } /** * @dev See {IERC2612Permit-permit}. * */ function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } /** * @dev See {IERC2612Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } ///////////////////////////////////////// End of flatten \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ contract sOlympus is ERC20Permit, Ownable { using SafeMath for uint256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogMonetaryPolicyUpdated(address monetaryPolicy); // Used for authentication address public monetaryPolicy; address public stakingContract; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 500000 * 10**9; // TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; constructor() ERC20("Staked Olympus", "sOHM", 9) { _totalSupply = INITIAL_FRAGMENTS_SUPPLY; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit Transfer(address(0x0), msg.sender, _totalSupply); } function setStakingContract( address newStakingContract_ ) external onlyOwner() { stakingContract = newStakingContract_; _gonBalances[stakingContract] = TOTAL_GONS; } function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner() { monetaryPolicy = monetaryPolicy_; emit LogMonetaryPolicyUpdated(monetaryPolicy_); } // uint256 olyProfit = amount to rebase by (oly is deprecated name for OHM) // returns new rebased total supply function rebase(uint256 olyProfit) public onlyMonetaryPolicy() returns (uint256) { uint256 _rebase; if (olyProfit == 0) { emit LogRebase(block.timestamp, _totalSupply); return _totalSupply; } if(circulatingSupply() > 0 ){ _rebase = olyProfit.mul(_totalSupply).div(circulatingSupply()); } else { _rebase = olyProfit; } _totalSupply = _totalSupply.add(_rebase); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit LogRebase(block.timestamp, _totalSupply); return _totalSupply; } function balanceOf(address who) public view override returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } // supply of sOHM not held by staking contract function circulatingSupply() public view returns (uint) { return _totalSupply.sub(balanceOf(stakingContract)); } // transfers only allowed to staking contract function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { require(msg.sender == stakingContract, 'transfer not from staking contract'); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(msg.sender, to, value); return true; } function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } // transfers only allowed to staking contract function transferFrom(address from, address to, uint256 value) public override validRecipient(to) returns (bool) { require(stakingContract == to, 'transfer from not to staking contract'); _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // What gets called in a permit function _approve(address owner, address spender, uint256 value) internal override virtual { _allowedFragments[owner][spender] = value; emit Approval(owner, spender, value); } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } } /** *Submitted for verification at Etherscan.io on 2021-03-20 */ // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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. */ 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. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 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; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } /* * Expects percentage to be trailed by 00, */ function percentageAmount( uint256 total_, uint8 percentage_ ) internal pure returns ( uint256 percentAmount_ ) { return div( mul( total_, percentage_ ), 1000 ); } /* * Expects percentage to be trailed by 00, */ function substractPercentage( uint256 total_, uint8 percentageToSub_ ) internal pure returns ( uint256 result_ ) { return sub( total_, div( mul( total_, percentageToSub_ ), 1000 ) ); } function percentageOfTotal( uint256 part_, uint256 total_ ) internal pure returns ( uint256 percent_ ) { return div( mul(part_, 100) , total_ ); } /** * Taken from Hypersonic https://github.com/M2629/HyperSonic/blob/main/Math.sol * @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); } function quadraticPricing( uint256 payment_, uint256 multiplier_ ) internal pure returns (uint256) { return sqrrt( mul( multiplier_, payment_ ) ); } function bondingCurve( uint256 supply_, uint256 multiplier_ ) internal pure returns (uint256) { return mul( multiplier_, supply_ ); } } interface IOwnable { function owner() external view returns (address); function renounceOwnership() external; function transferOwnership( address newOwner_ ) external; } contract Ownable is IOwnable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = msg.sender; emit OwnershipTransferred( address(0), _owner ); } /** * @dev Returns the address of the current owner. */ function owner() public view override returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require( _owner == msg.sender, "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 virtual override 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 virtual override onlyOwner() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred( _owner, newOwner_ ); _owner = newOwner_; } } interface IStaking { function initialize( address olyTokenAddress_, address sOLY_, address dai_ ) external; //function stakeOLY(uint amountToStake_) external { function stakeOLYWithPermit ( uint256 amountToStake_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; //function unstakeOLY( uint amountToWithdraw_) external { function unstakeOLYWithPermit ( uint256 amountToWithdraw_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; function stakeOLY( uint amountToStake_ ) external returns ( bool ); function unstakeOLY( uint amountToWithdraw_ ) external returns ( bool ); function distributeOLYProfits() external; } 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); } library Address { /** * @dev Returns true if `account` is 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. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @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]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ // function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { // require(address(this).balance >= value, "Address: insufficient balance for call"); // return _functionCallWithValue(target, data, value, errorMessage); // } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present 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(errorMessage); } } } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present 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(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } 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)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ 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. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "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"); } } } ///////////////////////////////////////// End of flatten \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ interface ITreasury { function getBondingCalculator() external returns ( address ); function payDebt( address depositor_ ) external returns ( bool ); function getTimelockEndBlock() external returns ( uint ); function getManagedToken() external returns ( address ); function getDebtAmountDue() external returns ( uint ); function incurDebt( address principleToken_, uint principieTokenAmountDeposited_ ) external returns ( bool ); } interface IOHMandsOHM { function rebase(uint256 ohmProfit) external returns (uint256); function circulatingSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } contract OlympusStaking is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public epochLengthInBlocks; address public ohm; address public sOHM; uint256 public ohmToDistributeNextEpoch; // used for rebase uint256 nextEpochBlock; bool isInitialized; modifier notInitialized() { require( !isInitialized ); _; } function initialize( address ohmTokenAddress_, address sOHM_, uint8 epochLengthInBlocks_ ) external onlyOwner() notInitialized() { ohm = ohmTokenAddress_; sOHM = sOHM_; epochLengthInBlocks = epochLengthInBlocks_; isInitialized = true; } // typo in function name function setEpochLengthintBlock( uint256 newEpochLengthInBlocks_ ) external onlyOwner() { epochLengthInBlocks = newEpochLengthInBlocks_; } // triggers rebase to distribute accumulated profits to circulating sOHM function _distributeOHMProfits() internal { if( nextEpochBlock <= block.number ) { IOHMandsOHM(sOHM).rebase(ohmToDistributeNextEpoch); uint256 _ohmBalance = IOHMandsOHM(ohm).balanceOf(address(this)); uint256 _sohmSupply = IOHMandsOHM(sOHM).circulatingSupply(); ohmToDistributeNextEpoch = _ohmBalance.sub(_sohmSupply); nextEpochBlock = nextEpochBlock.add( epochLengthInBlocks ); } } // checks for rebase and exchanges OHM 1:1 for sOHM function _stakeOHM( uint256 amountToStake_ ) internal { _distributeOHMProfits(); IERC20(ohm).safeTransferFrom( msg.sender, address(this), amountToStake_ ); IERC20(sOHM).safeTransfer(msg.sender, amountToStake_); } function stakeOHMWithPermit ( uint256 amountToStake_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external { IOHMandsOHM(ohm).permit( msg.sender, address(this), amountToStake_, deadline_, v_, r_, s_ ); _stakeOHM( amountToStake_ ); } // user stakes an amount of OHM to get sOHM function stakeOHM( uint amountToStake_ ) external returns ( bool ) { _stakeOHM( amountToStake_ ); return true; } // checks for rebase and exchanges sOHM 1:1 for OHM function _unstakeOHM( uint256 amountToUnstake_ ) internal { _distributeOHMProfits(); IERC20(sOHM).safeTransferFrom( msg.sender, address(this), amountToUnstake_ ); IERC20(ohm).safeTransfer(msg.sender, amountToUnstake_); } function unstakeOHMWithPermit ( uint256 amountToWithdraw_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external { IOHMandsOHM(sOHM).permit( msg.sender, address(this), amountToWithdraw_, deadline_, v_, r_, s_ ); _unstakeOHM( amountToWithdraw_ ); } // user unstakes an amount of sOHM to get OHM function unstakeOHM( uint amountToWithdraw_ ) external returns ( bool ) { _unstakeOHM( amountToWithdraw_ ); return true; } }
Public SMART CONTRACT AUDIT REPORT for OLYMPUSDAO Prepared By: Shuxiao Wang PeckShield April 9, 2021 1/23 PeckShield Audit Report #: 2021-028Public Document Properties Client OlympusDAO Title Smart Contract Audit Report Target OlympusDAO Version 1.0 Author Xuxian Jiang Auditors Huaguo Shi, Xuxian Jiang Reviewed by Shuxiao Wang Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 April 9, 2021 Xuxian Jiang Final Release 1.0-rc April 3, 2021 Xuxian Jiang Release Candidate #1 0.3 April 1, 2021 Xuxian Jiang Additional Findings #2 0.2 March 28, 2021 Xuxian Jiang Additional Findings #1 0.1 March 25, 2021 Xuxian Jiang Initial Draft 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/23 PeckShield Audit Report #: 2021-028Public Contents 1 Introduction 4 1.1 About OlympusDAO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Caller Authentication Of sOlympusERC20::rebase() . . . . . . . . . . . . . 11 3.2 Potential Rebasing Perturbation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Simplified Logic In BondingCalculator::_principleValuation() . . . . . . . . . . . . . 13 3.4 Proper Initialization Enforcement In sOlympus::setStakingContract() . . . . . . . . . 15 3.5 Improved Decimal Conversion in depositReserves() . . . . . . . . . . . . . . . . . . 16 3.6 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.7 Redundant Code Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 4 Conclusion 21 References 22 3/23 PeckShield Audit Report #: 2021-028Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the OlympusDAO 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 OlympusDAO Olympusis an algorithmic currency protocol based on the OHMtoken. It introduces unique economic and game-theoretic dynamics into the market through asset-backing and protocol owned value. It is a value-backed, self-stabilizing, and decentralized stablecoin with unique collateral backing and algorithmic incentive mechanism. Different from existing stablecoin solutions, it is proposed as a non-pegged stablecoin by exploring a radical opportunity to achieve stability while eliminating dependence on fiat currencies. The basic information of the OlympusDAO protocol is as follows: Table 1.1: Basic Information of The OlympusDAO Protocol ItemDescription IssuerOlympusDAO Website https://olympusdao.eth.link/ TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report April 9, 2021 In the following, we show the Git repository of reviewed files and the commit hash value used in 4/23 PeckShield Audit Report #: 2021-028Public this audit. •https://github.com/OlympusDAO/olympus.git (cdd4afe) 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 5/23 PeckShield Audit Report #: 2021-028Public 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/23 PeckShield Audit Report #: 2021-028Public 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/23 PeckShield Audit Report #: 2021-028Public 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/23 PeckShield Audit Report #: 2021-028Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the OlympusDAO 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 2 Informational 2 Undetermined 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. 9/23 PeckShield Audit Report #: 2021-028Public 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, 2low-severity vulnerabilities, 2informational recommendations, and 1issue with undetermined severity. Table 2.1: Key OlympusDAO Audit Findings ID Severity Title Category Status PVE-001 Low Improved Caller Authentication Of sOlym- pusERC20::rebase()Security Features Fixed PVE-002 Undetermined Potential Rebasing Perturbation Time And State Confirmed PVE-003 Informational Simplified Logic In BondingCalculator::_- principleValuation()Coding Practices Fixed PVE-004 Medium Proper Initialization Enforcement In sOlym- pus::setStakingContract()Security Features Fixed PVE-005 Low Improved Decimal Conversion in depositRe- serves()Business Logic Fixed PVE-006 Medium Trust Issue of Admin Keys Security Features Confirmed PVE-007 Informational Redundant Code Removal Coding Practices 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 details. 10/23 PeckShield Audit Report #: 2021-028Public 3 | Detailed Results 3.1 Improved Caller Authentication Of sOlympusERC20::rebase() •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Low•Target: sOlympusERC20 •Category: Security Features [7] •CWE subcategory: CWE-282 [2] Description In the Olympusprotocol, one core component is the Stakingcontract that allows participants to stake OHMtokens and get sOHMin return. The sOHMtoken is a rebasing, ERC20-compliant one that evenly distributes profits to staking users. While examining the rebasing logic, we notice an authentication issue that needs to be resolved. To elaborate, we show below the rebase() implementation. This function follows a similar imple- mentation from AmpleForth1with internal Gon-based representation. However, we notice this function is protected with a onlyMonetaryPolicy() modifier. This modifier has the requirement of require(msg .sender == monetaryPolicy) , which in essence restricts the caller to be from monetaryPolicy . 1063 function rebase( uint256 olyProfit ) public onlyMonetaryPolicy () returns (uint256 ) { 1064 uint256 _rebase ; 1066 i f( olyProfit == 0) { 1067 emitLogRebase( block.timestamp , _totalSupply) ; 1068 return _totalSupply ; 1069 } 1071 i f( circulatingSupply () > 0 ){ 1072 _rebase = olyProfit .mul(_totalSupply) . div ( circulatingSupply ()) ; 1073 } 1The AmpleForth protocol can be accessed at https://www.ampleforth.org/ 11/23 PeckShield Audit Report #: 2021-028Public 1075 e l s e{ 1076 _rebase = olyProfit ; 1077 } 1079 _totalSupply = _totalSupply .add(_rebase) ; 1082 i f(_totalSupply > MAX_SUPPLY) { 1083 _totalSupply = MAX_SUPPLY; 1084 } 1086 _gonsPerFragment = TOTAL_GONS. div (_totalSupply) ; 1088 emitLogRebase( block.timestamp , _totalSupply) ; 1089 return _totalSupply ; 1090 } Listing 3.1: sOlympusERC20::rebase() Meanwhile, our analysis shows that the only possible caller of rebase() is the Stakingcontract (line 723). With that, there is a need to adjust the modifier to be onlyStakingContract . Certainly, a possible solution will require the Stakingcontract to be the same as monetaryPolicy . Recommendation Properly authenticating the caller of rebaseto be stakingContract , not monetaryPolicy . Or consider the merge of stakingContract and monetaryPolicy as the same entity. Status This issue has been fixed for v2. 3.2 Potential Rebasing Perturbation •ID: PVE-002 •Severity: Undetermined •Likelihood: - •Impact: -•Target: OlympusStaking •Category: Time and State [10] •CWE subcategory: CWE-663 [5] Description Asmentionedearlier, the Olympusprotocolimplementsauniqueexpansionandcontractionmechanism in order to be a stablecoin. In the following, we examine the rebasing mechanism implemented in the protocol. To elaborate, we show below the _distributeOHMProfits() routine that triggers sOHM-rebasing so that the accumulated profits can be evenly distributed to circulating sOHM. Note that the rebasing 12/23 PeckShield Audit Report #: 2021-028Public operation will not be triggered until the current block height reaches the specified nextEpochBlock number. 720 // triggers rebase to distribute accumulated profits to circulating sOHM 721 function _distributeOHMProfits () i n t e r n a l { 722 i f( nextEpochBlock <= block.number ) { 723 IOHMandsOHM(sOHM) . rebase(ohmToDistributeNextEpoch) ; 724 uint256 _ohmBalance = IOHMandsOHM(ohm) . balanceOf( address (t h i s)) ; 725 uint256 _sohmSupply = IOHMandsOHM(sOHM) . circulatingSupply () ; 726 ohmToDistributeNextEpoch = _ohmBalance. sub(_sohmSupply) ; 727 nextEpochBlock = nextEpochBlock .add( epochLengthInBlocks ) ; 728 } 729 } Listing 3.2: OlympusStaking::_distributeOHMProfits() With that, it is possible that right before nextEpochBlock is reached, a user may choose to stake (or unstake) to increase (decrease) the circulating supply of sOHM. Either way, the current rebasing operation as well as the ohmToDistributeNextEpoch amount may be influenced. Note that this is a common sandwich-based arbitrage behavior plaguing current AMM-based DEX solutions. Specifically, a large 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. 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 sandwich arbitrage behavior to better protect the rebasing operation in Olympus. Status The issue has been confirmed. 3.3 Simplified Logic In BondingCalculator::_principleValuation() •ID: PVE-003 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: BondingCalculator •Category: Coding Practices [8] •CWE subcategory: CWE-1099 [1] Description Besides staking, the Olympusprotocol provides the bond mechanism as the secondary strategy to provide a more conservative and reliable return. Specifically, this mechanism quotes the bonder with 13/23 PeckShield Audit Report #: 2021-028Public terms for a trade at a future date and the actual bond amount depends on a bonding curve. There are two main factors, BCVand vesting term . The first factor allows to scale the rate at which bond premiums increase. A higher BCVmeans a lower discount for bonders and less inflation. A lower BCVmeans a higher capacity for bonders and less protocol profit. The vesting term determines how long it takes for bonds to become redeemable. A longer term means lower inflation and lower bond demand. Whileanalyzingthebondingcurve,weobserveanoptimizationintheinternalhelper _principleValuation (). This helper is used to determine the LP share values according to a conservative formula. In the actual calculation at line 628, the ending scaling factor of div(1e10).mul(10) can be simplified as div(1e9). 621 // Values LP share based on formula 622 // returns principleValuation = 2 sqrt ( constant product ) * (% ownership of total LP) 623 // uint k_ = constant product of liquidity pool 624 // uint amountDeposited_ = amount of LP token 625 // uint totalSupplyOfTokenDeposited = total amount of LP 626 function _principleValuation ( uintk_, uintamountDeposited_ , uint totalSupplyOfTokenDeposited_ ) i n t e r n a l pure returns (uintprincipleValuation_ ) { 627 // *** When deposit amount is small does not pick up principle valuation *** \\ 628 principleValuation_ = k_. sqrrt () .mul(2) .mul( FixedPoint . fraction ( amountDeposited_ , totalSupplyOfTokenDeposited_ ) . decode112with18 () . div ( 1e10 ) .mul( 10 ) ) ; 629 } Listing 3.3: BondingCalculator:: _principleValuation () Recommendation Simplify the scaling operation on the helper routine to calculate the principle valuation. Status This issue has been fixed for v2. 14/23 PeckShield Audit Report #: 2021-028Public 3.4 Proper Initialization Enforcement In sOlympus::setStakingContract() •ID: PVE-004 •Severity: Medium •Likelihood: Low •Impact: High•Target: sOlympus •Category: Security Features [7] •CWE subcategory: CWE-282 [2] Description As mentioned in Section 3.1, one core component of Olympusis the Stakingcontract that allows participants to stake OHMtokens and get sOHMin return. While examining the sOHMtoken contract, we notice a privileged operation setStakingContract() that is designed to initialize the stakingContract address and its internal Gonbalance. To elaborate, we show below the setStakingContract() implementation from the sOHMtoken con- tract, i.e., sOlympus. While it indeed properly sets up the stakingContract address and initializes the Gonbalance, this initialization operation should only occur once. Otherwise, the sOHMsupply may go awry, resulting in protocol-wide instability. 1051 function setStakingContract ( address newStakingContract_ ) external onlyOwner() { 1052 stakingContract = newStakingContract_ ; 1053 _gonBalances [ stakingContract ] = TOTAL_GONS; 1054 } Listing 3.4: sOlympus::setStakingContract() Recommendation Ensure the setStakingContract() can only be initialized once. Status This issue has been fixed for v2. 15/23 PeckShield Audit Report #: 2021-028Public 3.5 Improved Decimal Conversion in depositReserves() •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Low•Target: Vault •Category: Business Logic [9] •CWE subcategory: CWE-841 [6] Description The Olympusprotocol has a treasury contract, i.e., Vault, that allows for taking reserve tokens (e.g., DAI) and minting managed tokens (e.g., OHM). The treasury contact can also take the principle tokens (e..g, OHM-DAI SLP ) and mint the managed tokens according to the bonding curve-based principle evaluation. In the following, we examine the conversions from reserve tokens to managed tokens. The conversion logic is implemented in the depositReserves() routine. To elaborate, we show below its code. It comes to our attention that the conversion logic is coded as amount_.div(10 ** IERC20(getManagedToken).decimals()) . Note that the given amount is denominated at the reserve token DAIand the minted amount is in the unit of managed token ( OHM). With that, the proper calcu- lation of the converted amount should be the following: amount_.mul(10 ** IERC20(getManagedToken) .decimals()).div(10**IERC20(getReserveToken).decimals()) . 448 function depositReserves ( uintamount_ ) external returns (bool) { 449 require ( isReserveDepositor [ msg.sender] == true," Not allowed to deposit " ) ; 450 IERC20( getReserveToken ) . safeTransferFrom( msg.sender,address (t h i s) , amount_ ) ; 451 IERC20Mintable( getManagedToken ) . mint( msg.sender, amount_. div ( 10 ∗∗IERC20( getManagedToken ) . decimals () ) ) ; 452 return true ; 453 } Listing 3.5: Vault:: isReserveDepositor() Fortunately, themanagedtoken OHMhasthedecimalof 9andthereservetoken DAIhasthedecimal of18. As a result, it still results in the same converted (absolute) amount. However, the revised conversion logic is generic in accommodating other token setups, especially when the managed token does not have 9as its decimal. Recommendation Revise the isReserveDepositor() logic by following the correct decimal conversion. Status This issue has been fixed for v2. 16/23 PeckShield Audit Report #: 2021-028Public 3.6 Trust Issue of Admin Keys •ID: PVE-006 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: OlympusERC20 •Category: Security Features [7] •CWE subcategory: CWE-287 [3] Description In the OlympusDAO protocol, there is a privileged owner account plays a critical role in governing the treasury contract ( Vault) and regulating the OHMtoken contract. In the following, we show representative privileged operations in the Olympusprotocol. 378 function setDAOWallet( address newDAOWallet_ ) external onlyOwner() returns (bool) { 379 daoWallet = newDAOWallet_; 380 return true ; 381 } 383 function setStakingContract ( address newStakingContract_ ) external onlyOwner() returns (bool) { 384 stakingContract = newStakingContract_ ; 385 return true ; 386 } 388 function setLPRewardsContract( address newLPRewardsContract_ ) external onlyOwner() returns (bool) { 389 LPRewardsContract = newLPRewardsContract_; 390 return true ; 391 } 393 function setLPProfitShare ( uintnewDAOProfitShare_ ) external onlyOwner() returns ( bool) { 394 LPProfitShare = newDAOProfitShare_; 395 return true ; 396 } Listing 3.6: Example Privileged Operations in Vault function setVault ( address vault_ ) external onlyOwner() returns (bool) { _vault = vault_ ; return true ; } function mint( address account_ , uint256 amount_) external onlyVault () { _mint(account_ , amount_) ; 17/23 PeckShield Audit Report #: 2021-028Public } Listing 3.7: Example Privileged Operations in OlympusERC20Token We emphasize that the privilege assignment with various factory 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 change current vaultto mint arbitrary number of OHMor change other settings (e.g., stakingContract ) to steal funds of currently staking users, which directly undermines the integrity of the Olympusprotocol. 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. It is in place with the purpose as being a helper function to facilitate reward distribution. Note this functionality has been offloaded to a separate contract. And all of these have been removed for v2. 3.7 Redundant Code Removal •ID: PVE-007 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: OlympusERC20, Vault •Category: Coding Practices [8] •CWE subcategory: CWE-563 [4] Description OlympusDAO makes good use of a number of reference contracts, such as ERC20,SafeERC20 ,SafeMath, and Ownable, to facilitate its code implementation and organization. For example, the Vaultsmart contract has so far imported at least five 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 the isReserveToken state variable, it is designed to determine whether a given token is a reserve token. However, apparently, the current version does not make use of this state variable. 1245 contract TWAPOracleUpdater i sERC20Permit , VaultOwned { 1246 1247 usingEnumerableSet forEnumerableSet . AddressSet ; 1248 18/23 PeckShield Audit Report #: 2021-028Public 1249 eventTWAPOracleChanged( address indexed previousTWAPOracle , address indexed newTWAPOracle ) ; 1250 eventTWAPEpochChanged( uintpreviousTWAPEpochPeriod , uintnewTWAPEpochPeriod ) ; 1251 eventTWAPSourceAdded( address indexed newTWAPSource ) ; 1252 eventTWAPSourceRemoved( address indexed removedTWAPSource ) ; 1253 1254 EnumerableSet . AddressSet private _dexPoolsTWAPSources; 1255 1256 ITWAPOracle public twapOracle ; 1257 1258 uint public twapEpochPeriod ; 1259 1260 constructor ( 1261 s t r i n g memory name_, 1262 s t r i n g memory symbol_ , 1263 uint8decimals_ 1264 ) ERC20(name_, symbol_ , decimals_) { 1265 } 1266 1267 function changeTWAPOracle( address newTWAPOracle_ ) external onlyOwner() { 1268 emitTWAPOracleChanged( address (twapOracle) , newTWAPOracle_) ; 1269 twapOracle = ITWAPOracle( newTWAPOracle_ ) ; 1270 } 1271 1272 function changeTWAPEpochPeriod( uintnewTWAPEpochPeriod_ ) external onlyOwner() { 1273 require ( newTWAPEpochPeriod_ > 0, " TWAPOracleUpdater : TWAP Epoch period must be greater than 0." ) ; 1274 emitTWAPEpochChanged( twapEpochPeriod , newTWAPEpochPeriod_ ) ; 1275 twapEpochPeriod = newTWAPEpochPeriod_; 1276 } 1277 1278 function addTWAPSource( address newTWAPSourceDexPool_ ) external onlyOwner() { 1279 require ( _dexPoolsTWAPSources.add( newTWAPSourceDexPool_ ) , " OlympusERC20TOken : TWAP Source already stored ." ) ; 1280 emitTWAPSourceAdded( newTWAPSourceDexPool_ ) ; 1281 } 1282 1283 function removeTWAPSource( address twapSourceToRemove_ ) external onlyOwner() { 1284 require ( _dexPoolsTWAPSources.remove( twapSourceToRemove_ ) , " OlympusERC20TOken : TWAP source not present ." ) ; 1285 emitTWAPSourceRemoved( twapSourceToRemove_ ) ; 1286 } 1287 1288 function _uodateTWAPOracle( address dexPoolToUpdateFrom_ , uint twapEpochPeriodToUpdate_ ) i n t e r n a l { 1289 i f( _dexPoolsTWAPSources. contains ( dexPoolToUpdateFrom_ )) { 1290 twapOracle .updateTWAP( dexPoolToUpdateFrom_ , twapEpochPeriodToUpdate_ ) ; 1291 } 1292 } 1293 1294 function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) i n t e r n a l override virtual { 19/23 PeckShield Audit Report #: 2021-028Public 1295 i f( _dexPoolsTWAPSources. contains ( from_ ) ) { 1296 _uodateTWAPOracle( from_, twapEpochPeriod ) ; 1297 }e l s e{ 1298 i f( _dexPoolsTWAPSources. contains ( to_ ) ) { 1299 _uodateTWAPOracle( to_, twapEpochPeriod ) ; 1300 } 1301 } 1302 } 1303} Listing 3.8: The TWAPOracleUpdater Contract Moreover, the current implementation includes a contract TWAPOracleUpdater that is supposed to be inherited by the OHMtoken contract. However, this TWAPOracleUpdater contract is currently not used and thus can be safely removed. Recommendation Consider the removal of the redundant code with a simplified, consistent implementation. Status The issue has been confirmed. The team has integrated TWAP code, which will be utilized in future versions. 20/23 PeckShield Audit Report #: 2021-028Public 4 | Conclusion In this audit, we have analyzed the design and implementation of Olympus, which utilizes the protocol owned value to enable price consistency and scarcity within an infinite supply system. During the audit, we notice that the current implementation still remains to be completed, though the overall 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. 21/23 PeckShield Audit Report #: 2021-028Public References [1] MITRE. CWE-1099: Inconsistent Naming Conventions for Identifiers. https://cwe.mitre.org/ data/definitions/1099.html. [2] MITRE. CWE-282: ImproperOwnershipManagement. https://cwe.mitre.org/data/definitions/ 282.html. [3] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [4] MITRE. CWE-563: Assignment to Variable without Use. https://cwe.mitre.org/data/ definitions/563.html. [5] MITRE. CWE-663: Use of a Non-reentrant Function in a Concurrent Context. https://cwe. mitre.org/data/definitions/663.html. [6] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [7] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.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. 22/23 PeckShield Audit Report #: 2021-028Public [10] MITRE. CWE CATEGORY: Concurrency. https://cwe.mitre.org/data/definitions/557.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. 23/23 PeckShield Audit Report #: 2021-028
1. Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 1 - Major: 0 - Critical: 0 2. Minor Issues 2.a Problem (one line with code reference) - Improved Caller Authentication Of sOlympusERC20::rebase(): No authentication for the caller of the rebase() function. 2.b Fix (one line with code reference) - Add authentication for the caller of the rebase() function. 3. Moderate 3.a Problem (one line with code reference) - Potential Rebasing Perturbation: The rebase() function can be called multiple times in a single block, leading to potential perturbation. 3.b Fix (one line with code reference) - Add a check to ensure that the rebase() function is only called once per block. 4. Major - None 5. Critical - None 6. Observations - The OlympusDAO protocol is based on the OHMtoken. - There are several issues related to either security or performance that can be improved. 7. Conclusion The audit of the OlympusDAO protocol revealed 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): Unnecessary code in the contract (line 590) 2.b Fix (one line with code reference): Remove the unnecessary code (line 590) Moderate: None Major: None Critical: None Observations: - The OlympusDAO protocol is a non-pegged stablecoin with unique collateral backing and algorithmic incentive mechanism. - The audit was conducted using a whitebox method. - The audit was conducted using the OWASP Risk Rating Methodology. Conclusion: The audit of the OlympusDAO protocol was conducted successfully and no critical issues were found. 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 External Call (CWE-699) 2.b Fix (one line with code reference): Check the return value of external calls Moderate 3.a Problem (one line with code reference): Reentrancy (CWE-699) 3.b Fix (one line with code reference): Use the check-effects-interactions pattern 3.c Problem (one line with code reference): Money-Giving Bug (CWE-699) 3.d Fix (one line with code reference): Use the check-effects-interactions pattern 3.e Problem (one line with code reference): Unauthorized Self-Destruct (CWE-699) 3.f Fix (one line with code reference): Use the check-effects-interactions pattern Observations - The audit was conducted according to the procedure of Basic Coding Bugs, Semantic Consistency Checks, Advanced DeFi Scrutiny and Additional Recommendations.
pragma solidity 0.5.13; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "hardhat/console.sol"; import './lib/CloneFactory.sol'; import "./interfaces/ITreasury.sol"; import './interfaces/IRCMarket.sol'; import './interfaces/IRCProxyXdai.sol'; import './interfaces/IRCNftHubXdai.sol'; import './lib/NativeMetaTransaction.sol'; /// @title Reality Cards Factory /// @author Andrew Stanger /// @notice If you have found a bug, please contact andrew@realitycards.io- no hack pls!! contract RCFactory is Ownable, CloneFactory, NativeMetaTransaction { using SafeMath for uint256; using SafeMath for uint32; //////////////////////////////////// //////// VARIABLES ///////////////// //////////////////////////////////// ///// CONTRACT VARIABLES ///// ITreasury public treasury; IRCProxyXdai public proxy; IRCNftHubXdai public nfthub; ///// CONTRACT ADDRESSES ///// /// @dev reference contract address public referenceContractAddress; /// @dev increments each time a new reference contract is added uint256 public referenceContractVersion; /// @dev market addresses, mode // address /// @dev these are not used for anything, just an easy way to get markets mapping(uint256 => address[]) public marketAddresses; mapping(address => bool) public mappingOfMarkets; ///// GOVERNANCE VARIABLES- OWNER ///// /// @dev artist / winner / market creator / affiliate / card affiliate uint256[5] public potDistribution; /// @dev minimum xDai that must be sent when creating market which forms iniital pot uint256 public sponsorshipRequired; /// @dev adjust required price increase (in %) uint256 public minimumPriceIncrease; /// @dev market opening time must be at least this many seconds in the future uint32 public advancedWarning; /// @dev market closing time must be no more than this many seconds in the future uint32 public maximumDuration; /// @dev if hot potato mode, how much rent new owner must pay current owner (1 week divisor: i.e. 7 = 1 day's rent, 14 = 12 hours's rent) uint256 public hotPotatoDivisor; /// @dev list of governors mapping(address => bool) public governors; /// @dev if false, anyone can create markets bool public marketCreationGovernorsOnly = true; /// @dev if true, cards are burnt at the end of events for hidden markets to enforce scarcity bool public trapIfUnapproved = true; /// @dev high level owner who can change the factory address address public uberOwner; ///// GOVERNANCE VARIABLES- GOVERNORS ///// /// @dev unapproved markets hidden from the interface mapping(address => bool) public isMarketApproved; /// @dev allows artist to receive cut of total rent mapping(address => bool) public isArtistApproved; /// @dev allows affiliate to receive cut of total rent mapping(address => bool) public isAffiliateApproved; /// @dev allows card affiliate to receive cut of total rent mapping(address => bool) public isCardAffiliateApproved; ///// OTHER ///// /// @dev counts the total NFTs minted across all events /// @dev ... so the appropriate token id is used when upgrading to mainnet uint256 public totalNftMintCount; //////////////////////////////////// //////// EVENTS //////////////////// //////////////////////////////////// event LogMarketCreated1(address contractAddress, address treasuryAddress, address nftHubAddress, uint256 referenceContractVersion); event LogMarketCreated2(address contractAddress, uint32 mode, string[] tokenURIs, string ipfsHash, uint32[] timestamps, uint256 totalNftMintCount); event LogMarketApproved(address market, bool hidden); event LogAdvancedWarning(uint256 _newAdvancedWarning); event LogMaximumDuration(uint256 _newMaximumDuration); //////////////////////////////////// //////// CONSTRUCTOR /////////////// //////////////////////////////////// /// @dev Treasury must be deployed before Factory constructor(ITreasury _treasuryAddress) public { // initialise MetaTransactions _initializeEIP712("RealityCardsFactory","1"); // at initiation, uberOwner and owner will be the same uberOwner = msg.sender; // initialise contract variable treasury = _treasuryAddress; // initialise adjustable parameters // artist // winner // creator // affiliate // card affiliates setPotDistribution(20,0,0,20,100); // 2% artist, 2% affiliate, 10% card affiliate setMinimumPriceIncrease(10); // 10% setHotPotatoPayment(7); // one day's rent } //////////////////////////////////// ///////// VIEW FUNCTIONS /////////// //////////////////////////////////// function getMostRecentMarket(uint256 _mode) public view returns (address) { return marketAddresses[_mode][marketAddresses[_mode].length-1]; } function getAllMarkets(uint256 _mode) public view returns (address[] memory) { return marketAddresses[_mode]; } function getPotDistribution() public view returns (uint256[5] memory) { return potDistribution; } //////////////////////////////////// //////////// MODIFERS ////////////// //////////////////////////////////// modifier onlyGovernors() { require(governors[msgSender()] || owner() == msgSender(), "Not approved"); _; } //////////////////////////////////// ///// GOVERNANCE- OWNER (SETUP) //// //////////////////////////////////// /// @dev all functions should have onlyOwner modifier /// @notice address of the xDai Proxy contract function setProxyXdaiAddress(IRCProxyXdai _newAddress) external onlyOwner { proxy = _newAddress; } /// @notice where the NFTs live /// @dev nftMintCount will probably need to be reset to zero if new nft contract, but /// @dev ... keeping flexible in case returning to previous contract function setNftHubAddress(IRCNftHubXdai _newAddress, uint256 _newNftMintCount) external onlyOwner { nfthub = _newAddress; totalNftMintCount = _newNftMintCount; } //////////////////////////////////// /////// GOVERNANCE- OWNER ////////// //////////////////////////////////// /// @dev all functions should have onlyOwner modifier // Min price increase, pot distribution & hot potato events emitted by Market. // Advanced Warning and Maximum Duration events emitted here. Nothing else need be emitted. /// CALLED WITHIN CONSTRUCTOR (public) /// @notice update stakeholder payouts /// @dev in 10s of basis points (so 1000 = 100%) function setPotDistribution(uint256 _artistCut, uint256 _winnerCut, uint256 _creatorCut, uint256 _affiliateCut, uint256 _cardAffiliateCut) public onlyOwner { require(_artistCut.add(_affiliateCut).add(_creatorCut).add(_winnerCut).add(_affiliateCut).add(_cardAffiliateCut) <= 1000, "Cuts too big"); potDistribution[0] = _artistCut; potDistribution[1] = _winnerCut; potDistribution[2] = _creatorCut; potDistribution[3] = _affiliateCut; potDistribution[4] = _cardAffiliateCut; } /// @notice how much above the current price a user must bid, in % function setMinimumPriceIncrease(uint256 _percentIncrease) public onlyOwner { minimumPriceIncrease = _percentIncrease; } /// @dev if hot potato mode, how much rent new owner must pay current owner (1 week divisor: i.e. 7 = 1 day, 14 = 12 hours) function setHotPotatoPayment(uint256 _newDivisor) public onlyOwner { hotPotatoDivisor = _newDivisor; } /// NOT CALLED WITHIN CONSTRUCTOR (external) /// @notice whether or not only governors can create the market function setMarketCreationGovernorsOnly() external onlyOwner { marketCreationGovernorsOnly = marketCreationGovernorsOnly ? false : true; } /// @notice how much xdai must be sent in the createMarket tx which forms the initial pot function setSponsorshipRequired(uint256 _dai) external onlyOwner { sponsorshipRequired = _dai; } /// @notice if true, Cards in unapproved markets can't be upgraded function setTrapCardsIfUnapproved() onlyOwner external { trapIfUnapproved = trapIfUnapproved ? false : true; } /// @notice market opening time must be at least this many seconds in the future function setAdvancedWarning(uint32 _newAdvancedWarning) onlyOwner external { advancedWarning = _newAdvancedWarning; emit LogAdvancedWarning(_newAdvancedWarning); } /// @notice market closing time must be no more than this many seconds in the future function setMaximumDuration(uint32 _newMaximumDuration) onlyOwner external { maximumDuration = _newMaximumDuration; emit LogMaximumDuration(_newMaximumDuration); } // EDIT GOVERNORS /// @notice add or remove an address from market creator whitelist function addOrRemoveGovernor(address _governor) external onlyOwner { governors[_governor] = governors[_governor] ? false : true; } //////////////////////////////////// ///// GOVERNANCE- GOVERNORS //////// //////////////////////////////////// /// @dev all functions should have onlyGovernors modifier /// @notice markets are default hidden from the interface, this reveals them function approveOrUnapproveMarket(address _market) external onlyGovernors { isMarketApproved[_market] = isMarketApproved[_market] ? false : true; emit LogMarketApproved(_market, isMarketApproved[_market]); } /// @notice artistAddress, passed in createMarket, must be approved function addOrRemoveArtist(address _artist) external onlyGovernors { isArtistApproved[_artist] = isArtistApproved[_artist] ? false : true; } /// @notice affiliateAddress, passed in createMarket, must be approved function addOrRemoveAffiliate(address _affiliate) external onlyGovernors { isAffiliateApproved[_affiliate] = isAffiliateApproved[_affiliate] ? false : true; } /// @notice cardAffiliateAddress, passed in createMarket, must be approved function addOrRemoveCardAffiliate(address _affiliate) external onlyGovernors { isCardAffiliateApproved[_affiliate] = isCardAffiliateApproved[_affiliate] ? false : true; } //////////////////////////////////// ////// GOVERNANCE- UBER OWNER ////// //////////////////////////////////// //// ******** DANGER ZONE ******** //// /// @dev uber owner required for upgrades /// @dev this is seperated so owner so can be set to multisig, or burn address to relinquish upgrade ability /// @dev ... while maintaining governance over other governanace functions /// @notice change the reference contract for the contract logic function setReferenceContractAddress(address _newAddress) external { require(msg.sender == uberOwner, "Extremely Verboten"); // check it's an RC contract IRCMarket newContractVariable = IRCMarket(_newAddress); assert(newContractVariable.isMarket()); // set referenceContractAddress = _newAddress; // increment version referenceContractVersion = referenceContractVersion.add(1); } function changeUberOwner(address _newUberOwner) external { require(msg.sender == uberOwner, "Extremely Verboten"); uberOwner = _newUberOwner; } //////////////////////////////////// //////// MARKET CREATION /////////// //////////////////////////////////// /// @param _mode 0 = normal, 1 = winner takes all, 2 = hot potato /// @param _timestamps for market opening, locking, and oracle resolution /// @param _tokenURIs location of NFT metadata /// @param _artistAddress where to send artist's cut, if any /// @param _affiliateAddress where to send affiliate's cut, if any /// @param _cardAffiliateAddresses where to send card specific affiliate's cut, if any /// @param _realitioQuestion the details of the event to send to the oracle function createMarket( uint32 _mode, string memory _ipfsHash, uint32[] memory _timestamps, string[] memory _tokenURIs, address _artistAddress, address _affiliateAddress, address[] memory _cardAffiliateAddresses, string memory _realitioQuestion ) public payable returns (address) { // check sponsorship require(msg.value >= sponsorshipRequired, "Insufficient sponsorship"); // check stakeholder addresses // artist require(isArtistApproved[_artistAddress] || _artistAddress == address(0), "Artist not approved"); // affiliate require(isAffiliateApproved[_affiliateAddress] || _affiliateAddress == address(0), "Affiliate not approved"); // card affiliates for (uint i = 0; i < _cardAffiliateAddresses.length; i++) { require(isCardAffiliateApproved[_cardAffiliateAddresses[i]] || _cardAffiliateAddresses[i] == address(0), "Card affiliate not approved"); } // check market creator is approved if (marketCreationGovernorsOnly) { require(governors[msgSender()] || owner() == msgSender(), "Not approved"); } // check timestamps // check market opening time if (advancedWarning != 0) { require(_timestamps[0] >= now, "Market opening time not set"); require(_timestamps[0].sub(advancedWarning) > now, "Market opens too soon" ); } // check market locking time if (maximumDuration != 0) { require(_timestamps[1] < now.add(maximumDuration), "Market locks too late"); } // check oracle resolution time (no more than 1 week after market locking to get result) require(_timestamps[1].add(1 weeks) > _timestamps[2] && _timestamps[1] <= _timestamps[2], "Oracle resolution time error" ); uint256 _numberOfTokens = _tokenURIs.length; // create the market and emit the appropriate events // two events to avoid stack too deep error address _newAddress = createClone(referenceContractAddress); emit LogMarketCreated1(_newAddress, address(treasury), address(nfthub), referenceContractVersion); emit LogMarketCreated2(_newAddress, _mode, _tokenURIs, _ipfsHash, _timestamps, totalNftMintCount); IRCMarket(_newAddress).initialize({ _mode: _mode, _timestamps: _timestamps, _numberOfTokens: _numberOfTokens, _totalNftMintCount: totalNftMintCount, _artistAddress: _artistAddress, _affiliateAddress: _affiliateAddress, _cardAffiliateAddresses: _cardAffiliateAddresses, _marketCreatorAddress: msgSender() }); // create the NFTs require(address(nfthub) != address(0), "Nfthub not set"); for (uint i = 0; i < _numberOfTokens; i++) { uint256 _tokenId = i.add(totalNftMintCount); assert(nfthub.mintNft(_newAddress, _tokenId, _tokenURIs[i])); } // increment totalNftMintCount totalNftMintCount = totalNftMintCount.add(_numberOfTokens); // post question to Oracle require(address(proxy) != address(0), "xDai proxy not set"); proxy.saveQuestion(_newAddress, _realitioQuestion, _timestamps[2]); // tell Treasury, Proxy, and NFT hub about new market assert(treasury.addMarket(_newAddress)); assert(proxy.addMarket(_newAddress)); assert(nfthub.addMarket(_newAddress)); // update internals marketAddresses[_mode].push(_newAddress); mappingOfMarkets[_newAddress] = true; // pay sponsorship, if applicable if (msg.value > 0) { IRCMarket(_newAddress).sponsor.value(msg.value)(); } return _newAddress; } } 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.13; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "hardhat/console.sol"; import './lib/NativeMetaTransaction.sol'; /// @title Reality Cards Treasury /// @author Andrew Stanger /// @notice If you have found a bug, please contact andrew@realitycards.io- no hack pls!! contract RCTreasury is Ownable, NativeMetaTransaction { using SafeMath for uint256; //////////////////////////////////// //////// VARIABLES ///////////////// //////////////////////////////////// /// @dev address of the Factory so only the Factory can add new markets address public factoryAddress; /// @dev so only markets can use certain functions mapping (address => bool) public isMarket; /// @dev the deposit balance of each user mapping (address => uint256) public deposits; /// @dev sum of all deposits uint256 public totalDeposits; /// @dev the rental payments made in each market mapping (address => uint256) public marketPot; /// @dev sum of all market pots uint256 public totalMarketPots; /// @dev sum of prices of all Cards a user is renting mapping (address => uint256) public userTotalRentals; /// @dev when a user most recently rented (to prevent users withdrawing within minRentalTime) mapping (address => uint256) public lastRentalTime; ///// GOVERNANCE VARIABLES ///// /// @dev only parameters that need to be are here, the rest are in the Factory /// @dev minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins) uint256 public minRentalDivisor; /// @dev max deposit balance, to minimise funds at risk uint256 public maxContractBalance; ///// SAFETY ///// /// @dev if true, cannot deposit, withdraw or rent any cards across all events bool public globalPause; /// @dev if true, cannot rent any cards for specific market mapping (address => bool) public marketPaused; ///// UBER OWNER ///// /// @dev high level owner who can change the factory address address public uberOwner; //////////////////////////////////// //////// EVENTS //////////////////// //////////////////////////////////// event LogDepositIncreased(address indexed sentBy, uint256 indexed daiDeposited); event LogDepositWithdrawal(address indexed returnedTo, uint256 indexed daiWithdrawn); event LogAdjustDeposit(address indexed user, uint256 indexed amount, bool increase); event LogHotPotatoPayment(address from, address to, uint256 amount); //////////////////////////////////// //////// CONSTRUCTOR /////////////// //////////////////////////////////// constructor() public { // initialise MetaTransactions _initializeEIP712("RealityCardsTreasury","1"); // at initiation, uberOwner and owner will be the same uberOwner = msg.sender; // initialise adjustable parameters setMinRental(24*6); // ten mins setMaxContractBalance(1000000 ether); // 1m } //////////////////////////////////// /////////// MODIFIERS ////////////// //////////////////////////////////// modifier balancedBooks { _; // using >= not == because forced Ether send via selfdestruct will not trigger a deposit via the fallback // SWC-Integer Overflow and Underflow: L85 assert(address(this).balance >= totalDeposits + totalMarketPots); } modifier onlyMarkets { require(isMarket[msg.sender], "Not authorised"); _; } //////////////////////////////////// //////////// ADD MARKETS /////////// //////////////////////////////////// /// @dev so only markets can move funds from deposits to marketPots and vice versa function addMarket(address _newMarket) external returns(bool) { require(msg.sender == factoryAddress, "Not factory"); isMarket[_newMarket] = true; return true; } //////////////////////////////////// /////// GOVERNANCE- OWNER ////////// //////////////////////////////////// /// @dev all functions should be onlyOwner // min rental event emitted by market. Nothing else need be emitted. /// CALLED WITHIN CONSTRUCTOR (public) /// @notice minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins) function setMinRental(uint256 _newDivisor) public onlyOwner { minRentalDivisor = _newDivisor; } /// @dev max deposit balance, to minimise funds at risk function setMaxContractBalance(uint256 _newBalanceLimit) public onlyOwner { maxContractBalance = _newBalanceLimit; } /// NOT CALLED WITHIN CONSTRUCTOR (external) /// @dev if true, cannot deposit, withdraw or rent any cards function setGlobalPause() external onlyOwner { globalPause = globalPause ? false : true; } /// @dev if true, cannot rent any cards for specific market function setPauseMarket(address _market) external onlyOwner { marketPaused[_market] = marketPaused[_market] ? false : true; } //////////////////////////////////// ////// GOVERNANCE- UBER OWNER ////// //////////////////////////////////// //// ******** DANGER ZONE ******** //// /// @dev uber owner required for upgrades /// @dev deploying and setting a new factory is effectively an upgrade /// @dev this is seperated so owner so can be set to multisig, or burn address to relinquish upgrade ability /// @dev ... while maintaining governance over other governanace functions function setFactoryAddress(address _newFactory) external { require(msg.sender == uberOwner, "Extremely Verboten"); factoryAddress = _newFactory; } function changeUberOwner(address _newUberOwner) external { require(msg.sender == uberOwner, "Extremely Verboten"); uberOwner = _newUberOwner; } //////////////////////////////////// /// DEPOSIT & WITHDRAW FUNCTIONS /// //////////////////////////////////// /// @dev it is passed the user instead of using msg.sender because might be called /// @dev ... via contract (fallback, newRental) or dai->xdai bot function deposit(address _user) public payable balancedBooks returns(bool) { require(!globalPause, "Deposits are disabled"); require(msg.value > 0, "Must deposit something"); require(address(this).balance <= maxContractBalance, "Limit hit"); deposits[_user] = deposits[_user].add(msg.value); totalDeposits = totalDeposits.add(msg.value); emit LogDepositIncreased(_user, msg.value); emit LogAdjustDeposit(_user, msg.value, true); return true; } /// @dev this is the only function where funds leave the contract function withdrawDeposit(uint256 _dai) external balancedBooks { require(!globalPause, "Withdrawals are disabled"); require(deposits[msgSender()] > 0, "Nothing to withdraw"); require(now.sub(lastRentalTime[msgSender()]) > uint256(1 days).div(minRentalDivisor), "Too soon"); if (_dai > deposits[msgSender()]) { _dai = deposits[msgSender()]; } deposits[msgSender()] = deposits[msgSender()].sub(_dai); totalDeposits = totalDeposits.sub(_dai); address _thisAddressNotPayable = msgSender(); address payable _recipient = address(uint160(_thisAddressNotPayable)); (bool _success, ) = _recipient.call.value(_dai)(""); require(_success, "Transfer failed"); emit LogDepositWithdrawal(msgSender(), _dai); emit LogAdjustDeposit(msgSender(), _dai, false); } //////////////////////////////////// ////// MARKET CALLABLE ////// //////////////////////////////////// /// only markets can call these functions /// @dev a rental payment is equivalent to moving to market pot from user's deposit, called by _collectRent in the market function payRent(address _user, uint256 _dai) external balancedBooks onlyMarkets returns(bool) { require(!globalPause, "Rentals are disabled"); require(!marketPaused[msg.sender], "Rentals are disabled"); assert(deposits[_user] >= _dai); // assert because should have been reduced to user's deposit already deposits[_user] = deposits[_user].sub(_dai); marketPot[msg.sender] = marketPot[msg.sender].add(_dai); totalMarketPots = totalMarketPots.add(_dai); totalDeposits = totalDeposits.sub(_dai); emit LogAdjustDeposit(_user, _dai, false); return true; } /// @dev a payout is equivalent to moving from market pot to user's deposit (the opposite of payRent) function payout(address _user, uint256 _dai) external balancedBooks onlyMarkets returns(bool) { assert(marketPot[msg.sender] >= _dai); deposits[_user] = deposits[_user].add(_dai); marketPot[msg.sender] = marketPot[msg.sender].sub(_dai); totalMarketPots = totalMarketPots.sub(_dai); totalDeposits = totalDeposits.add(_dai); emit LogAdjustDeposit(_user, _dai, true); return true; } /// @notice ability to add liqudity to the pot without being able to win (called by market sponsor function). function sponsor() external payable balancedBooks onlyMarkets returns(bool) { marketPot[msg.sender] = marketPot[msg.sender].add(msg.value); totalMarketPots = totalMarketPots.add(msg.value); return true; } /// @dev new owner pays current owner for hot potato mode function processHarbergerPayment(address _newOwner, address _currentOwner, uint256 _requiredPayment) external balancedBooks onlyMarkets returns(bool) { require(deposits[_newOwner] >= _requiredPayment, "Insufficient deposit"); deposits[_newOwner] = deposits[_newOwner].sub(_requiredPayment); deposits[_currentOwner] = deposits[_currentOwner].add(_requiredPayment); emit LogAdjustDeposit(_newOwner, _requiredPayment, false); emit LogAdjustDeposit(_currentOwner, _requiredPayment, true); emit LogHotPotatoPayment(_newOwner, _currentOwner, _requiredPayment); return true; } /// @dev tracks when the user last rented- so they cannot rent and immediately withdraw, thus bypassing minimum rental duration function updateLastRentalTime(address _user) external onlyMarkets returns(bool) { lastRentalTime[_user] = now; return true; } /// @dev tracks the total rental payments across all Cards, to enforce minimum rental duration function updateTotalRental(address _user, uint256 _newPrice, bool _add) external onlyMarkets returns(bool) { if (_add) { userTotalRentals[_user] = userTotalRentals[_user].add(_newPrice); } else { userTotalRentals[_user] = userTotalRentals[_user].sub(_newPrice); } return true; } //////////////////////////////////// ////////// FALLBACK ///////// //////////////////////////////////// /// @dev sending ether/xdai direct is equal to a deposit function() external payable { assert(deposit(msgSender())); } } pragma solidity 0.5.13; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "hardhat/console.sol"; import "./interfaces/IRealitio.sol"; import "./interfaces/IFactory.sol"; import "./interfaces/ITreasury.sol"; import './interfaces/IRCProxyXdai.sol'; import './interfaces/IRCNftHubXdai.sol'; import './lib/NativeMetaTransaction.sol'; /// @title Reality Cards Market /// @author Andrew Stanger /// @notice If you have found a bug, please contact andrew@realitycards.io- no hack pls!! contract RCMarket is Initializable, NativeMetaTransaction { using SafeMath for uint256; //////////////////////////////////// //////// VARIABLES ///////////////// //////////////////////////////////// ///// CONTRACT SETUP ///// /// @dev = how many outcomes/teams/NFTs etc uint256 public numberOfTokens; /// @dev only for _revertToUnderbidder to prevent gas limits uint256 public constant MAX_ITERATIONS = 10; uint256 public constant MAX_UINT256 = 2**256 - 1; uint256 public constant MAX_UINT128 = 2**128 - 1; enum States {CLOSED, OPEN, LOCKED, WITHDRAW} States public state; /// @dev type of event. 0 = classic, 1 = winner takes all, 2 = hot potato uint256 public mode; /// @dev so the Factory can check its a market bool public constant isMarket = true; /// @dev counts the total NFTs minted across all events at the time market created /// @dev nft tokenId = card Id + totalNftMintCount uint256 public totalNftMintCount; ///// CONTRACT VARIABLES ///// ITreasury public treasury; IFactory public factory; IRCProxyXdai public proxy; IRCNftHubXdai public nfthub; ///// PRICE, DEPOSITS, RENT ///// /// @dev in attodai (so 100xdai = 100000000000000000000) mapping (uint256 => uint256) public price; /// @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, for card specific affiliate payout mapping (uint256 => uint256) public collectedPerToken; /// @dev an easy way to track the above across all tokens uint256 public totalCollected; /// @dev prevents user from exiting and re-renting in the same block (prevents troll attacks) mapping (address => uint256) public exitedTimestamp; ///// PARAMETERS ///// /// @dev read from the Factory upon market creation, can not be changed for existing market /// @dev the minimum required price increase in % uint256 public minimumPriceIncrease; /// @dev minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins) uint256 public minRentalDivisor; /// @dev if hot potato mode, how much rent new owner must pay current owner (1 week divisor: i.e. 7 = 1 day, 14 = 12 hours) uint256 public hotPotatoDivisor; ///// ORDERBOOK ///// /// @dev stores the orderbook. Doubly linked list. mapping (uint256 => mapping(address => Bid)) public orderbook; // tokenID // user address // Bid /// @dev orderbook uses uint128 to save gas, because Struct. Using uint256 everywhere else because best for maths. struct Bid{ uint128 price; uint128 timeHeldLimit; // users can optionally set a maximum time to hold it for address next; // who it will return to when current owner exits (i.e, next = going down the list) address prev; // who it returned from (i.e., prev = going up the list) } ///// 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. Used 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 to track the max timeheld of each token (for giving NFT to winner) mapping (uint256 => uint256) public longestTimeHeld; /// @dev to track who has owned it the most (for giving NFT to winner) mapping (uint256 => address) public longestOwner; /// @dev tells the contract to exit position after min rental duration (or immediately, if already rented for this long) /// @dev if not current owner, prevents ownership reverting back to you ///// TIMESTAMPS ///// /// @dev when the market opens uint32 public marketOpeningTime; /// @dev when the market locks uint32 public marketLockingTime; /// @dev when the question can be answered on realitio /// @dev only needed for circuit breaker uint32 public oracleResolutionTime; ///// PAYOUT VARIABLES ///// uint256 public winningOutcome; /// @dev prevent users withdrawing twice mapping (address => bool) public userAlreadyWithdrawn; /// @dev prevent users claiming twice mapping (uint256 => mapping (address => bool) ) public userAlreadyClaimed; // token ID // user // bool /// @dev the artist address public artistAddress; uint256 public artistCut; bool public artistPaid; /// @dev the affiliate address public affiliateAddress; uint256 public affiliateCut; bool public affiliatePaid; /// @dev the winner uint256 public winnerCut; /// @dev the market creator address public marketCreatorAddress; uint256 public creatorCut; bool public creatorPaid; /// @dev card specific recipients address[] public cardAffiliateAddresses; uint256 public cardAffiliateCut; mapping (uint256 => bool) public cardAffiliatePaid; //////////////////////////////////// //////// EVENTS //////////////////// //////////////////////////////////// event LogAddToOrderbook(address indexed newOwner, uint256 indexed newPrice, uint256 timeHeldLimit, address insertedBelow, uint256 indexed tokenId); event LogNewOwner(uint256 indexed tokenId, address indexed newOwner); event LogRentCollection(uint256 indexed rentCollected, uint256 indexed tokenId, address indexed owner); event LogRemoveFromOrderbook(address indexed owner, uint256 indexed tokenId); event LogContractLocked(bool indexed didTheEventFinish); event LogWinnerKnown(uint256 indexed winningOutcome); event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid); event LogStakeholderPaid(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); event LogStateChange(uint256 indexed newState); event LogUpdateTimeHeldLimit(address indexed owner, uint256 newLimit, uint256 tokenId); event LogExit(address indexed owner, uint256 tokenId); event LogSponsor(address indexed sponsor, uint256 indexed amount); event LogNftUpgraded(uint256 indexed currentTokenId, uint256 indexed newTokenId); event LogPayoutDetails(address indexed artistAddress, address marketCreatorAddress, address affiliateAddress, address[] cardAffiliateAddresses, uint256 indexed artistCut, uint256 winnerCut, uint256 creatorCut, uint256 affiliateCut, uint256 cardAffiliateCut); event LogTransferCardToLongestOwner(uint256 tokenId, address longestOwner); event LogSettings(uint256 indexed minRentalDivisor, uint256 indexed minimumPriceIncrease, uint256 hotPotatoDivisor); //////////////////////////////////// //////// CONSTRUCTOR /////////////// //////////////////////////////////// /// @param _mode 0 = normal, 1 = winner takes all, 2 = hot potato /// @param _timestamps for market opening, locking, and oracle resolution /// @param _numberOfTokens how many Cards in this market /// @param _totalNftMintCount total existing Cards across all markets excl this event's Cards /// @param _artistAddress where to send artist's cut, if any /// @param _affiliateAddress where to send affiliate's cut, if any /// @param _cardAffiliateAddresses where to send card specific affiliate's cut, if any /// @param _marketCreatorAddress where to send market creator's cut, if any function initialize( uint256 _mode, uint32[] memory _timestamps, uint256 _numberOfTokens, uint256 _totalNftMintCount, address _artistAddress, address _affiliateAddress, address[] memory _cardAffiliateAddresses, address _marketCreatorAddress ) public initializer { assert(_mode <= 2); // initialise MetaTransactions _initializeEIP712("RealityCardsMarket","1"); // external contract variables: factory = IFactory(msg.sender); treasury = factory.treasury(); proxy = factory.proxy(); nfthub = factory.nfthub(); // get adjustable parameters from the factory/treasury uint256[5] memory _potDistribution = factory.getPotDistribution(); minRentalDivisor = treasury.minRentalDivisor(); minimumPriceIncrease = factory.minimumPriceIncrease(); hotPotatoDivisor = factory.hotPotatoDivisor(); // initialiiize! winningOutcome = MAX_UINT256; // default invalid // assign arguments to public variables mode = _mode; numberOfTokens = _numberOfTokens; totalNftMintCount = _totalNftMintCount; marketOpeningTime = _timestamps[0]; marketLockingTime = _timestamps[1]; oracleResolutionTime = _timestamps[2]; artistAddress = _artistAddress; marketCreatorAddress = _marketCreatorAddress; affiliateAddress = _affiliateAddress; cardAffiliateAddresses = _cardAffiliateAddresses; artistCut = _potDistribution[0]; winnerCut = _potDistribution[1]; creatorCut = _potDistribution[2]; affiliateCut = _potDistribution[3]; cardAffiliateCut = _potDistribution[4]; // reduce artist cut to zero if zero adddress set if (_artistAddress == address(0)) { artistCut = 0; } // reduce affiliate cut to zero if zero adddress set if (_affiliateAddress == address(0)) { affiliateCut = 0; } // check the validity of card affiliate array. // if not valid, reduce payout to zero if (_cardAffiliateAddresses.length == _numberOfTokens) { for (uint i = 0; i < _numberOfTokens; i++) { if (_cardAffiliateAddresses[i] == address(0)) { cardAffiliateCut = 0; } } } else { cardAffiliateCut = 0; } // if winner takes all mode, set winnerCut to max if (_mode == 1) { winnerCut = (((uint256(1000).sub(artistCut)).sub(creatorCut)).sub(affiliateCut)).sub(cardAffiliateCut); } // move to OPEN immediately if market opening time in the past if (marketOpeningTime <= now) { _incrementState(); } emit LogPayoutDetails(_artistAddress, _marketCreatorAddress, _affiliateAddress, cardAffiliateAddresses, artistCut, winnerCut, creatorCut, affiliateCut, cardAffiliateCut); emit LogSettings(minRentalDivisor, minimumPriceIncrease, hotPotatoDivisor); } //////////////////////////////////// /////////// MODIFIERS ////////////// //////////////////////////////////// /// @dev automatically opens market if appropriate modifier autoUnlock() { if (marketOpeningTime <= now && state == States.CLOSED) { _incrementState(); } _; } /// @dev automatically locks market if appropriate modifier autoLock() { _; if (marketLockingTime <= now) { lockMarket(); } } /// @notice what it says on the tin modifier onlyTokenOwner(uint256 _tokenId) { require(msgSender() == ownerOf(_tokenId), "Not owner"); _; } //////////////////////////////////// //// ORACLE PROXY CONTRACT CALLS /// //////////////////////////////////// /// @notice send NFT to mainnet /// @dev upgrades not possible if market not approved function upgradeCard(uint256 _tokenId) external onlyTokenOwner(_tokenId) { _checkState(States.WITHDRAW); require(!factory.trapIfUnapproved() || factory.isMarketApproved(address(this)), "Upgrade blocked"); string memory _tokenUri = tokenURI(_tokenId); address _owner = ownerOf(_tokenId); uint256 _actualTokenId = _tokenId.add(totalNftMintCount); proxy.saveCardToUpgrade(_actualTokenId, _tokenUri, _owner); _transferCard(ownerOf(_tokenId), address(this), _tokenId); // contract becomes final resting place emit LogNftUpgraded(_tokenId, _actualTokenId); } //////////////////////////////////// /////// NFT HUB CONTRACT CALLS ///// //////////////////////////////////// /// @notice gets the owner of the NFT via their Card Id function ownerOf(uint256 _tokenId) public view returns(address) { uint256 _actualTokenId = _tokenId.add(totalNftMintCount); return nfthub.ownerOf(_actualTokenId); } /// @notice gets tokenURI via their Card Id function tokenURI(uint256 _tokenId) public view returns(string memory) { uint256 _actualTokenId = _tokenId.add(totalNftMintCount); return nfthub.tokenURI(_actualTokenId); } /// @notice transfer ERC 721 between users function _transferCard(address _from, address _to, uint256 _tokenId) internal { require(_from != address(0) && _to != address(0) , "Cannot send to/from zero address"); uint256 _actualTokenId = _tokenId.add(totalNftMintCount); assert(nfthub.transferNft(_from, _to, _actualTokenId)); emit LogNewOwner(_tokenId, _to); } //////////////////////////////////// //// MARKET RESOLUTION FUNCTIONS /// //////////////////////////////////// /// @notice checks whether the competition has ended, if so moves to LOCKED state /// @dev can be called by anyone /// @dev public because called within autoLock modifier & setWinner function lockMarket() public { _checkState(States.OPEN); require(marketLockingTime < now, "Market has not finished"); // do a final rent collection before the contract is locked down collectRentAllCards(); _incrementState(); emit LogContractLocked(true); } /// @notice called by proxy, sets the winner function setWinner(uint256 _winningOutcome) external { if (state == States.OPEN) { lockMarket(); } _checkState(States.LOCKED); require(msg.sender == address(proxy), "Not proxy"); // get the winner. This will revert if answer is not resolved. winningOutcome = _winningOutcome; _incrementState(); emit LogWinnerKnown(winningOutcome); } /// @notice pays out winnings, or returns funds /// @dev public because called by withdrawWinningsAndDeposit function withdraw() external { _checkState(States.WITHDRAW); require(!userAlreadyWithdrawn[msgSender()], "Already withdrawn"); userAlreadyWithdrawn[msgSender()] = true; if (totalTimeHeld[winningOutcome] > 0) { _payoutWinnings(); } else { _returnRent(); } } /// @notice the longest owner of each NFT gets to keep it /// @dev LOCKED or WITHDRAW states are fine- does not need to wait for winner to be known function claimCard(uint256 _tokenId) external { _checkNotState(States.CLOSED); _checkNotState(States.OPEN); require(!userAlreadyClaimed[_tokenId][msgSender()], "Already claimed"); userAlreadyClaimed[_tokenId][msgSender()] = true; require(longestOwner[_tokenId] == msgSender(), "Not longest owner"); _transferCard(ownerOf(_tokenId), longestOwner[_tokenId], _tokenId); } /// @notice pays winnings function _payoutWinnings() internal { uint256 _winningsToTransfer; uint256 _remainingCut = ((((uint256(1000).sub(artistCut)).sub(affiliateCut))).sub(cardAffiliateCut).sub(winnerCut)).sub(creatorCut); // calculate longest owner's extra winnings, if relevant if (longestOwner[winningOutcome] == msgSender() && winnerCut > 0){ _winningsToTransfer = (totalCollected.mul(winnerCut)).div(1000); } // calculate normal winnings, if any uint256 _remainingPot = (totalCollected.mul(_remainingCut)).div(1000); uint256 _winnersTimeHeld = timeHeld[winningOutcome][msgSender()]; uint256 _numerator = _remainingPot.mul(_winnersTimeHeld); _winningsToTransfer = _winningsToTransfer.add(_numerator.div(totalTimeHeld[winningOutcome])); require(_winningsToTransfer > 0, "Not a winner"); _payout(msgSender(), _winningsToTransfer); emit LogWinningsPaid(msgSender(), _winningsToTransfer); } /// @notice returns all funds to users in case of invalid outcome function _returnRent() internal { // deduct artist share and card specific share if relevant but NOT market creator share or winner's share (no winner, market creator does not deserve) uint256 _remainingCut = ((uint256(1000).sub(artistCut)).sub(affiliateCut)).sub(cardAffiliateCut); uint256 _rentCollected = collectedPerUser[msgSender()]; require(_rentCollected > 0, "Paid no rent"); uint256 _rentCollectedAdjusted = (_rentCollected.mul(_remainingCut)).div(1000); _payout(msgSender(), _rentCollectedAdjusted); emit LogRentReturned(msgSender(), _rentCollectedAdjusted); } /// @notice all payouts happen through here function _payout(address _recipient, uint256 _amount) internal { assert(treasury.payout(_recipient, _amount)); } /// @dev the below functions pay stakeholders (artist, creator, affiliate, card specific affiliates) /// @dev they are not called within determineWinner() because of the risk of an /// @dev .... address being a contract which refuses payment, then nobody could get winnings /// @notice pay artist function payArtist() external { _checkState(States.WITHDRAW); require(!artistPaid, "Artist already paid"); artistPaid = true; _processStakeholderPayment(artistCut, artistAddress); } /// @notice pay market creator function payMarketCreator() external { _checkState(States.WITHDRAW); require(totalTimeHeld[winningOutcome] > 0, "No winner"); require(!creatorPaid, "Creator already paid"); creatorPaid = true; _processStakeholderPayment(creatorCut, marketCreatorAddress); } /// @notice pay affiliate function payAffiliate() external { _checkState(States.WITHDRAW); require(!affiliatePaid, "Affiliate already paid"); affiliatePaid = true; _processStakeholderPayment(affiliateCut, affiliateAddress); } /// @notice pay card affiliate /// @dev does not call _processStakeholderPayment because it works differently function payCardAffiliate(uint256 _tokenId) external { _checkState(States.WITHDRAW); require(!cardAffiliatePaid[_tokenId], "Card affiliate already paid"); cardAffiliatePaid[_tokenId] = true; uint256 _cardAffiliatePayment = (collectedPerToken[_tokenId].mul(cardAffiliateCut)).div(1000); if (_cardAffiliatePayment > 0) { _payout(cardAffiliateAddresses[_tokenId], _cardAffiliatePayment); emit LogStakeholderPaid(cardAffiliateAddresses[_tokenId], _cardAffiliatePayment); } } function _processStakeholderPayment(uint256 _cut, address _recipient) internal { if (_cut > 0) { uint256 _payment = (totalCollected.mul(_cut)).div(1000); _payout(_recipient, _payment); emit LogStakeholderPaid(_recipient, _payment); } } //////////////////////////////////// ///// CORE FUNCTIONS- EXTERNAL ///// //////////////////////////////////// /// @dev basically functions that have _checkState(States.OPEN) on first line /// @notice collects rent for all tokens /// @dev cannot be external because it is called within the lockMarket function, therefore public function collectRentAllCards() public { _checkState(States.OPEN); for (uint i = 0; i < numberOfTokens; i++) { _collectRent(i); } } /// @notice rent every Card at the minimum price function rentAllCards(uint256 _maxSumOfPrices) external { // check that not being front run uint256 _actualSumOfPrices; for (uint i = 0; i < numberOfTokens; i++) { _actualSumOfPrices = _actualSumOfPrices.add(price[i]); } require(_actualSumOfPrices <= _maxSumOfPrices, "Prices too high"); for (uint i = 0; i < numberOfTokens; i++) { if (ownerOf(i) != msgSender()) { uint _newPrice; if (price[i]>0) { _newPrice = (price[i].mul(minimumPriceIncrease.add(100))).div(100); } else { _newPrice = 1 ether; } newRental(_newPrice, 0, address(0), i); } } } /// @notice to rent a Card /// @dev no event: it is emitted in _updateBid, _setNewOwner or _placeInList as appropriate function newRental(uint256 _newPrice, uint256 _timeHeldLimit, address _startingPosition, uint256 _tokenId) public payable autoUnlock() autoLock() returns (uint256) { _checkState(States.OPEN); require(_newPrice >= 1 ether, "Minimum rental 1 xDai"); require(_tokenId < numberOfTokens, "This token does not exist"); require(exitedTimestamp[msgSender()] != now, "Cannot lose and re-rent in same block"); _collectRent(_tokenId); // process deposit, if sent if (msg.value > 0) { assert(treasury.deposit.value(msg.value)(msgSender())); } // check sufficient deposit uint256 _updatedTotalRentals = treasury.userTotalRentals(msgSender()).add(_newPrice); require(treasury.deposits(msgSender()) >= _updatedTotalRentals.div(minRentalDivisor), "Insufficient deposit"); // check _timeHeldLimit if (_timeHeldLimit == 0) { _timeHeldLimit = MAX_UINT128; // so 0 defaults to no limit } uint256 _minRentalTime = uint256(1 days).div(minRentalDivisor); require(_timeHeldLimit >= timeHeld[_tokenId][msgSender()].add(_minRentalTime), "Limit too low"); // must be after collectRent so timeHeld is up to date // if not in the orderbook, _newBid else _updateBid if (orderbook[_tokenId][msgSender()].price == 0) { _newBid(_newPrice, _tokenId, _timeHeldLimit, _startingPosition); } else { _updateBid(_newPrice, _tokenId, _timeHeldLimit, _startingPosition); } assert(treasury.updateLastRentalTime(msgSender())); return price[_tokenId]; } /// @notice to change your timeHeldLimit without having to re-rent function updateTimeHeldLimit(uint256 _timeHeldLimit, uint256 _tokenId) external { _checkState(States.OPEN); _collectRent(_tokenId); if (_timeHeldLimit == 0) { _timeHeldLimit = MAX_UINT128; // so 0 defaults to no limit } uint256 _minRentalTime = uint256(1 days).div(minRentalDivisor); require(_timeHeldLimit >= timeHeld[_tokenId][msgSender()].add(_minRentalTime), "Limit too low"); // must be after collectRent so timeHeld is up to date orderbook[_tokenId][msgSender()].timeHeldLimit = SafeCast.toUint128(_timeHeldLimit); emit LogUpdateTimeHeldLimit(msgSender(), _timeHeldLimit, _tokenId); } /// @notice stop renting a token and/or remove from orderbook /// @dev public because called by exitAll() /// @dev doesn't need to be current owner so user can prevent ownership returning to them /// @dev does not apply minimum rental duration, because it returns ownership to the next user function exit(uint256 _tokenId) public { _checkState(States.OPEN); // if current owner, collect rent, revert if necessary if (ownerOf(_tokenId) == msgSender()) { // collectRent first _collectRent(_tokenId); // if still the current owner after collecting rent, revert to underbidder if (ownerOf(_tokenId) == msgSender()) { _revertToUnderbidder(_tokenId); // if not current owner no further action necessary because they will have been deleted from the orderbook } else { assert(orderbook[_tokenId][msgSender()].price == 0); } // if not owner, just delete from orderbook } else { orderbook[_tokenId][orderbook[_tokenId][msgSender()].next].prev = orderbook[_tokenId][msgSender()].prev; orderbook[_tokenId][orderbook[_tokenId][msgSender()].prev].next = orderbook[_tokenId][msgSender()].next; delete orderbook[_tokenId][msgSender()]; emit LogRemoveFromOrderbook(msgSender(), _tokenId); } emit LogExit(msgSender(), _tokenId); } /// @notice stop renting all tokens function exitAll() external { for (uint i = 0; i < numberOfTokens; i++) { exit(i); } } /// @notice ability to add liqudity to the pot without being able to win. function sponsor() external payable { _checkNotState(States.LOCKED); _checkNotState(States.WITHDRAW); require(msg.value > 0, "Must send something"); // send funds to the Treasury assert(treasury.sponsor.value(msg.value)()); totalCollected = totalCollected.add(msg.value); // just so user can get it back if invalid outcome collectedPerUser[msgSender()] = collectedPerUser[msgSender()].add(msg.value); // allocate equally to each token, in case card specific affiliates for (uint i = 0; i < numberOfTokens; i++) { collectedPerToken[i] = collectedPerToken[i].add(msg.value.div(numberOfTokens)); } emit LogSponsor(msg.sender, msg.value); } //////////////////////////////////// ///// CORE 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 { uint256 _timeOfThisCollection = now; //only collect rent if the token is owned (ie, if owned by the contract this implies unowned) if (ownerOf(_tokenId) != address(this)) { uint256 _rentOwed = price[_tokenId].mul(now.sub(timeLastCollected[_tokenId])).div(1 days); address _collectRentFrom = ownerOf(_tokenId); uint256 _deposit = treasury.deposits(_collectRentFrom); // get the maximum rent they can pay based on timeHeldLimit uint256 _rentOwedLimit; uint256 _timeHeldLimit = orderbook[_tokenId][_collectRentFrom].timeHeldLimit; if (_timeHeldLimit == MAX_UINT128) { _rentOwedLimit = MAX_UINT256; } else { _rentOwedLimit = price[_tokenId].mul(_timeHeldLimit.sub(timeHeld[_tokenId][_collectRentFrom])).div(1 days); } // if rent owed is too high, reduce if (_rentOwed >= _deposit || _rentOwed >= _rentOwedLimit) { // case 1: rentOwed is reduced to _deposit if (_deposit <= _rentOwedLimit) { _timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(_deposit).div(_rentOwed))); _rentOwed = _deposit; // take what's left // case 2: rentOwed is reduced to _rentOwedLimit } else { _timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(_rentOwedLimit).div(_rentOwed))); _rentOwed = _rentOwedLimit; // take up to the max } _revertToUnderbidder(_tokenId); } if (_rentOwed > 0) { // decrease deposit by rent owed at the Treasury assert(treasury.payRent(_collectRentFrom, _rentOwed)); // update internals uint256 _timeHeldToIncrement = (_timeOfThisCollection.sub(timeLastCollected[_tokenId])); timeHeld[_tokenId][_collectRentFrom] = timeHeld[_tokenId][_collectRentFrom].add(_timeHeldToIncrement); totalTimeHeld[_tokenId] = totalTimeHeld[_tokenId].add(_timeHeldToIncrement); collectedPerUser[_collectRentFrom] = collectedPerUser[_collectRentFrom].add(_rentOwed); collectedPerToken[_tokenId] = collectedPerToken[_tokenId].add(_rentOwed); totalCollected = totalCollected.add(_rentOwed); // longest owner tracking if (timeHeld[_tokenId][_collectRentFrom] > longestTimeHeld[_tokenId]) { longestTimeHeld[_tokenId] = timeHeld[_tokenId][_collectRentFrom]; longestOwner[_tokenId] = _collectRentFrom; } emit LogTimeHeldUpdated(timeHeld[_tokenId][_collectRentFrom], _collectRentFrom, _tokenId); emit LogRentCollection(_rentOwed, _tokenId, _collectRentFrom); } } // 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] = _timeOfThisCollection; } /// @dev user is not in the orderbook function _newBid(uint256 _newPrice, uint256 _tokenId, uint256 _timeHeldLimit, address _startingPosition) internal { // check user not in the orderbook assert(orderbook[_tokenId][msgSender()].price == 0); uint256 _minPriceToOwn = (price[_tokenId].mul(minimumPriceIncrease.add(100))).div(100); // case 1: user is sufficiently above highest bidder (or only bidder) if(ownerOf(_tokenId) == address(this) || _newPrice >= _minPriceToOwn) { _setNewOwner(_newPrice, _tokenId, _timeHeldLimit); } else { // case 2: user is not sufficiently above highest bidder _placeInList(_newPrice, _tokenId, _timeHeldLimit, _startingPosition); } } /// @dev user is already in the orderbook function _updateBid(uint256 _newPrice, uint256 _tokenId, uint256 _timeHeldLimit, address _startingPosition) internal { uint256 _minPriceToOwn; // ensure user is in the orderbook assert(orderbook[_tokenId][msgSender()].price > 0); // case 1: user is currently the owner if(msgSender() == ownerOf(_tokenId)) { _minPriceToOwn = (price[_tokenId].mul(minimumPriceIncrease.add(100))).div(100); // case 1A: new price is at least X% above current price- adjust price & timeHeldLimit. newRental event required. if(_newPrice >= _minPriceToOwn) { orderbook[_tokenId][msgSender()].price = SafeCast.toUint128(_newPrice); orderbook[_tokenId][msgSender()].timeHeldLimit = SafeCast.toUint128(_timeHeldLimit); _processUpdateOwner(_newPrice, _tokenId); emit LogAddToOrderbook(msgSender(), _newPrice, _timeHeldLimit, orderbook[_tokenId][msgSender()].prev, _tokenId); // case 1B: new price is higher than current price but by less than X%- revert the tx to prevent frontrunning } else if (_newPrice > price[_tokenId]) { // SWC-Requirement Violation: L685 require(false, "Not 10% higher"); // case 1C: new price is equal or below old price } else { _minPriceToOwn = (uint256(orderbook[_tokenId][orderbook[_tokenId][msgSender()].next].price).mul(minimumPriceIncrease.add(100))).div(100); // case 1Ca: still the highest owner- adjust price & timeHeldLimit. newRental event required. if(_newPrice >= _minPriceToOwn) { orderbook[_tokenId][msgSender()].price = SafeCast.toUint128(_newPrice); orderbook[_tokenId][msgSender()].timeHeldLimit = SafeCast.toUint128(_timeHeldLimit); _processUpdateOwner(_newPrice, _tokenId); emit LogAddToOrderbook(msgSender(), _newPrice, _timeHeldLimit, orderbook[_tokenId][msgSender()].prev, _tokenId); // case 1Cb: user is not owner anymore- remove from list & add back. newRental event called in _setNewOwner or _placeInList via _newBid } else { _revertToUnderbidder(_tokenId); _newBid(_newPrice, _tokenId, _timeHeldLimit, _startingPosition); } } // case 2: user is not currently the owner- remove and add them back } else { // remove from the list orderbook[_tokenId][orderbook[_tokenId][msgSender()].prev].next = orderbook[_tokenId][msgSender()].next; orderbook[_tokenId][orderbook[_tokenId][msgSender()].next].prev = orderbook[_tokenId][msgSender()].prev; delete orderbook[_tokenId][msgSender()]; // no LogRemoveFromOrderbook they are being added right back _minPriceToOwn = (price[_tokenId].mul(minimumPriceIncrease.add(100))).div(100); // case 2A: should be owner, add on top. newRental event called in _setNewOwner if(_newPrice >= _minPriceToOwn) { _setNewOwner(_newPrice, _tokenId, _timeHeldLimit); // case 2B: should not be owner, add to list. newRental event called in _placeInList } else { _placeInList(_newPrice, _tokenId, _timeHeldLimit, _startingPosition); } } } /// @dev only for when user is NOT already in the list and IS the highest bidder function _setNewOwner(uint256 _newPrice, uint256 _tokenId, uint256 _timeHeldLimit) internal { // if hot potato mode, pay current owner if (mode == 2) { uint256 _duration = uint256(1 weeks).div(hotPotatoDivisor); uint256 _requiredPayment = (price[_tokenId].mul(_duration)).div(uint256(1 days)); assert(treasury.processHarbergerPayment(msgSender(), ownerOf(_tokenId), _requiredPayment)); } // process new owner orderbook[_tokenId][msgSender()] = Bid(SafeCast.toUint128(_newPrice), SafeCast.toUint128(_timeHeldLimit), ownerOf(_tokenId), address(this)); orderbook[_tokenId][ownerOf(_tokenId)].prev = msgSender(); // _processNewOwner must be after LogAddToOrderbook so LogNewOwner is not emitted before user is in the orderbook emit LogAddToOrderbook(msgSender(), _newPrice, _timeHeldLimit, address(this), _tokenId); _processNewOwner(msgSender(), _newPrice, _tokenId); } /// @dev only for when user is NOT already in the list and NOT the highest bidder function _placeInList(uint256 _newPrice, uint256 _tokenId, uint256 _timeHeldLimit, address _startingPosition) internal { // if starting position is not set, start at the top if (_startingPosition == address(0)) { _startingPosition = ownerOf(_tokenId); // _newPrice could be the highest, but not X% above owner, hence _newPrice must be reduced or require statement below would fail if (orderbook[_tokenId][_startingPosition].price <_newPrice) { _newPrice = orderbook[_tokenId][_startingPosition].price; } } // check the starting location is not too low down the list require(orderbook[_tokenId][_startingPosition].price >= _newPrice, "Location too low"); address _tempNext = _startingPosition; address _tempPrev; uint256 _loopCount; uint256 _requiredPrice; // loop through orderbook until bid is at least _requiredPrice above that user do { _tempPrev = _tempNext; _tempNext = orderbook[_tokenId][_tempPrev].next; _requiredPrice = (uint256(orderbook[_tokenId][_tempNext].price).mul(minimumPriceIncrease.add(100))).div(100); _loopCount = _loopCount.add(1); } while ( // break loop if match price above AND above price below (so if either is false, continue, hence OR ) (_newPrice != orderbook[_tokenId][_tempPrev].price || _newPrice <= orderbook[_tokenId][_tempNext].price ) && // break loop if price x% above below _newPrice < _requiredPrice && // break loop if hits max iterations _loopCount < MAX_ITERATIONS ); require(_loopCount < MAX_ITERATIONS, "Location too high"); // reduce user's price to the user above them in the list if necessary, so prices are in order if (orderbook[_tokenId][_tempPrev].price < _newPrice) { _newPrice = orderbook[_tokenId][_tempPrev].price; } // add to the list orderbook[_tokenId][msgSender()] = Bid(SafeCast.toUint128(_newPrice), SafeCast.toUint128(_timeHeldLimit), _tempNext, _tempPrev); orderbook[_tokenId][_tempPrev].next = msgSender(); orderbook[_tokenId][_tempNext].prev = msgSender(); emit LogAddToOrderbook(msgSender(), _newPrice, _timeHeldLimit, orderbook[_tokenId][msgSender()].prev, _tokenId); } /// @notice if a users deposit runs out, either return to previous owner or foreclose /// @dev can be called by anyone via collectRent, therefore should never use msg.sender function _revertToUnderbidder(uint256 _tokenId) internal { address _tempNext = ownerOf(_tokenId); address _tempPrev; uint256 _tempNextDeposit; uint256 _requiredDeposit; uint256 _loopCount; // loop through orderbook list for user with sufficient deposit, deleting users who fail the test do { // get the address of next person in the list _tempPrev = _tempNext; _tempNext = orderbook[_tokenId][_tempPrev].next; // remove the previous user orderbook[_tokenId][_tempNext].prev = address(this); delete orderbook[_tokenId][_tempPrev]; emit LogRemoveFromOrderbook(_tempPrev, _tokenId); // get required and actual deposit of next user _tempNextDeposit = treasury.deposits(_tempNext); uint256 _nextUserTotalRentals = treasury.userTotalRentals(msgSender()).add(orderbook[_tokenId][_tempNext].price); _requiredDeposit = _nextUserTotalRentals.div(minRentalDivisor); _loopCount = _loopCount.add(1); } while ( _tempNext != address(this) && _tempNextDeposit < _requiredDeposit && _loopCount < MAX_ITERATIONS ); // transfer to previous owner exitedTimestamp[ownerOf(_tokenId)] = now; _processNewOwner(_tempNext, orderbook[_tokenId][_tempNext].price, _tokenId); } /// @dev we don't emit LogAddToOrderbook because this is not correct if called via _revertToUnderbidder function _processNewOwner(address _newOwner, uint256 _newPrice, uint256 _tokenId) internal { // _transferCard & updating price MUST come after treasury calls // ... because they assume price and owner not yet updated assert(treasury.updateTotalRental(_newOwner, _newPrice, true)); assert(treasury.updateTotalRental(ownerOf(_tokenId), price[_tokenId], false)); _transferCard(ownerOf(_tokenId), _newOwner, _tokenId); price[_tokenId] = _newPrice; } /// @dev same as above except does not transfer the Card or update last rental time function _processUpdateOwner(uint256 _newPrice, uint256 _tokenId) internal { assert(treasury.updateTotalRental(ownerOf(_tokenId), _newPrice, true)); assert(treasury.updateTotalRental(ownerOf(_tokenId), price[_tokenId], false)); price[_tokenId] = _newPrice; } function _checkState(States currentState) internal view { require(state == currentState, "Incorrect state"); } function _checkNotState(States currentState) internal view { require(state != currentState, "Incorrect state"); } /// @dev should only be called thrice function _incrementState() internal { assert(uint256(state) < 4); state = States(uint256(state) + 1); emit LogStateChange(uint256(state)); } //////////////////////////////////// /////////// CIRCUIT BREAKER //////// //////////////////////////////////// /// @dev alternative to determineWinner, in case Oracle never resolves for any reason /// @dev does not set a winner so same as invalid outcome /// @dev market does not need to be locked, just in case lockMarket bugs out function circuitBreaker() external { require(now > (oracleResolutionTime + 12 weeks), "Too early"); _incrementState(); state = States.WITHDRAW; } }
REALITYCARDS SMART CONTRACT AUDIT March 23, 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 Use msgSender instead of msg.sender in Event param....................7 2.3.WARNING...................................................................8 WRN-1 Check that the address is not zero....................................8 WRN-2 Use general safeTransferFrom ...........................................9 2.4.COMMENTS.................................................................10 CMT-1 Missing the check whether _timestamps has an appropriate length.......10 CMT-2 Incorrect function name..............................................11 CMT-3 Difficult calculation of uint max....................................12 CMT-4 Self-explainable naming..............................................13 CMT-5 Not optimal data type................................................15 CMT-6 No magic numbers.....................................................16 CMT-7 The requirement will never work......................................17 CMT-8 Save time cache values...............................................18 CMT-9 Explain tricky places................................................19 CMT-10 One value is always returned........................................20 CMT-11 Do not hardcode addresses in constructor............................21 CMT-12 Use msgSender instead of msg.sender.................................22 CMT-13 Use SafeMath........................................................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 RealityCards. 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 Reality Cards is the world's first NFT-based prediction market, where instead of betting on an outcome, you own it. Concepts such as shares, bids, asks do not exist- even 'odds' are abstracted away, replaced by a 'daily rental price'. 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 scope implements custom predictions market with a feature of renting tokens to claim reward instead of having them. The project have several logical modules: proxies to xDai and ETH mainnet, NFT hubs to manage NFT, RCMarket to mange prediction market, RCFactory to create new RCMarkets, RCTreasury to store deposits and manage rewards. Usage of xDai makes gas very cheap. Such project could be used to create robust predictions markets. 1.5PROJECT DASHBOARD Client RealityCards Audit name RealityCards Initial version 8c0b05b25a7deef25f98532ae2f8afd4f9a84360 Final version a860b714944341eeda9b26a9e3d1f8f0747b6cbd SLOC 1457 Date 2021-02-01 - 2021-03-23 Auditors engaged 2 auditors 4FILES LISTING RCFactory.sol RCFactory.sol RCMarket.sol RCMarket.sol RCTreasury.sol RCTreasury.sol RCNftHubXdai.sol RCNftHubXdai.sol RCNftHubMainnet.sol RCNftHubMainnet.sol RCProxyMainnet.sol RCProxyMainnet.sol RCProxyXdai.sol RCProxyXdai.sol IAlternateReceiverBridge.sol IAlternateReceiverBri... IRCProxyMainnet.sol IRCProxyMainnet.sol IRCProxyXdai.sol IRCProxyXdai.sol IRCNftHubXdai.sol IRCNftHubXdai.sol IRealitio.sol IRealitio.sol IERC20Dai.sol IERC20Dai.sol IERC721.sol IERC721.sol IRCMarket.sol IRCMarket.sol IFactory.sol IFactory.sol ITreasury.sol ITreasury.sol IBridgeContract.sol IBridgeContract.sol RCTreasury.sol RCTreasury.sol EIP712Base.sol EIP712Base.sol NativeMetaTransaction.sol NativeMetaTransaction.sol CloneFactory.sol CloneFactory.sol 5FINDINGS SUMMARY Level Amount Critical 0 Major 1 Warning 2 Comment 13 CONCLUSION Smart contracts have been audited and several suspicious places have been spotted. During the audit no critical issues were spotted. One issue was marked major as it might cause the undesirable behavior. Several warnings and comments were found and discussed with the client. After working on the reported findings some of them were fixed or acknowledged (if the problem was not critical). So, the contracts are assumed as secure to use according to our security criteria.Final commit identifier with all fixes: a860b714944341eeda9b26a9e3d1f8f0747b6cbd 62.FINDINGS REPORT 2.1CRITICAL Not Found 2.2MAJOR MJR-1 Use msgSender instead of msg.sender in Event param File RCMarket.sol NativeMetaTransaction.sol SeverityMajor Status Acknowledged DESCRIPTION Since the contract uses metatransactions everywhere (and uses NativeMetaTransaction), you should always use msgSender() RCMarket.sol#L584 otherwise the event parameter maybe not correct look at the logic at NativeMetaTransaction.sol#L105 But at RCMarket.sol#L579 the msgSender() , so it is used what is not consistent. RECOMMENDATION It is recommended to use msgSender() in all of msg.sender usages (see also: https://medium.com/biconomy/biconomy-supports-native-meta-transactions- 243ce52a2a2b). CLIENT'S COMMENTARY The instances of msg.sender left are in functions that are only for the market contract (doesn't use meta-Tx), or the sponsor function where the sponsor is expected to have funds and not use meta-Tx. But we've decided that yes we will do a blanket change to msgSender() everywhere, so this will be fixed. 72.3WARNING WRN-1 Check that the address is not zero File RCTreasury.sol RCProxyMainnet.sol RCProxyMainnet.sol RCProxyXdai.sol RCNftHubMainnet.sol SeverityWarning Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION The following lines use address variables. But if the value turns out to be zero, funds will be lost: RCTreasury.sol#L163 RCProxyMainnet.sol#L70 RCProxyMainnet.sol#L75 RCProxyMainnet.sol#L80 RCProxyMainnet.sol#L85 RCProxyMainnet.sol#L90 RCProxyMainnet.sol#L100 RCProxyMainnet.sol#L104 RCProxyXdai.sol#L95 RCProxyXdai.sol#L100 RCProxyXdai.sol#L105 RCProxyXdai.sol#L110 RCProxyXdai.sol#L120 RCProxyXdai.sol#L142-L149 RCProxyXdai.sol#L182 RCNftHubMainnet.sol#L29 RECOMMENDATION It is recommended to add a check that address is valid. 8WRN-2 Use general safeTransferFrom File RCNftHubXdai.sol SeverityWarning Status No issue DESCRIPTION It is required to check success of transfer. So it is should be handled as in ERC20: RCNftHubXdai.sol#L69 RECOMMENDATION It is recommended to use the safeTransferFrom() method from the ERC20 safe library. CLIENT'S COMMENTARY The intention is for the market to move the NFTs as and when the highest bidder changes, this means forcefully moving the NFTs without prior approval of the owner, which is why we are calling the internal function _transfer() and bypassing the usual ownership checks in transferFrom(), because of this it doesn't matter if the owner is a contract not implementing ERC721. If a non-implementer owns it during the event the market will forcefully move the NFT anyway, if they end up being the owner after the event has completed then it's assumed that was the intention of the winning bidder (the non-ERC721 contract creator) and the NFT is now locked. This will not be amended. 92.4COMMENTS CMT-1 Missing the check whether _timestamps has an appropriate length File RCFactory.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION At the lines RCFactory.sol#L312-L313 RCFactory.sol#L317 RCFactory.sol#L320 RCFactory.sol#L352 have operations with elements of the _timestamps array. It is possible that the number of transferred elements of the _timestamps array will be less than 3. In this case, a reference will be made to a nonexistent array element. For clean code, it is better to avoid this situation and check the length of the array. RECOMMENDATION It is recommended to check the number of array elements: require(_timestamps.length < 3, "Incorrect number of array elements"); 1 0CMT-2 Incorrect function name File RCFactory.sol RCFactory.sol RCTreasury.sol RCProxyMainnet.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION In some function setSomeValue() the value of boolean variable someValue is reversed. But by setting it means setting any value and the value may not even change. It would be more correct to call not "Set", but "Change". This can be seen on the following lines: RCFactory.sol#L187 RCFactory.sol#L197 RCFactory.sol#L216 RCFactory.sol#L226 RCFactory.sol#L232 RCFactory.sol#L237 RCFactory.sol#L242 RCTreasury.sol#L125 RCTreasury.sol#L130 RCProxyMainnet.sol#L137 RECOMMENDATION It is recommended to rename a setSomeValue() function to changeSomeValue() . CLIENT'S COMMENTARY setMarketCreationGovernorsOnly to changeMarketCreationGovernorsOnly setTrapCardsIfUnapproved to changeTrapCardsIfUnapproved addOrRemoveGovernor to changeGovernorApproval approveOrUnapproveMarket to changeMarketApproval addOrRemoveArtist to changeArtistApproval addOrRemoveAffiliate to changeAffiliateApproval addOrRemoveCardAffiliate to changeCardAffiliateApproval setGlobalPause to changeGlobalPause setPauseMarket to changePauseMarket enableOrDisableDeposits to changeDepositsEnabled 1 1CMT-3 Difficult calculation of uint max File RCMarket.sol RCProxyMainnet.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION See these lines: RCMarket.sol#L29 RCMarket.sol#L30 RCProxyMainnet.sol#L91 Both of this values are worked out by strange way. E.g. 2**256 for uint256 will get 0. But there are simpler ways to calculate the maximum value. For example: uint256 public constant MAX_UINT256 = uint256(-1); uint256 public constant MAX_UINT256 = type(uint256).max; RECOMMENDATION It is recommended to make it clearer. CLIENT'S COMMENTARY The recommended solution was not available in the project solidity version, after update the recommendations were applied. 1 2CMT-4 Self-explainable naming File RCFactory.sol RCMarket.sol RCTreasury.sol RCProxyXdai.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION It's good if the name of the variable is absolutely self-explainable. For primitive types (integers) it's good to know what exactly the variable is. For mappings it's better to add key to the name (e.g. userDeposits not just deposits) key and value of struct is unclear RCFactory.sol#L38 - mappingOfMarkets RCMarket.sol#L49 - price add Percent postfix RCFactory.sol#L46 - minimumPriceIncrease RCMarket.sol#L62 - minimumPriceIncrease add DayDivisor postfix RCMarket.sol#L64 - minRentalDivisor add weekDivisor postfix RCMarket.sol#L66 - hotPotatoDivisor rentCollected postfix RCMarket.sol#L51 RCMarket.sol#L53 RCMarket.sol#L55 deposit - RCTreasury.sol#L23 what is the key? RCProxyXdai.sol#L37 what is the key? RCProxyXdai.sol#L38 what is the key? RCProxyXdai.sol#L39 - must be upper-cased RCProxyXdai.sol#L47 - what is the key? 1 3RCProxyXdai.sol#L48 - what is the key? RCProxyXdai.sol#L118 - change amicable to some common word RCProxyXdai.sol#L50 - the purpose of the value is not clear from the name RECOMMENDATION It is recommended to rename variables. CLIENT'S COMMENTARY mappingOfMarkets not changed, variable unused for now, a better name will be chosen if it's used otherwise it will be removed. price to tokenPrice minimumPriceIncrease to minimumPriceIncreasePercent minRentalDivisor to minRentalDayDivisor hotPotatoDivisor to hotPotatioWeekDivisor collectedPerUser to rentCollectedPerUser collectedPerToken to rentCollectedPerToken totalCollected to totalRentCollected deposit to userDeposit isMarket not changed, where used it offers a simple readable name, also used in external bot upgradedNfts to upgradedNftId nft to NFT deposits not changed, used in external bot hasConfirmedDeposit not changed, used in external bot setAmicableResolution not changed floatSize, not changed, it is the size of the float. 1 4CMT-5 Not optimal data type File RCFactory.sol RCMarket.sol RCNftHubXdai.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION At the line RCFactory.sol#L42 uses an array. But with the use of structure, the code will become clearer. The following lines use variables and numbers: RCMarket.sol#L34 RCNftHubXdai.sol#L80 RCNftHubXdai.sol#L87 This makes the code hard to read. RECOMMENDATION It is recommended to make a structure. It is recommended to create constants or enum: MODE_CLASSIC MODE_WINNER_TAKES_ALL MODE_HOT_POTATO CLIENT'S COMMENTARY Not changed, using an array offers easier integration with certain external services that already have an array as a data type. 6. Named constants or enum Mode changed to enum Market state checks have been updated. 1 5CMT-6 No magic numbers File RCMarket.sol RCProxyMainnet.sol RCProxyXdai.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION RCMarket.sol#L487 (fixed) RCMarket.sol#L675 RCMarket.sol#L687 RCMarket.sol#L721 (fixed) RCProxyMainnet.sol#L117 (what is 2 and 0 ) RCProxyMainnet.sol#L149 (what is 2 and 0 ) RCProxyMainnet.sol#L169 (what is 400000 ) (fixed) RCProxyXdai.sol#L173 (what is 200000 ) (fixed) RCProxyXdai.sol#L206 (what is 200000 ) (fixed) RECOMMENDATION It is recommended to create named constants with required explanation about choicing the value CLIENT'S COMMENTARY Changed to MIN_RENTAL_VALUE 100 is not considered a magic number here because alternatives such as "HUNDRED", "PERCENT" or "CENTUM" wouldn't clarify the basic arithmetic formula being performed. As above Issue derived from 6.a. Updated to REALITIO_TEMPLATE_ID and REALITIO_NONCE As above Updated to XDAI_BRIDGE_GAS_COST Updated to MAINNET_BRIDGE_GAS_COST As above 1 6CMT-7 The requirement will never work File RCMarket.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION At the line RCMarket.sol#L684 has the value for the requirement always False. RECOMMENDATION It is recommended to make a variable or condition instead of False. Or remove this requirement. CLIENT'S COMMENTARY Require statement amended and moved to a more appropriate place 1 7CMT-8 Save time cache values File RCMarket.sol RCTreasury.sol SeverityComment Status No issue DESCRIPTION At the lines: RCMarket.sol#L774-L777 RCTreasury.sol#L176-L186 msgSender() is used in a lot of places. It is better to cache it to avoid multi calls. RECOMMENDATION It is recommended to cache the value. CLIENT'S COMMENTARY msgSender() is now cached in several functions, although minimal benefit to be had when compiling with the optimizer. 1 8CMT-9 Explain tricky places File RCTreasury.sol RCProxyXdai.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION Let's take a look at the following lines: RCTreasury.sol#L73 RCProxyXdai.sol#L215 It is not clear why 24*6 = 10 minutes. It is not clear floatSize. RECOMMENDATION It is recommended to add explanations as comments. CLIENT'S COMMENTARY Added explanation about min rental divisor floatSize, not changed, it is the size of the float 1 9CMT-10 One value is always returned File RCTreasury.sol RCProxyXdai.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION Here the function always returns True and never returns False: RCTreasury.sol#L100 RCProxyXdai.sol#L85 RECOMMENDATION It is recommended to remove the return statement. CLIENT'S COMMENTARY Removed the return value 2 0CMT-11 Do not hardcode addresses in constructor File RCProxyMainnet.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION The address could be changed if deployed to testnet for example RCProxyMainnet.sol#L52 RECOMMENDATION It is recommended to set the address as an argument. CLIENT'S COMMENTARY Address is now passed into the constructor 2 1CMT-12 Use msgSender instead of msg.sender File RCMarket.sol RCTreasury.sol NativeMetaTransaction.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION Since the contract uses metatransactions everywhere (and uses NativeMetaTransaction), you should always use msgSender RCMarket.sol#L332 RCTreasury.sol#L200 RCTreasury.sol#L211 look at the logic at NativeMetaTransaction.sol#L105 In above examples the code is correct but not robust, the method cannot be called via metaTransaction by the market contract. If the part of logic will be inaccurate copy-pasted to some other place it's easy to make a mistake forgetting about switching to msgSender() . RECOMMENDATION It is recommended to use msgSender() in all of msg.sender usages (see also: https://medium.com/biconomy/biconomy-supports-native-meta-transactions- 243ce52a2a2b). CLIENT'S COMMENTARY Changed all occurrences of msg.sender to msgSender. 2 2CMT-13 Use SafeMath File RCTreasury.sol SeverityComment Status Fixed at https://github.com/RealityCards/RealityCards- Contracts/blob/a860b714944341eeda9b26a9e3d1f8f0747b6cbd DESCRIPTION The uint256 overflow is possible at RCTreasury.sol#L84 RECOMMENDATION It is recommended to use SafeMath. 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
1. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 1 - Critical: 1 2. Major 2.a Problem (one line with code reference) MJR-1 Use msgSender instead of msg.sender in Event param (Line 7) 2.b Fix (one line with code reference) Replace msg.sender with msgSender (Line 7) 3. Critical 3.a Problem (one line with code reference) CRT-1 Unchecked call to external contract (Line 7) 3.b Fix (one line with code reference) Add a check to ensure that the external contract is not a zero address (Line 7) 6. Observations - No Minor or Moderate issues were found - Major issue found related to use of msgSender instead of msg.sender in Event param - Critical issue found related to unchecked call to external contract 7. Conclusion The audit of the RealityCards Smart Contract revealed one Major issue and one Critical issue. Both issues were related to the use of msgSender instead of msg.sender in Event 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. Conclusion: The audit found two minor issues which were addressed by building an independent view of the project's architecture and finding logical flaws. The company's checklist was also used to eliminate typical vulnerabilities. Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Findings Severity Breakdown - Critical: Bugs leading to assets theft, fund access locking, or any other loss funds to be transferred to any party. Immediate 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. - Warning: Bugs that can break the intended contract logic or expose it to DoS attacks. Take into consideration and implement fix in certain period. - Comment: Other issues and recommendations reported to/acknowledged by the team. Take into consideration. Status Description - Fixed: Recommended fixes have been made to the project code and no longer affect its security. - Acknowledged: The project team is aware of this finding. Recommendations for this finding are planned to be resolved in the future.
// SPDX-License-Identifier: MIT // SWC-Floating Pragma: L3 pragma solidity ^0.8.0; interface IERC20 { /** * @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); /** * @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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount ) external returns (bool); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @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: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, 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}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, 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}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, 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) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, 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) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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 Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - 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 {} } // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @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 { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } } abstract 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual onlyOwner { _transferOwnership(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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } contract Cronospad is ERC20, ERC20Burnable, Ownable { constructor() ERC20("Cronospad", "CPAD") { _mint(msg.sender, 1000000000000000000000000000); } }
Audit R eport May, 2022 For QuillA ud i t saudits.quillhash.com CronosPad - Audit ReportHigh Severity Issues Medium Severity Issues Low Severity Issues Informational Issues A.1 Unlocked Pragma A.2 BEP20 Standard violation A.3 Public functions that could be declared external inorder to save gasExecutive Summary Checked Vulnerabilities Techniques and Methods Manual Anaysis ......................................................................................... ........................................................................................... .................................................................................... .......................................................................................... ................................................................................... ............................................................................................ ............................................................................................... ............................................................................................Functional Testing Automated Testing Closing Summary About QuillAuditsTable of Content 01 03 04 05 05 05 05 05 05 06 07 08 08 09 10audits.quillhash.com High Open Issues Resolved IssuesAcknowledged Issues Partially Resolved IssuesLow 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 Medium Informational3 Issues FoundHigh Medium Low InformationalExecutive Summary CronosPad Cronospad is the first major micro and small cap decentralized launchpad on Cronos. May 10th, 2022 to May 16th, 2022 Manual Review, Functional Testing, Automated Testing etc. The scope of this audit was to analyse CronosPad codebase for quality, security, and correctness. https://github.com/cronospad/cronospad 1605d38fab314cab399093f756b41093fdbc859f https://github.com/cronospad/cronospad 4f44581df5aa090764ec905121ee45889e796bdbProject Name Overview Timeline Method Scope of Audit Sourcecode Commit Fixed in Commit 01 CronosPad - Audit Reportaudits.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 CronosPad - 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 CronosPad - 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 CronosPad - Audit Reportaudits.quillhash.com Manual Analysis High Severity Issues No issues were found Medium Severity Issues 05 No issues were found Low Severity Issues No issues were found A.1 Unlocked pragma (pragma solidity ^0.8.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.eg 0.8.4 FixedInformational Issues CronosPad - Audit Reportaudits.quillhash.com 062. BEP20 Standard violation Description 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. Recommendation 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. Reference: https://github.com/bnb-chain/BEPs/blob/master/BEP20.md#5117-transfer Status Fixed CronosPad - Audit Reportaudits.quillhash.com 073. Public functions that could be declared external inorder to save gas Status 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() Fixed CronosPad - 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 be able to burn token Should be able to burnFrom Should be able to transferOwnership Should revert if transfer amount exceeds balanceSome 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. CronosPad - Audit Reportaudits.quillhash.com 09 QuillAudits smart contract audit is not a security warranty, investment advice, or an endorsement of the CronosPad 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 CronosPad 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 CronosPad. We performed our audit according to the procedure described above. No Major Issues in Code, Just Some informational severity were found, Some suggestions and best practices are also provided in order to improve the code quality and security posture. In CronosPad - Audit ReportEnd, CronosPad Team Resolved all Issues.500+ 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 CronosPad - 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: 0 - Major: 3 - Critical: 0 Minor Issues: None Moderate Issues: None Major Issues: 3.a Unlocked Pragma (A.1) 3.b BEP20 Standard violation (A.2) 3.c Public functions that could be declared external inorder to save gas (A.3) Critical Issues: None Observations: - Manual Review, Functional Testing, Automated Testing were conducted - No critical issues were found Conclusion: The audit of the CronosPad codebase was successful and no critical issues were found. Minor and moderate issues were not found. Major issues were found and were addressed. Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 5 - Major: 4 - Critical: 2 Minor Issues - Problem: Use of tx.origin (Code Reference: Line No. 28) - Fix: Replace tx.origin with msg.sender (Code Reference: Line No. 28) Moderate Issues - Problem: Unchecked external call (Code Reference: Line No. 32) - Fix: Check the return value of external calls (Code Reference: Line No. 32) Major Issues - Problem: Malicious libraries (Code Reference: Line No. 36) - Fix: Use verified libraries (Code Reference: Line No. 36) Critical Issues - Problem: DoS with Block Gas Limit (Code Reference: Line No. 24) - Fix: Use a gas limit that is appropriate for the transaction (Code Reference: Line No. 24) Observations - Structural Analysis, Static Analysis, Code Review/Manual Analysis and Gas Consumption were used to review the smart contracts. - Checks were done to ensure the smart contract is structured in a way that will not result in future problems. Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: A.1 Unlocked pragma (pragma solidity ^0.8.0) Problem: Contracts should be deployed with the same compiler version and flags that they have been tested with thoroughly. Fix: Lock the pragma and refactor the code base to only use stable features (e.g. 0.8.4). Moderate: None Major: None Critical: None Observations: Public functions should be declared external in order to save gas. Conclusion: No issues of high, medium or low severity were found. It is recommended to lock the pragma and refactor the code base to only use stable features. Public functions should be declared external in order to save gas.
//SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./SingleBond.sol"; contract SingleBondsFactory is Ownable { using SafeERC20 for IERC20; event NewBonds(address indexed bond, address _rewardtoken, uint256 _start, uint256 _duration, uint256 _phasenum,uint256 _principal,uint256 _interestone,address _debtor); address public epochImp; constructor(address _epochImp) { epochImp = _epochImp; } function newBonds(address _rewardtoken, uint256 _start, uint256 _duration, uint256 _phasenum,uint256 _principal,uint256 _interestone,address _debtor) external onlyOwner { IERC20 token = IERC20(_rewardtoken); uint totalAmount = _phasenum * _interestone + _principal; require(token.balanceOf(msg.sender)>= totalAmount, "factory:no balance"); token.safeTransferFrom(msg.sender, address(this), totalAmount); SingleBond singlebond = new SingleBond(_rewardtoken); token.approve(address(singlebond), totalAmount); singlebond.setEpochImp(epochImp); singlebond.initBond(_start, _duration, _phasenum, _principal, _interestone, _debtor); emit NewBonds(address(singlebond), _rewardtoken, _start, _duration, _phasenum, _principal, _interestone, _debtor); } // function renewal (SingleBond bondAddr, uint256 _phasenum,uint256 _principal,uint256 _interestone) external onlyOwner { IERC20 token = IERC20(bondAddr.rewardtoken()); uint totalAmount = _phasenum * _interestone + _principal; require(token.balanceOf(msg.sender)>= totalAmount, "factory:no balance"); token.safeTransferFrom(msg.sender, address(this), totalAmount); token.approve(address(bondAddr), totalAmount); bondAddr.renewal(_phasenum, _principal, _interestone); } function renewSingleEpoch(SingleBond bondAddr, uint256 id, uint256 amount, address to) external onlyOwner{ IERC20 token = IERC20(bondAddr.rewardtoken()); token.safeTransferFrom(msg.sender, address(this), amount); token.approve(address(bondAddr), amount); bondAddr.renewSingleEpoch(id,amount,to); } } //SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./interfaces/IVaultFarm.sol"; import "./interfaces/ISingleBond.sol"; import "./interfaces/IEpoch.sol"; import "./interfaces/IVault.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./Pool.sol"; import "./CloneFactory.sol"; contract VaultFarm is IVaultFarm, CloneFactory, OwnableUpgradeable { address public bond; address public poolImp; address[] public pools; // pool => point mapping(address => uint) public allocPoint; // asset => pool mapping(address => address) public assetPool; mapping(address => bool) public vaults; uint256 public totalAllocPoint; uint256 public lastUpdateSecond; uint256 public periodFinish; address[] public epoches; uint[] public epochRewards; event NewPool(address asset, address pool); event VaultApproved(address vault, bool approved); constructor() { } function initialize(address _bond, address _poolImp) external initializer { OwnableUpgradeable.__Ownable_init(); bond = _bond; poolImp = _poolImp; } function setPoolImp(address _poolImp) external onlyOwner { poolImp = _poolImp; } function approveVault(address vault, bool approved) external onlyOwner { vaults[vault] = approved; emit VaultApproved(vault, approved); } function assetPoolAlloc(address asset) external view returns (address pool, uint alloc){ pool = assetPool[asset]; alloc = allocPoint[pool]; } function getPools() external view returns(address [] memory ps) { ps = pools; } function epochesRewards() external view returns(address[] memory epochs, uint[] memory rewards) { epochs = epoches; rewards = epochRewards; } function syncVault(address vault) external { require(vaults[vault], "invalid vault"); address asset = IVault(vault).underlying(); uint amount = IVault(vault).deposits(msg.sender); address pooladdr = assetPool[asset]; require(pooladdr != address(0), "no asset pool"); uint currAmount = Pool(pooladdr).deposits(msg.sender); require(amount != currAmount, "aleady migrated"); if (amount > currAmount) { Pool(pooladdr).deposit(msg.sender, amount - currAmount); } else { Pool(pooladdr).withdraw(msg.sender, currAmount - amount); } } function syncDeposit(address _user, uint256 _amount, address asset) external override { require(vaults[msg.sender], "invalid vault"); address pooladdr = assetPool[asset]; if (pooladdr != address(0)) { Pool(pooladdr).deposit(_user, _amount); } } function syncWithdraw(address _user, uint256 _amount, address asset) external override { require(vaults[msg.sender], "invalid vault"); address pooladdr = assetPool[asset]; if (pooladdr != address(0)) { Pool(pooladdr).withdraw(_user, _amount); } } function syncLiquidate(address _user, address asset) external override { require(vaults[msg.sender], "invalid vault"); address pooladdr = assetPool[asset]; if (pooladdr != address(0)) { Pool(pooladdr).liquidate(_user); } } //SWC-Function Default Visibility: L111-L126 function massUpdatePools(address[] memory epochs, uint256[] memory rewards) public { uint256 poolLen = pools.length; uint256 epochLen = epochs.length; uint[] memory epochArr = new uint[](epochLen); for (uint256 pi = 0; pi < poolLen; pi++) { for (uint256 ei = 0; ei < epochLen; ei++) { epochArr[ei] = rewards[ei] * allocPoint[pools[pi]] / totalAllocPoint; } Pool(pools[pi]).updateReward(epochs, epochArr, periodFinish); } epochRewards = rewards; lastUpdateSecond = block.timestamp; } // epochs need small for gas issue. function newReward(address[] memory epochs, uint256[] memory rewards, uint duration) public onlyOwner { require(block.timestamp >= periodFinish, 'period not finish'); require(duration > 0, 'duration zero'); periodFinish = block.timestamp + duration; epoches = epochs; massUpdatePools(epochs, rewards); for (uint i = 0 ; i < epochs.length; i++) { require(IEpoch(epochs[i]).bond() == bond, "invalid epoch"); IERC20(epochs[i]).transferFrom(msg.sender, address(this), rewards[i]); } } function appendReward(address epoch, uint256 reward) public onlyOwner { require(block.timestamp < periodFinish, 'period not finish'); require(IEpoch(epoch).bond() == bond, "invalid epoch"); bool inEpoch; uint i; for (; i < epoches.length; i++) { if (epoch == epoches[i]) { inEpoch = true; break; } } uint[] memory leftRewards = calLeftAwards(); if (!inEpoch) { epoches.push(epoch); uint[] memory newleftRewards = new uint[](epoches.length); for (uint j = 0; j < leftRewards.length; j++) { newleftRewards[j] = leftRewards[j]; } newleftRewards[leftRewards.length] = reward; massUpdatePools(epoches, newleftRewards); } else { leftRewards[i] += reward; massUpdatePools(epoches, leftRewards); } IERC20(epoch).transferFrom(msg.sender, address(this), reward); } function removePoolEpoch(address pool, address epoch) external onlyOwner { Pool(pool).remove(epoch); } function calLeftAwards() internal view returns(uint[] memory leftRewards) { uint len = epochRewards.length; leftRewards = new uint[](len); if (periodFinish > lastUpdateSecond && block.timestamp < periodFinish) { uint duration = periodFinish - lastUpdateSecond; uint passed = block.timestamp - lastUpdateSecond; for (uint i = 0 ; i < len; i++) { leftRewards[i] = epochRewards[i] - (passed * epochRewards[i] / duration); } } } function newPool(uint256 _allocPoint, address asset) public onlyOwner { require(assetPool[asset] == address(0), "pool exist!"); address pool = createClone(poolImp); Pool(pool).init(); pools.push(pool); allocPoint[pool] = _allocPoint; assetPool[asset] = pool; totalAllocPoint = totalAllocPoint + _allocPoint; emit NewPool(asset, pool); uint[] memory leftRewards = calLeftAwards(); massUpdatePools(epoches,leftRewards); } function updatePool(uint256 _allocPoint, address asset) public onlyOwner { address pool = assetPool[asset]; require(pool != address(0), "pool not exist!"); totalAllocPoint = totalAllocPoint - allocPoint[pool] + _allocPoint; allocPoint[pool] = _allocPoint; uint[] memory leftRewards = calLeftAwards(); massUpdatePools(epoches,leftRewards); } // _pools need small for gas issue. function withdrawAward(address[] memory _pools, address to, bool redeem) external { address user = msg.sender; uint len = _pools.length; address[] memory epochs; uint256[] memory rewards; for (uint i = 0 ; i < len; i++) { (epochs, rewards)= Pool(_pools[i]).withdrawAward(user); if (redeem) { ISingleBond(bond).redeemOrTransfer(epochs, rewards, to); } else { ISingleBond(bond).multiTransfer(epochs, rewards, to); } } } function redeemAward(address[] memory _pools, address to) external { address user = msg.sender; uint len = _pools.length; address[] memory epochs; uint256[] memory rewards; for (uint i = 0 ; i < len; i++) { (epochs, rewards)= Pool(_pools[i]).withdrawAward(user); ISingleBond(bond).redeem(epochs, rewards, to); } } function emergencyWithdraw(address[] memory epochs, uint256[] memory amounts) external onlyOwner { require(epochs.length == amounts.length, "mismatch length"); for (uint i = 0 ; i < epochs.length; i++) { IERC20(epochs[i]).transfer(msg.sender, amounts[i]); } } }pragma solidity 0.8.11; import "./interfaces/ISingleBond.sol"; import "./interfaces/IEpoch.sol"; import "./interfaces/IVaultFarm.sol"; contract Pool { uint256 public constant SCALE = 1e12; address public farming; address[] public epoches; mapping(address => bool) public validEpoches; mapping(address => uint) public deposits; // user => epoch => debt mapping(address => mapping(address => uint)) public rewardDebt; mapping(address => mapping(address => uint)) public rewardAvailable; struct EpochInfo { uint accPerShare; //Accumulated rewards per share, times SCALE uint epochPerSecond; // for total deposit } mapping(address => EpochInfo) public epochInfos; uint256 public totalAmount; uint256 public lastRewardSecond; uint256 public periodEnd; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); constructor() { } modifier onlyFarming() { require(farming == msg.sender, "must call from framing"); _; } function getEpoches() external view returns(address[] memory){ return epoches; } function addEpoch(address epoch) internal { if(!validEpoches[epoch]) { validEpoches[epoch] = true; epoches.push(epoch); } } // remove some item for saving gas (array issue). // should only used when no such epoch assets. function remove(address epoch) external onlyFarming { require(validEpoches[epoch], "Not a valid epoch"); validEpoches[epoch] = false; uint len = epoches.length; for (uint i = 0; i < len; i++) { if( epoch == epoches[i]) { if (i == len - 1) { epoches.pop(); break; } else { epoches[i] = epoches[len - 1]; epoches.pop(); break; } } } } function init() external { require(address(farming) == address(0), "inited"); farming = msg.sender; } function updateReward(address[] memory epochs, uint[] memory awards, uint periodFinish) public onlyFarming { if(periodFinish <= block.timestamp) { return ; } require(epochs.length == awards.length, "mismatch length"); updatePool(); periodEnd = periodFinish; uint duration = periodFinish - block.timestamp; for(uint256 i = 0; i< epochs.length; i++) { addEpoch(epochs[i]); EpochInfo storage epinfo = epochInfos[epochs[i]]; epinfo.epochPerSecond = awards[i] / duration; } } function getPassed() internal view returns (uint) { uint endTs; if (periodEnd > block.timestamp) { endTs = block.timestamp; } else { endTs = periodEnd; } if (endTs <= lastRewardSecond) { return 0; } return endTs - lastRewardSecond; } function updatePool() internal { uint passed = getPassed(); if (totalAmount > 0 && passed > 0) { for(uint256 i = 0; i< epoches.length; i++) { EpochInfo storage epinfo = epochInfos[epoches[i]]; epinfo.accPerShare += epinfo.epochPerSecond * passed * SCALE / totalAmount; } } lastRewardSecond = block.timestamp; } function updateUser(address user, uint newDeposit, bool liq) internal { for(uint256 i = 0; i< epoches.length; i++) { EpochInfo memory epinfo = epochInfos[epoches[i]]; if (liq) { rewardAvailable[user][epoches[i]] = 0; } else { rewardAvailable[user][epoches[i]] += (deposits[user] * epinfo.accPerShare / SCALE) - rewardDebt[user][epoches[i]]; } rewardDebt[user][epoches[i]] = newDeposit * epinfo.accPerShare / SCALE; } } function deposit(address user, uint256 amount) external onlyFarming { updatePool(); uint newDeposit = deposits[user] + amount; updateUser(user, newDeposit, false); deposits[user] = newDeposit; totalAmount += amount; emit Deposit(user, amount); } function withdraw(address user, uint256 amount) external onlyFarming { updatePool(); uint newDeposit = deposits[user] - amount; updateUser(user, newDeposit, false); deposits[user] = newDeposit; totalAmount -= amount; emit Withdraw(user, amount); } function liquidate(address user) external onlyFarming { updatePool(); updateUser(user,0, true); uint amount = deposits[user]; totalAmount -= amount; deposits[user] = 0; emit Withdraw(user, amount); } function pending(address user) public view returns (address[] memory epochs, uint256[] memory rewards) { uint passed = getPassed(); uint len = epoches.length; rewards = new uint[](len); for(uint256 i = 0; i< epoches.length; i++) { EpochInfo memory epinfo = epochInfos[epoches[i]]; uint currPending = 0; if (passed > 0) { currPending = epinfo.epochPerSecond * passed * deposits[user] / totalAmount; } rewards[i] = rewardAvailable[user][epoches[i]] + currPending + (deposits[user] * epinfo.accPerShare / SCALE) - rewardDebt[user][epoches[i]]; } epochs = epoches; } function withdrawAward(address user) external returns (address[] memory epochs, uint256[] memory rewards) { require(farming == msg.sender, "must call from framing"); updatePool(); updateUser(user, deposits[user], false); (epochs, rewards) = pending(user); for(uint256 i = 0; i< epoches.length; i++) { rewardAvailable[user][epoches[i]] = 0; } } }//SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./ERC20Clonable.sol"; contract Epoch is ERC20Clonable { using SafeERC20 for IERC20; address public underlying; address public bond; uint256 public end; constructor() { } function initialize(address _underlying, uint256 _end, address _debtor, uint256 _initAmount, string memory _name, string memory _symbol) external { require(address(bond) == address(0), "inited"); bond = msg.sender; underlying = _underlying; end = _end; super.initialize(_name, _symbol, 18); _mint(_debtor, _initAmount); } function mint(address to, uint256 _amount) external { require(msg.sender == bond, "only call by bond"); _mint(to, _amount); } function multiTransfer(address user, address to, uint256 amount) external returns (bool) { require(msg.sender == bond, "only call by bond"); return _transfer(user, to, amount); } function redeem(address user, address to, uint256 amount) external { require(msg.sender == bond, "only call by bond"); doRedeem(user, to, amount); } function burn(address to, uint256 amount) external { doRedeem(msg.sender, to, amount); } function doRedeem(address user, address to, uint256 amount) internal { IERC20 token = IERC20(underlying); require(block.timestamp > end, "Epoch: not end"); require(token.balanceOf(address(this))>= amount, "Epoch: need more underlying token"); _burn(user, amount); token.safeTransfer(to, amount); } } pragma solidity >=0.8.0; contract ERC20Clonable { uint256 internal _totalSupply; mapping (address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; string public symbol; uint8 public decimals; string public name; // Optional token name constructor() { } event Approval(address indexed owner, address indexed spender, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); function initialize(string memory _name, string memory _symbol, uint8 _decimals) public { require(_totalSupply == 0 && decimals == 0, "erc20 inited"); require(_decimals > 0, "invalid decimals"); name = _name; symbol = _symbol; decimals = _decimals; } function totalSupply() public view virtual returns (uint256) { return _totalSupply; } function balanceOf(address guy) public view virtual returns (uint256) { return _balanceOf[guy]; } function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowance[owner][spender]; } function approve(address spender, uint wad) public virtual returns (bool) { return _approve(msg.sender, spender, wad); } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowance[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowance[msg.sender][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } function transfer(address dst, uint wad) public virtual returns (bool) { return _transfer(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public virtual returns (bool) { uint256 allowed = _allowance[src][msg.sender]; if (src != msg.sender && allowed != type(uint).max) { require(allowed >= wad, "ERC20: Insufficient approval"); _approve(src, msg.sender, allowed - wad); } return _transfer(src, dst, wad); } function _transfer(address src, address dst, uint wad) internal virtual returns (bool) { require(_balanceOf[src] >= wad, "ERC20: Insufficient balance"); _balanceOf[src] = _balanceOf[src] - wad; _balanceOf[dst] = _balanceOf[dst] + wad; emit Transfer(src, dst, wad); return true; } function _approve(address owner, address spender, uint wad) internal virtual returns (bool) { _allowance[owner][spender] = wad; emit Approval(owner, spender, wad); return true; } function _mint(address dst, uint wad) internal virtual { _balanceOf[dst] = _balanceOf[dst] + wad; _totalSupply = _totalSupply + wad; emit Transfer(address(0), dst, wad); } function _burn(address src, uint wad) internal virtual { require(_balanceOf[src] >= wad, "ERC20: Insufficient balance"); _balanceOf[src] = _balanceOf[src] - wad; _totalSupply = _totalSupply - wad; emit Transfer(src, address(0), wad); } function _burnFrom(address src, uint wad) internal virtual { uint256 allowed = _allowance[src][msg.sender]; if (src != msg.sender && allowed != type(uint).max) { require(allowed >= wad, "ERC20: Insufficient approval"); _approve(src, msg.sender, allowed - wad); } _burn(src, wad); } }//SPDX-License-Identifier: MIT pragma solidity 0.8.11; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import './libs/FixedPoint.sol'; import './libs/UniswapV2OracleLibrary.sol'; import "./interfaces/IUSDOracle.sol"; contract DexUSDOracle is IUSDOracle, Initializable, OwnableUpgradeable { using FixedPoint for *; uint public period; IUniswapV2Pair public pair; IUSDOracle public baseOracle; address public token0; address public token1; uint public price0CumulativeLast1Period; uint public price1CumulativeLast1Period; uint32 public blockTimestampLast1Period; FixedPoint.uq112x112 public price0Average1Period; FixedPoint.uq112x112 public price1Average1Period; uint public price0CumulativeLast4Period; uint public price1CumulativeLast4Period; uint32 public blockTimestampLast4Period; FixedPoint.uq112x112 public price0Average4Period; FixedPoint.uq112x112 public price1Average4Period; event PeriodChanged(uint newPeriod); constructor() { } function initialize( address _baseOracle, address _pair) external initializer { OwnableUpgradeable.__Ownable_init(); period = 30 minutes; baseOracle = IUSDOracle(_baseOracle); pair = IUniswapV2Pair(_pair); token0 = pair.token0(); token1 = pair.token1(); price0CumulativeLast1Period = pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLast1Period = pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) price0CumulativeLast4Period = price0CumulativeLast1Period; price1CumulativeLast4Period = price1CumulativeLast1Period; uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast1Period) = pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, 'NO_RESERVES'); // ensure that there's liquidity in the pair blockTimestampLast4Period = blockTimestampLast1Period; uint decimal0 = IERC20Metadata(token0).decimals(); uint decimal1 = IERC20Metadata(token1).decimals(); require(decimal0 == 18 && decimal1 == 18, 'MISMATCH_DEC'); } function setPeriod(uint _period) external onlyOwner { period = _period; emit PeriodChanged(_period); } // for update price. call every PERIOD by robot. function update() external { (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 timeElapsed1Period = blockTimestamp - blockTimestampLast1Period; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed1Period >= period, '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 price0Average1Period = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast1Period) / timeElapsed1Period)); price1Average1Period = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast1Period) / timeElapsed1Period)); price0CumulativeLast1Period = price0Cumulative; price1CumulativeLast1Period = price1Cumulative; blockTimestampLast1Period = blockTimestamp; uint32 timeElapsed4Period = blockTimestamp - blockTimestampLast4Period; if (timeElapsed4Period >= 4 * period) { price0Average4Period = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast4Period) / timeElapsed4Period)); price1Average4Period = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast4Period) / timeElapsed4Period)); price0CumulativeLast4Period = price0Cumulative; price1CumulativeLast4Period = price1Cumulative; blockTimestampLast4Period = blockTimestamp; } } function consult(address token, uint amountIn) external view returns (uint amountOut) { if (token == token0) { if (price0Average4Period._x < price0Average1Period._x) { amountOut = price0Average4Period.mul(amountIn).decode144(); } else { amountOut = price0Average1Period.mul(amountIn).decode144(); } } else { require(token == token1, 'INVALID_TOKEN'); if (price1Average4Period._x < price1Average1Period._x) { amountOut = price1Average4Period.mul(amountIn).decode144(); } else { amountOut = price1Average1Period.mul(amountIn).decode144(); } } } // get lower price (1period vs 4period) function getPrice(address token) external override view returns (uint256 price) { if (token == token0) { uint token1Price = baseOracle.getPrice(token1); if (price0Average4Period._x < price0Average1Period._x) { price = price0Average4Period.mul(token1Price).decode144(); } else { price = price0Average1Period.mul(token1Price).decode144(); } } else { require(token == token1, 'INVALID_TOKEN'); uint token0Price = baseOracle.getPrice(token0); if (price1Average4Period._x < price1Average1Period._x) { price = price1Average4Period.mul(token0Price).decode144(); } else { price = price1Average1Period.mul(token0Price).decode144(); } } require(price != 0, "NO_PRICE"); } } //SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./Epoch.sol"; import "./CloneFactory.sol"; contract SingleBond is Ownable, CloneFactory { using Strings for uint256; address[] private epoches; address public rewardtoken; address public debtor; uint256 public start; uint256 public duration; uint256 public phasenum; uint256 public end; address public epochImp; event NewEpoch(address indexed epoch); function getEpoches() external view returns(address[] memory){ return epoches; } function setEpochImp(address _epochImp) external onlyOwner { epochImp = _epochImp; } function getEpoch(uint256 id) external view returns(address){ return epoches[id]; } constructor(address _rewardtoken) { rewardtoken = _rewardtoken; } function initBond(uint256 _start, uint256 _duration, uint256 _phasenum,uint256 _principal,uint256 _interestone,address _debtor) external onlyOwner { require(start == 0 && end == 0, "aleady inited"); debtor = _debtor; start = _start; duration = _duration; phasenum = _phasenum; for (uint256 i = 0; i < phasenum; i++){ uint256 epend = start + (i+1) * duration; uint256 amount = _interestone; if(i == phasenum - 1) { amount = _principal + _interestone; } string memory name = string(abi.encodePacked(string("Epoch#"), i.toString())); string memory symbol = string(abi.encodePacked(string("EP#"), i.toString())); address ep = createClone(epochImp); Epoch(ep).initialize(rewardtoken, epend, debtor, amount, name, symbol); epoches.push(ep); emit NewEpoch(ep); IERC20(rewardtoken).transferFrom(msg.sender, ep, amount); } end = start + phasenum * duration; } //renewal bond will start at next phase function renewal (uint256 _phasenum,uint256 _principal,uint256 _interestone) external onlyOwner { uint256 needcreate = 0; uint256 newstart = end; uint256 renewphase = (block.timestamp - start)/duration + 1; if(block.timestamp + duration >= end){ needcreate = _phasenum; newstart = block.timestamp; start = block.timestamp; phasenum = 0; }else{ if(block.timestamp + duration*_phasenum <= end) { needcreate = 0; } else { needcreate = _phasenum - (end - block.timestamp)/duration; } } uint256 needrenew = _phasenum - needcreate; IERC20 token = IERC20(rewardtoken); for(uint256 i = 0; i < needrenew; i++){ address renewEP = epoches[renewphase+i]; uint256 amount = _interestone; if(i == _phasenum-1){ amount = _interestone + _principal; } Epoch(renewEP).mint(debtor, amount); token.transferFrom(msg.sender, renewEP, amount); } uint256 idnum = epoches.length; for(uint256 j = 0; j < needcreate; j++){ uint256 amount = _interestone; if(needrenew + j == _phasenum - 1){ amount = _principal + _interestone; } string memory name = string(abi.encodePacked(string("Epoch#"), (j+idnum).toString())); string memory symbol = string(abi.encodePacked(string("EP#"), (j+idnum).toString())); address ep = createClone(epochImp); Epoch(ep).initialize(rewardtoken, newstart + (j+1)*duration, debtor, amount, name, symbol); epoches.push(ep); emit NewEpoch(address(ep)); token.transferFrom(msg.sender, ep, amount); } end = newstart + needcreate * duration; phasenum = phasenum + needcreate; } function renewSingleEpoch(uint256 id, uint256 amount, address to) external onlyOwner{ require(epoches[id] != address(0), "unavailable epoch"); IERC20(rewardtoken).transferFrom(msg.sender, epoches[id], amount); Epoch(epoches[id]).mint(to, amount); } // redeem all function redeemAll(address to) external { address user = msg.sender; for( uint256 i = 0; i < epoches.length; i++ ){ Epoch ep = Epoch(epoches[i]); if( block.timestamp > ep.end() ){ uint256 user_balance = ep.balanceOf(user); if( user_balance > 0 ){ ep.redeem(user, to, user_balance); } } else { break; } } } function redeem(address[] memory epochs, uint[] memory amounts, address to) external { require(epochs.length == amounts.length, "mismatch length"); address user = msg.sender; for( uint256 i = 0; i < epochs.length; i++ ){ Epoch ep = Epoch(epochs[i]); require( block.timestamp > ep.end(), "epoch not end"); ep.redeem(user, to, amounts[i]); } } function redeemOrTransfer(address[] memory epochs, uint[] memory amounts, address to) external { require(epochs.length == amounts.length, "mismatch length"); address user = msg.sender; for( uint256 i = 0; i < epochs.length; i++){ Epoch ep = Epoch(epochs[i]); if( block.timestamp > ep.end()) { ep.redeem(user, to, amounts[i]); } else { ep.multiTransfer(user, to, amounts[i]); } } } function multiTransfer(address[] memory epochs, uint[] memory amounts, address to) external { require(epochs.length == amounts.length, "mismatch length"); address user = msg.sender; for( uint256 i = 0; i < epochs.length; i++){ Epoch ep = Epoch(epochs[i]); ep.multiTransfer(user, to, amounts[i]); } } } pragma solidity >=0.8.0; // introduction of proxy mode design: https://docs.openzeppelin.com/upgrades/2.8/ // minimum implementation of transparent proxy: https://eips.ethereum.org/EIPS/eip-1167 contract CloneFactory { function createClone(address prototype) internal returns (address proxy) { bytes20 targetBytes = bytes20(prototype); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) proxy := create(0, clone, 0x37) } return proxy; } }
Public SMART CONTRACT AUDIT REPORT for Duet Bond Prepared By: Patrick Lou PeckShield March 19, 2022 1/23 PeckShield Audit Report #: 2022-095Public Document Properties Client Duet Finance Title Smart Contract Audit Report Target Duet Bond Version 1.0 Author Xiaotao Wu Auditors Xiaotao Wu, Xuxian Jiang Reviewed by Patrick Lou Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 March 19, 2022 Xiaotao Wu Final Release 1.0-rc March 18, 2022 Xiaotao Wu Release Candidate Contact For more information about this document and its contents, please contact PeckShield Inc. Name Patrick Lou Phone +86 183 5897 7782 Email contact@peckshield.com 2/23 PeckShield Audit Report #: 2022-095Public Contents 1 Introduction 4 1.1 About Duet Bond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2 Findings 10 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3 Detailed Results 12 3.1 Exposure Of Permissioned VaultFarm::massUpdatePools() . . . . . . . . . . . . . . . 12 3.2 Incorrect Epoch Removal Logic In VaultFarm::removePoolEpoch . . . . . . . . . . . 13 3.3 Accommodation Of Non-ERC20-Compliant Tokens . . . . . . . . . . . . . . . . . . 14 3.4 Improved Sanity Checks Of System/Function Parameters . . . . . . . . . . . . . . . 16 3.5 Incorrect start Update Logic In SingleBond::renewal() . . . . . . . . . . . . . . . . . 17 3.6 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 4 Conclusion 22 References 23 3/23 PeckShield Audit Report #: 2022-095Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the Duet Bond feature, 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 is well designed and engineered, though it can be further improved by addressing our suggestions. This document outlines our audit results. 1.1 About Duet Bond Duetis a multi-chain synthetic asset protocol with a hybrid mechanism (overcollateralization + algorithm-pegged) that sharpens assets to be traded on the blockchain. A duet in music refers to a piece of music where two people play different parts or melodies. Similarly, the Duetprotocol allows traders to replicate the real-world tradable assets in a decentralized finance ecosystem. The audited Duet Bond feature allows for the protocol administrator to issue bonds through the bond fac- tory and set the reward pools. The DYTokendeposited to the Duet Vault by a user will be synchronized to the reward pool and get Epochtokens in return. The basic information of the audited protocol is as follows: Table 1.1: Basic Information of Duet Bond ItemDescription NameDuet Finance Website https://duet.finance/ TypeSolidity Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report March 19, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in 4/23 PeckShield Audit Report #: 2022-095Public this audit. •https://github.com/duet-protocol/duet-bond-contract.git (549f7d3) And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/duet-protocol/duet-bond-contract.git (0e841c5) 1.2 About PeckShield PeckShield Inc. [9] 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 [8]: •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/23 PeckShield Audit Report #: 2022-095Public 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/23 PeckShield Audit Report #: 2022-095Public 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 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) [7], 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 7/23 PeckShield Audit Report #: 2022-095Public 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/23 PeckShield Audit Report #: 2022-095Public 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/23 PeckShield Audit Report #: 2022-095Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the implementation of the Duet Bond smart 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 logic, 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 2 Informational 1 Total 6 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/23 PeckShield Audit Report #: 2022-095Public 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, 2low-severity vulnerabilities, and 1informational recommendation. Table 2.1: Key Duet Bond Audit Findings ID Severity Title Category Status PVE-001 High Exposure Of Permissioned Vault- Farm::massUpdatePools()Business Logic Resolved PVE-002 Medium Incorrect Epoch Removal Logic In VaultFarm::removePoolEpochBusiness Logic Resolved PVE-003 Low Accommodation Of Non-ERC20- Compliant TokensCoding Practices Resolved PVE-004 Informational Improved Sanity Checks Of System/- Function ParametersCoding Practices Resolved PVE-005 Low Incorrect start Update Logic In Sin- gleBond::renewal()Business Logic Resolved PVE-006 Medium Trust Issue of Admin Keys Security Features 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. 11/23 PeckShield Audit Report #: 2022-095Public 3 | Detailed Results 3.1 Exposure Of Permissioned VaultFarm::massUpdatePools() •ID: PVE-001 •Severity: High •Likelihood: High •Impact: High•Target: VaultFarm •Category: Business Logic [6] •CWE subcategory: CWE-841 [3] Description The Duet Bond feature has the VaultFarm contract to farm the Epochtokens for vault users. When examining the implementation of the VaultFarm contract, we notice the presence of a specific routine, i.e., massUpdatePools() . As the name indicates, this routine is used to update reward variables for all pools with the given input parameters. To elaborate, we show below the code snippet of this function. 111 function massUpdatePools ( address [] memory epochs , uint256 [] memory rewards ) public { 112 uint256 poolLen = pools . length ; 113 uint256 epochLen = epochs . length ; 116 uint [] memory epochArr = new uint []( epochLen ); 117 for ( uint256 pi = 0; pi < poolLen ; pi ++) { 118 for ( uint256 ei = 0; ei < epochLen ; ei ++) { 119 epochArr [ei] = rewards [ei] * allocPoint [ pools [pi ]] / totalAllocPoint ; 120 } 121 Pool ( pools [pi ]). updateReward ( epochs , epochArr , periodFinish ); 122 } 124 epochRewards = rewards ; 125 lastUpdateSecond = block . timestamp ; 126 } Listing 3.1: VaultFarm::massUpdatePools() 12/23 PeckShield Audit Report #: 2022-095Public However, we notice that this routine is currently permissionless, which means it can be invoked by anyone to update reward variables for all pools according to his wish. To fix, the function type needs to be changed from publictointernal such that this function can only be accessed internally. Recommendation Adjustthefunctiontypefrom publictointernalfortheabove massUpdatePools ()function. Status This issue has been fixed in the following commit: 655a706. 3.2 Incorrect Epoch Removal Logic In VaultFarm::removePoolEpoch •ID: PVE-002 •Severity: Medium •Likelihood: High •Impact: Medium•Target: VaultFarm •Category: Business Logic [6] •CWE subcategory: CWE-841 [3] Description The VaultFarm contract provides an external removePoolEpoch() function for the privileged Ownerac- count to remove a specified epochtoken from a specified pool. Our analysis with this routine shows its current logic is not correct. To elaborate, we show below its code snippet. It comes to our attention that there is a lack of pending rewards handling and related storage arrays epochs/epochRewards updates before removing anepochtoken from a pool. If the storage arrays epochs/epochRewards are not updated timely, this removed epochtoken will be added to the pool again if the newPool()/updatePool()/appendReward() functions are called by the privileged Owneraccount. 174 function removePoolEpoch ( address pool , address epoch ) external onlyOwner { 175 Pool ( pool ). remove ( epoch ); 176 } Listing 3.2: VaultFarm::removePoolEpoch() 49 // remove some item for saving gas ( array issue ). 50 // should only used when no such epoch assets . 51 function remove ( address epoch ) external onlyFarming { 52 require ( validEpoches [ epoch ], " Not a valid epoch "); 53 validEpoches [ epoch ] = false ; 54 55 uint len = epoches . length ; 56 for ( uint i = 0; i < len ; i ++) { 13/23 PeckShield Audit Report #: 2022-095Public 57 if( epoch == epoches [i]) { 58 if (i == len - 1) { 59 epoches . pop (); 60 break ; 61 } else { 62 epoches [i] = epoches [ len - 1]; 63 epoches . pop (); 64 break ; 65 } 66 } 67 } 68 } Listing 3.3: Pool::remove() Recommendation Add pending rewards handling and storage arrays epoches/epochRewards updates logic before removing an epochtoken from a pool. Status This issue has been fixed in the following commit: 0e841c5. 3.3 Accommodation Of Non-ERC20-Compliant Tokens •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: SingleBond/SingleBondsFactory •Category: Coding Practices [5] •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 . 14/23 PeckShield Audit Report #: 2022-095Public 197 * @param _value The amount of tokens to be spent . 198 */ 199 function approve ( address _spender , uint _value ) public onlyPayloadSize (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) && ( allowed [ msg . sender ][ _spender ] != 0))); 207 allowed [ 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() with a currently non-zero allowance may fail. To accommodate the specific idiosyncrasy, there is a need to approve() twice: the first one reduces the allowance to 0; and the second one sets the new allowance. Moreover, it is important to note that for certain non-compliant ERC20 tokens (e.g., USDT), the approve() function does not have a return value. However, the IERC20interface has defined the following approve() interface with a boolreturn value: function approve(address spender, uint256 amount)external returns (bool) . As a result, the call to approve() may expect a return value. With the lack of return value of USDT’sapprove() , the call will be unfortunately reverted. 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 transferFrom() as well, i.e., safeTransferFrom() . In the following, we use the SingleBondsFactory::renewal() routine as an example. If the USDTto- ken is supported as rewardtoken , the unsafe version of token.approve(address(bondAddr), totalAmount) may revert as there is no return value in the USDTtoken contract’s approve() implementation (but the IERC20interface expects a return value)! 37 function renewal ( SingleBond bondAddr , uint256 _phasenum , uint256 _principal , uint256 _interestone ) external onlyOwner { 38 IERC20 token = IERC20 ( bondAddr . rewardtoken ()); 39 uint totalAmount = _phasenum * _interestone + _principal ; 40 require ( token . balanceOf ( msg . sender ) >= totalAmount , " factory :no balance "); 41 token . safeTransferFrom ( msg . sender , address ( this ), totalAmount ); 42 token . approve ( address ( bondAddr ), totalAmount ); 44 bondAddr . renewal ( _phasenum , _principal , _interestone ); 45 } Listing 3.5: SingleBondsFactory::renewal() 15/23 PeckShield Audit Report #: 2022-095Public Note that a number of routines can be similarly improved, including SingleBondsFactory::newBonds ()/renewSingleEpoch() , and SingleBond::initBond()/renewal()/renewSingleEpoch() . Recommendation Accommodate the above-mentioned idiosyncrasy about ERC20-related approve()/transferFrom() . Status This issue has been fixed in the following commit: 655a706. 3.4 Improved Sanity Checks Of System/Function Parameters •ID: PVE-004 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: VaultFarm •Category: Coding Practices [5] •CWE subcategory: CWE-1126 [1] Description In the VaultFarm contract, the newReward() function allows for the privileged Owneraccount to add Epochtokens as rewards for existing pools. While reviewing the implementation of this routine, we notice that it can benefit from additional sanity checks. To elaborate, we show below the full implementation of the newReward() function. Specifically, thereisalackoflengthverificationfortheinputparameters. Thustheexecutionof IERC20(epochs[i]) .transferFrom(msg.sender, address(this), rewards[i]) will revert if epochs.length > rewards.length (line 139). 129 function newReward ( address [] memory epochs , uint256 [] memory rewards , uint duration ) public onlyOwner { 130 require ( block . timestamp >= periodFinish , ’period not finish ’); 131 require ( duration > 0, ’duration zero ’); 132 133 periodFinish = block . timestamp + duration ; 134 epoches = epochs ; 135 massUpdatePools ( epochs , rewards ); 136 137 for ( uint i = 0 ; i < epochs . length ; i++) { 138 require ( IEpoch ( epochs [i]). bond () == bond , " invalid epoch "); 139 IERC20 ( epochs [i]). transferFrom (msg .sender , address ( this ), rewards [i]); 140 } 141 } Listing 3.6: VaultFarm::newReward() Recommendation Add length verification for the input parameters. 16/23 PeckShield Audit Report #: 2022-095Public Status This issue has been fixed in the following commit: 655a706. 3.5 Incorrect start Update Logic In SingleBond::renewal() •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Low•Target: SingleBond •Category: Business Logic [6] •CWE subcategory: CWE-841 [3] Description The SingleBond contract provides an external renewal() function for the privileged Owner(i.e., the SingleBondsFactory contract) to create Epochtoken contracts and transfer the rewardtoken to these Epochtoken contracts as the underlying tokens. In the following, we show the code snippet of the renewal() routine. Our analysis with this routine shows that the update of the state variables newstart/start is not implemented correctly. Specifically, the conditions for updating the state variables newstart/start should be block.timestamp > end, instead of current block.timestamp + duration >= end (line 76). 71 // renewal bond will start at next phase 72 function renewal ( uint256 _phasenum , uint256 _principal , uint256 _interestone ) external onlyOwner { 73 uint256 needcreate = 0; 74 uint256 newstart = end ; 75 uint256 renewphase = ( block . timestamp - start )/ duration + 1; 76 if( block . timestamp + duration >= end ){ 77 needcreate = _phasenum ; 78 newstart = block . timestamp ; 79 start = block . timestamp ; 80 phasenum = 0; 81 } else { 82 if( block . timestamp + duration * _phasenum <= end ) { 83 needcreate = 0; 84 } else { 85 needcreate = _phasenum - ( end - block . timestamp )/ duration ; 86 } 87 } 88 89 ... 90 } Listing 3.7: SingleBond::renewal() Recommendation Correct the above renewal() logic by fixing the ifstatement as follows. 17/23 PeckShield Audit Report #: 2022-095Public 71 // renewal bond will start at next phase 72 function renewal ( uint256 _phasenum , uint256 _principal , uint256 _interestone ) external onlyOwner { 73 uint256 needcreate = 0; 74 uint256 newstart = end ; 75 uint256 renewphase = ( block . timestamp - start )/ duration + 1; 76 if( block . timestamp > end ){ 77 needcreate = _phasenum ; 78 newstart = block . timestamp ; 79 start = block . timestamp ; 80 phasenum = 0; 81 } else { 82 if( block . timestamp + duration * _phasenum <= end ) { 83 needcreate = 0; 84 } else { 85 needcreate = _phasenum - ( end - block . timestamp )/ duration ; 86 } 87 } 88 89 ... 90 } Listing 3.8: SingleBond::renewal() Status This issue has been fixed in the following commit: 655a706. 3.6 Trust Issue of Admin Keys •ID: PVE-006 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple contracts •Category: Security Features [4] •CWE subcategory: CWE-287 [2] Description In the Duet Bond feature, there is a privileged owneraccount that plays a critical role in governing and regulating the system-wide operations (e.g., set pool implementation, approve vault, create rewards or append rewards for existing pools, remove Epochfrom an existing pool, create/update pool, emergency withdraw Epochtokens from the VaultFarm contract, renew bond, and renew single epochfor an existing bond, set periodfor the DexUSDOracle contract, etc.). It also has the privilege to control or govern the flow of assets managed by this feature. 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. 18/23 PeckShield Audit Report #: 2022-095Public 46 function setPoolImp ( address _poolImp ) external onlyOwner { 47 poolImp = _poolImp ; 48 } 50 function approveVault ( address vault , bool approved ) external onlyOwner { 51 vaults [ vault ] = approved ; 52 emit VaultApproved (vault , approved ); 53 } Listing 3.9: VaultFarm::setPoolImp()/approveVault() 128 // epochs need small for gas issue . 129 function newReward ( address [] memory epochs , uint256 [] memory rewards , uint duration ) public onlyOwner { 130 require ( block . timestamp >= periodFinish , ’period not finish ’); 131 require ( duration > 0, ’duration zero ’); 133 periodFinish = block . timestamp + duration ; 134 epoches = epochs ; 135 massUpdatePools ( epochs , rewards ); 137 for ( uint i = 0 ; i < epochs . length ; i++) { 138 require ( IEpoch ( epochs [i]). bond () == bond , " invalid epoch "); 139 IERC20 ( epochs [i]). transferFrom ( msg. sender , address ( this ), rewards [i]); 140 } 141 } 143 function appendReward ( address epoch , uint256 reward ) public onlyOwner { 144 require ( block . timestamp < periodFinish , ’period not finish ’); 145 require ( IEpoch ( epoch ). bond () == bond , " invalid epoch "); 147 bool inEpoch ; 148 uint i; 149 for (; i < epoches . length ; i++) { 150 if ( epoch == epoches [i]) { 151 inEpoch = true ; 152 break ; 153 } 154 } 156 uint [] memory leftRewards = calLeftAwards (); 157 if (! inEpoch ) { 158 epoches . push ( epoch ); 159 uint [] memory newleftRewards = new uint []( epoches . length ); 160 for ( uint j = 0; j < leftRewards . length ; j ++) { 161 newleftRewards [j] = leftRewards [j]; 162 } 163 newleftRewards [ leftRewards . length ] = reward ; 165 massUpdatePools ( epoches , newleftRewards ); 166 } else { 167 leftRewards [i] += reward ; 168 massUpdatePools ( epoches , leftRewards ); 19/23 PeckShield Audit Report #: 2022-095Public 169 } 171 IERC20 ( epoch ). transferFrom ( msg. sender , address ( this ), reward ); 172 } 174 function removePoolEpoch ( address pool , address epoch ) external onlyOwner { 175 Pool ( pool ). remove ( epoch ); 176 } Listing 3.10: VaultFarm::newReward()/appendReward()/removePoolEpoch() 191 function newPool ( uint256 _allocPoint , address asset ) public onlyOwner { 192 require ( assetPool [ asset ] == address (0) , " pool exist !"); 194 address pool = createClone ( poolImp ); 195 Pool ( pool ). init (); 197 pools . push ( pool ); 198 allocPoint [ pool ] = _allocPoint ; 199 assetPool [ asset ] = pool ; 200 totalAllocPoint = totalAllocPoint + _allocPoint ; 202 emit NewPool (asset , pool ); 203 uint [] memory leftRewards = calLeftAwards (); 204 massUpdatePools ( epoches , leftRewards ); 205 } 207 function updatePool ( uint256 _allocPoint , address asset ) public onlyOwner { 208 address pool = assetPool [ asset ]; 209 require ( pool != address (0) , " pool not exist !"); 211 totalAllocPoint = totalAllocPoint - allocPoint [ pool ] + _allocPoint ; 212 allocPoint [ pool ] = _allocPoint ; 214 uint [] memory leftRewards = calLeftAwards (); 215 massUpdatePools ( epoches , leftRewards ); 216 } Listing 3.11: VaultFarm::newPool()/updatePool() 247 function emergencyWithdraw ( address [] memory epochs , uint256 [] memory amounts ) external onlyOwner { 248 require ( epochs . length == amounts . length , " mismatch length "); 249 for ( uint i = 0 ; i < epochs . length ; i++) { 250 IERC20 ( epochs [i]). transfer ( msg. sender , amounts [i]); 251 } 252 } Listing 3.12: VaultFarm::emergencyWithdraw() 37 function renewal ( SingleBond bondAddr , uint256 _phasenum , uint256 _principal , uint256 _interestone ) external onlyOwner { 20/23 PeckShield Audit Report #: 2022-095Public 38 IERC20 token = IERC20 ( bondAddr . rewardtoken ()); 39 uint totalAmount = _phasenum * _interestone + _principal ; 40 require ( token . balanceOf ( msg . sender ) >= totalAmount , " factory :no balance "); 41 token . safeTransferFrom ( msg . sender , address ( this ), totalAmount ); 42 token . approve ( address ( bondAddr ), totalAmount ); 44 bondAddr . renewal ( _phasenum , _principal , _interestone ); 45 } 47 function renewSingleEpoch ( SingleBond bondAddr , uint256 id , uint256 amount , address to) external onlyOwner { 48 IERC20 token = IERC20 ( bondAddr . rewardtoken ()); 49 token . safeTransferFrom ( msg . sender , address ( this ), amount ); 50 token . approve ( address ( bondAddr ), amount ); 51 bondAddr . renewSingleEpoch (id ,amount ,to); 52 } Listing 3.13: SingleBondsFactory::renewal()/renewSingleEpoch() 71 function setPeriod ( uint _period ) external onlyOwner { 72 period = _period ; 73 emit PeriodChanged ( _period ); 74 } Listing 3.14: DexUSDOracle::setPeriod() 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. 21/23 PeckShield Audit Report #: 2022-095Public 4 | Conclusion In this audit, we have analyzed the Duet Bond design and implementation. The audited Duet Bond feature allows for the protocol administrator to issue bonds through the bond factory and set the reward pools. The DYTokendeposited to the Duet Vault by a user will be synchronized to the reward pool and users will get Epochtokens in return. 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. 22/23 PeckShield Audit Report #: 2022-095Public References [1] MITRE. CWE-1126: Declaration of Variable with Unnecessarily Wide Scope. https://cwe.mitre. org/data/definitions/1126.html. [2] MITRE. CWE-287: Improper Authentication. https://cwe.mitre.org/data/definitions/287.html. [3] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/data/ definitions/841.html. [4] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [5] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [6] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/840. html. [7] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699.html. [8] OWASP. RiskRatingMethodology. https://www.owasp.org/index.php/OWASP_Risk_Rating_ Methodology. [9] PeckShield. PeckShield Inc. https://www.peckshield.com. 23/23 PeckShield Audit Report #: 2022-095
Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 1 Critical: 0 Minor Issues: 2.a Problem: Exposure Of Permissioned VaultFarm::massUpdatePools() (3.1) 2.b Fix: Add a modifier to restrict the function call to the admin (3.1) Moderate: 3.a Problem: Incorrect Epoch Removal Logic In VaultFarm::removePoolEpoch (3.2) 3.b Fix: Add a check to ensure that the epoch is not the current epoch (3.2) Major: 4.a Problem: Incorrect start Update Logic In SingleBond::renewal() (3.5) 4.b Fix: Add a check to ensure that the start time is not before the current time (3.5) Observations: The Duet Bond feature is well designed and engineered, though it can be further improved by addressing the suggestions provided in the report. Conclusion: The Duet Bond feature is secure and can be deployed with minor improvements. 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 `_mint` (Lines 545-546). 2.b Fix (one line with code reference): Checked return value in the function `_mint` (Lines 545-546). Moderate: None Major: None Critical: None Observations: - The audited Duet Bond feature allows for the protocol administrator to issue bonds through the bond factory and set the reward pools. - The DYTokendeposited to the Duet Vault by a user will be synchronized to the reward pool and get Epochtokens in return. - The audit was conducted using a whitebox method. - The Git repository of reviewed files and the commit hash value used in the audit were provided. Conclusion: The audit of the Duet Bond feature found no critical, major, or moderate issues. Two minor issues were identified and fixed. Issues Count of Minor/Moderate/Major/Critical: - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations: - No issues were identified during the audit. Conclusion: - The contract is considered safe and secure.
/** * @title: Idle Token main contract * @summary: ERC20 that holds pooled user funds together * Each token rapresent a share of the underlying pools * and with each token user have the right to redeem a portion of these pools * @author: William Bergamo, idle.finance */ pragma solidity 0.5.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/lifecycle/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/iERC20Fulcrum.sol"; import "./interfaces/ILendingProtocol.sol"; import "./interfaces/IIdleToken.sol"; import "./IdleRebalancer.sol"; import "./IdlePriceCalculator.sol"; contract IdleToken is ERC20, ERC20Detailed, ReentrancyGuard, Ownable, Pausable, IIdleToken { using SafeERC20 for IERC20; using SafeMath for uint256; // protocolWrappers may be changed/updated/removed do not rely on their // addresses to determine where funds are allocated // eg. cTokenAddress => IdleCompoundAddress mapping(address => address) public protocolWrappers; // eg. DAI address address public token; // eg. iDAI address address public iToken; // used for claimITokens and userClaimITokens // Min thresold of APR difference between protocols to trigger a rebalance uint256 public minRateDifference; // Idle rebalancer current implementation address address public rebalancer; // Idle rebalancer current implementation address address public priceCalculator; // Last iToken price, used to pause contract in case of a black swan event uint256 public lastITokenPrice; // Manual trigger for unpausing contract in case of a black swan event that caused the iToken price to not // return to the normal level bool public manualPlay = false; // no one can directly change this // Idle pool current investments eg. [cTokenAddress, iTokenAddress] address[] public currentTokensUsed; // eg. [cTokenAddress, iTokenAddress, ...] address[] public allAvailableTokens; struct TokenProtocol { address tokenAddr; address protocolAddr; } event Rebalance(uint256 amount); /** * @dev constructor, initialize some variables, mainly addresses of other contracts * * @param _name : IdleToken name * @param _symbol : IdleToken symbol * @param _decimals : IdleToken decimals * @param _token : underlying token address * @param _cToken : cToken address * @param _iToken : iToken address * @param _rebalancer : Idle Rebalancer address * @param _idleCompound : Idle Compound address * @param _idleFulcrum : Idle Fulcrum address */ constructor( string memory _name, // eg. IdleDAI string memory _symbol, // eg. IDLEDAI uint8 _decimals, // eg. 18 address _token, address _cToken, address _iToken, address _rebalancer, address _priceCalculator, address _idleCompound, address _idleFulcrum) public ERC20Detailed(_name, _symbol, _decimals) { token = _token; iToken = _iToken; // used for claimITokens and userClaimITokens methods rebalancer = _rebalancer; priceCalculator = _priceCalculator; protocolWrappers[_cToken] = _idleCompound; protocolWrappers[_iToken] = _idleFulcrum; allAvailableTokens = [_cToken, _iToken]; minRateDifference = 100000000000000000; // 0.1% min } modifier whenITokenPriceHasNotDecreased() { uint256 iTokenPrice = iERC20Fulcrum(iToken).tokenPrice(); require( iTokenPrice >= lastITokenPrice || manualPlay, "Paused: iToken price decreased" ); _; if (iTokenPrice > lastITokenPrice) { lastITokenPrice = iTokenPrice; } } // onlyOwner /** * It allows owner to set the underlying token address * * @param _token : underlying token address tracked by this contract (eg DAI address) */ function setToken(address _token) external onlyOwner { token = _token; } /** * It allows owner to set the iToken (Fulcrum) address * * @param _iToken : iToken address */ function setIToken(address _iToken) external onlyOwner { iToken = _iToken; } /** * It allows owner to set the IdleRebalancer address * * @param _rebalancer : new IdleRebalancer address */ function setRebalancer(address _rebalancer) external onlyOwner { rebalancer = _rebalancer; } /** * It allows owner to set the IdlePriceCalculator address * * @param _priceCalculator : new IdlePriceCalculator address */ function setPriceCalculator(address _priceCalculator) external onlyOwner { priceCalculator = _priceCalculator; } /** * It allows owner to set a protocol wrapper address * * @param _token : underlying token address (eg. DAI) * @param _wrapper : Idle protocol wrapper address */ function setProtocolWrapper(address _token, address _wrapper) external onlyOwner { // update allAvailableTokens if needed if (protocolWrappers[_token] == address(0)) { allAvailableTokens.push(_token); } protocolWrappers[_token] = _wrapper; } function setMinRateDifference(uint256 _rate) external onlyOwner { minRateDifference = _rate; } /** * It allows owner to unpause the contract when iToken price decreased and didn't return to the expected level * * @param _manualPlay : new IdleRebalancer address */ function setManualPlay(bool _manualPlay) external onlyOwner { manualPlay = _manualPlay; } // view /** * IdleToken price calculation, in underlying * * @return : price in underlying token */ function tokenPrice() public view returns (uint256 price) { address[] memory protocolWrappersAddresses = new address[](currentTokensUsed.length); for (uint8 i = 0; i < currentTokensUsed.length; i++) { protocolWrappersAddresses[i] = protocolWrappers[currentTokensUsed[i]]; } price = IdlePriceCalculator(priceCalculator).tokenPrice( this.totalSupply(), address(this), currentTokensUsed, protocolWrappersAddresses ); } /** * Get APR of every ILendingProtocol * * @return addresses: array of token addresses * @return aprs: array of aprs (ordered in respect to the `addresses` array) */ function getAPRs() public view returns (address[] memory addresses, uint256[] memory aprs) { address currToken; addresses = new address[](allAvailableTokens.length); aprs = new uint256[](allAvailableTokens.length); for (uint8 i = 0; i < allAvailableTokens.length; i++) { currToken = allAvailableTokens[i]; addresses[i] = currToken; aprs[i] = ILendingProtocol(protocolWrappers[currToken]).getAPR(); } } // external // We should save the amount one has deposited to calc interests /** * Used to mint IdleTokens, given an underlying amount (eg. DAI). * This method triggers a rebalance of the pools if needed * NOTE: User should 'approve' _amount of tokens before calling mintIdleToken * NOTE 2: this method can be paused * * @param _amount : amount of underlying token to be lended * @param _clientProtocolAmounts : client side calculated amounts to put on each lending protocol * @return mintedTokens : amount of IdleTokens minted */ function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts) external nonReentrant whenNotPaused whenITokenPriceHasNotDecreased returns (uint256 mintedTokens) { // Get current IdleToken price uint256 idlePrice = tokenPrice(); // transfer tokens to this contract IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); // Rebalance the current pool if needed and mint new supplyied amount rebalance(_amount, _clientProtocolAmounts); mintedTokens = _amount.mul(10**18).div(idlePrice); _mint(msg.sender, mintedTokens); } /** * Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn * This method triggers a rebalance of the pools if needed * NOTE: If the contract is paused or iToken price has decreased one can still redeem but no rebalance happens. * NOTE 2: If iToken price has decresed one should not redeem (but can do it) otherwise he would capitalize the loss. * Ideally one should wait until the black swan event is terminated * * @param _amount : amount of IdleTokens to be burned * @param _skipRebalance : whether to skip the rebalance process or not * @param _clientProtocolAmounts : client side calculated amounts to put on each lending protocol * @return redeemedTokens : amount of underlying tokens redeemed */ function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts) external nonReentrant returns (uint256 redeemedTokens) { address currentToken; for (uint8 i = 0; i < currentTokensUsed.length; i++) { currentToken = currentTokensUsed[i]; redeemedTokens = redeemedTokens.add( _redeemProtocolTokens( protocolWrappers[currentToken], currentToken, // _amount * protocolPoolBalance / idleSupply _amount.mul(IERC20(currentToken).balanceOf(address(this))).div(this.totalSupply()), // amount to redeem msg.sender ) ); } _burn(msg.sender, _amount); // Do not rebalance if contract is paused or iToken price has decreased if (this.paused() || iERC20Fulcrum(iToken).tokenPrice() < lastITokenPrice || _skipRebalance) { return redeemedTokens; } rebalance(0, _clientProtocolAmounts); } /** * Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn * and send interest-bearing tokens (eg. cDAI/iDAI) directly to the user. * Underlying (eg. DAI) is not redeemed here. * * @param _amount : amount of IdleTokens to be burned */ function redeemInterestBearingTokens(uint256 _amount) external nonReentrant { uint256 idleSupply = this.totalSupply(); address currentToken; for (uint8 i = 0; i < currentTokensUsed.length; i++) { currentToken = currentTokensUsed[i]; IERC20(currentToken).safeTransfer( msg.sender, _amount.mul(IERC20(currentToken).balanceOf(address(this))).div(idleSupply) // amount to redeem ); } _burn(msg.sender, _amount); } /** * Here we are redeeming unclaimed token from iToken contract to this contracts * then allocating claimedTokens with rebalancing * Everyone should be incentivized in calling this method * NOTE: this method can be paused * * @param _clientProtocolAmounts : client side calculated amounts to put on each lending protocol * @return claimedTokens : amount of underlying tokens claimed */ function claimITokens(uint256[] calldata _clientProtocolAmounts) external whenNotPaused whenITokenPriceHasNotDecreased returns (uint256 claimedTokens) { claimedTokens = iERC20Fulcrum(iToken).claimLoanToken(); rebalance(claimedTokens, _clientProtocolAmounts); } /** * Dynamic allocate all the pool across different lending protocols if needed * Everyone should be incentivized in calling this method * * If _newAmount == 0 then simple rebalance * else rebalance (if needed) and mint (always) * NOTE: this method can be paused * * @param _newAmount : amount of underlying tokens that needs to be minted with this rebalance * @param _clientProtocolAmounts : client side calculated amounts to put on each lending protocol * @return : whether has rebalanced or not */ function rebalance(uint256 _newAmount, uint256[] memory _clientProtocolAmounts) public whenNotPaused whenITokenPriceHasNotDecreased returns (bool) { // If we are using only one protocol we check if that protocol has still the best apr // if yes we check if it can support all `_newAmount` provided and still has the best apr bool shouldRebalance; address bestToken; if (currentTokensUsed.length == 1 && _newAmount > 0) { (shouldRebalance, bestToken) = _rebalanceCheck(_newAmount, currentTokensUsed[0]); if (!shouldRebalance) { // only one protocol is currently used and can support all the new liquidity _mintProtocolTokens(protocolWrappers[currentTokensUsed[0]], _newAmount); return false; // hasNotRebalanced } } // otherwise we redeem everything from every protocol and check if the protocol with the // best apr can support all the liquidity that we redeemed // - get current protocol used TokenProtocol[] memory tokenProtocols = _getCurrentProtocols(); // - redeem everything from each protocol for (uint8 i = 0; i < tokenProtocols.length; i++) { _redeemProtocolTokens( tokenProtocols[i].protocolAddr, tokenProtocols[i].tokenAddr, IERC20(tokenProtocols[i].tokenAddr).balanceOf(address(this)), address(this) // tokens are now in this contract ); } // remove all elements from `currentTokensUsed` delete currentTokensUsed; // tokenBalance here has already _newAmount counted uint256 tokenBalance = IERC20(token).balanceOf(address(this)); if (tokenBalance == 0) { return false; } // (we are re-fetching aprs because after redeeming they changed) (shouldRebalance, bestToken) = _rebalanceCheck(tokenBalance, address(0)); if (!shouldRebalance) { // only one protocol is currently used and can support all the new liquidity _mintProtocolTokens(protocolWrappers[bestToken], tokenBalance); // update current tokens used in IdleToken storage currentTokensUsed.push(bestToken); return false; // hasNotRebalanced } // if it's not the case we calculate the dynamic allocation for every protocol (address[] memory tokenAddresses, uint256[] memory protocolAmounts) = _calcAmounts(tokenBalance, _clientProtocolAmounts); // mint for each protocol and update currentTokensUsed uint256 currAmount; address currAddr; for (uint8 i = 0; i < protocolAmounts.length; i++) { currAmount = protocolAmounts[i]; if (currAmount == 0) { continue; } currAddr = tokenAddresses[i]; _mintProtocolTokens(protocolWrappers[currAddr], currAmount); // update current tokens used in IdleToken storage currentTokensUsed.push(currAddr); } emit Rebalance(tokenBalance); return true; // hasRebalanced } // internal /** * Check if a rebalance is needed * if there is only one protocol and has the best rate then check the nextRateWithAmount() * if rate is still the highest then put everything there * otherwise rebalance with all amount * * @param _amount : amount of underlying tokens that needs to be added to the current pools NAV * @return : whether should rebalanced or not */ function _rebalanceCheck(uint256 _amount, address currentToken) internal view returns (bool, address) { (address[] memory addresses, uint256[] memory aprs) = getAPRs(); if (aprs.length == 0) { return (false, address(0)); } // we are trying to find if the protocol with the highest APR can support all the liquidity // we intend to provide uint256 maxRate; address maxAddress; uint256 secondBestRate; uint256 currApr; address currAddr; // find best rate and secondBestRate for (uint8 i = 0; i < aprs.length; i++) { currApr = aprs[i]; currAddr = addresses[i]; if (currApr > maxRate) { secondBestRate = maxRate; maxRate = currApr; maxAddress = currAddr; } else if (currApr <= maxRate && currApr >= secondBestRate) { secondBestRate = currApr; } } if (currentToken != address(0) && currentToken != maxAddress) { return (true, maxAddress); } if (currentToken == address(0) || currentToken == maxAddress) { uint256 nextRate = _getProtocolNextRate(protocolWrappers[maxAddress], _amount); if (nextRate.add(minRateDifference) < secondBestRate) { return (true, maxAddress); } } return (false, maxAddress); } /** * Calls IdleRebalancer `calcRebalanceAmounts` method * * @param _amount : amount of underlying tokens that needs to be allocated on lending protocols * @return tokenAddresses : array with all token addresses used, * @return amounts : array with all amounts for each protocol in order, */ function _calcAmounts(uint256 _amount, uint256[] memory _clientProtocolAmounts) internal view returns (address[] memory, uint256[] memory) { uint256[] memory paramsRebalance = new uint256[](_clientProtocolAmounts.length + 1); paramsRebalance[0] = _amount; for (uint8 i = 1; i <= _clientProtocolAmounts.length; i++) { paramsRebalance[i] = _clientProtocolAmounts[i-1]; } return IdleRebalancer(rebalancer).calcRebalanceAmounts(paramsRebalance); } /** * Get addresses of current tokens and protocol wrappers used * * @return currentProtocolsUsed : array of `TokenProtocol` (currentToken address, protocolWrapper address) */ function _getCurrentProtocols() internal view returns (TokenProtocol[] memory currentProtocolsUsed) { currentProtocolsUsed = new TokenProtocol[](currentTokensUsed.length); for (uint8 i = 0; i < currentTokensUsed.length; i++) { currentProtocolsUsed[i] = TokenProtocol( currentTokensUsed[i], protocolWrappers[currentTokensUsed[i]] ); } } // ILendingProtocols calls /** * Get next rate of a lending protocol given an amount to be lended * * @param _wrapperAddr : address of protocol wrapper * @param _amount : amount of underlying to be lended * @return apr : new apr one will get after lending `_amount` */ function _getProtocolNextRate(address _wrapperAddr, uint256 _amount) internal view returns (uint256 apr) { ILendingProtocol _wrapper = ILendingProtocol(_wrapperAddr); apr = _wrapper.nextSupplyRate(_amount); } /** * Mint protocol tokens through protocol wrapper * * @param _wrapperAddr : address of protocol wrapper * @param _amount : amount of underlying to be lended * @return tokens : new tokens minted */ function _mintProtocolTokens(address _wrapperAddr, uint256 _amount) internal returns (uint256 tokens) { if (_amount == 0) { return tokens; } ILendingProtocol _wrapper = ILendingProtocol(_wrapperAddr); // Transfer _amount underlying token (eg. DAI) to _wrapperAddr IERC20(token).safeTransfer(_wrapperAddr, _amount); tokens = _wrapper.mint(); } /** * Redeem underlying tokens through protocol wrapper * * @param _wrapperAddr : address of protocol wrapper * @param _amount : amount of `_token` to redeem * @param _token : protocol token address * @param _account : should be msg.sender when rebalancing and final user when redeeming * @return tokens : new tokens minted */ function _redeemProtocolTokens(address _wrapperAddr, address _token, uint256 _amount, address _account) internal returns (uint256 tokens) { if (_amount == 0) { return tokens; } ILendingProtocol _wrapper = ILendingProtocol(_wrapperAddr); // Transfer _amount of _protocolToken (eg. cDAI) to _wrapperAddr IERC20(_token).safeTransfer(_wrapperAddr, _amount); tokens = _wrapper.redeem(_account); } } /** * @title: Idle Price Calculator contract * @summary: Used for calculating the current IdleToken price in underlying (eg. DAI) * price is: Net Asset Value / totalSupply * @author: William Bergamo, idle.finance */ pragma solidity 0.5.11; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/iERC20Fulcrum.sol"; import "./interfaces/ILendingProtocol.sol"; contract IdlePriceCalculator { using SafeMath for uint256; /** * IdleToken price calculation, in underlying (eg. DAI) * * @return : price in underlying token */ function tokenPrice( uint256 totalSupply, address idleToken, address[] calldata currentTokensUsed, address[] calldata protocolWrappersAddresses ) external view returns (uint256 price) { if (totalSupply == 0) { return 10**18; } uint256 currPrice; uint256 currNav; uint256 totNav; for (uint8 i = 0; i < currentTokensUsed.length; i++) { currPrice = ILendingProtocol(protocolWrappersAddresses[i]).getPriceInToken(); // NAV = price * poolSupply currNav = currPrice.mul(IERC20(currentTokensUsed[i]).balanceOf(idleToken)); totNav = totNav.add(currNav); } price = totNav.div(totalSupply); // idleToken price in token wei } } pragma solidity ^0.5.0; 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); } } /** * @title: Idle Rebalancer contract * @summary: Used for calculating amounts to lend on each implemented protocol. * This implementation works with Compound and Fulcrum only, * when a new protocol will be added this should be replaced * @author: William Bergamo, idle.finance */ pragma solidity 0.5.11; import "./interfaces/CERC20.sol"; import "./interfaces/iERC20Fulcrum.sol"; import "./interfaces/ILendingProtocol.sol"; import "./interfaces/WhitePaperInterestRateModel.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract IdleRebalancer is Ownable { using SafeMath for uint256; // IdleToken address address public idleToken; // protocol token (cToken) address address public cToken; // protocol token (iToken) address address public iToken; // cToken protocol wrapper IdleCompound address public cWrapper; // iToken protocol wrapper IdleFulcrum address public iWrapper; // max % difference between next supply rate of Fulcrum and Compound uint256 public maxRateDifference; // 10**17 -> 0.1 % // max % difference between off-chain user supplied params for rebalance and actual amount to be rebalanced uint256 public maxSupplyedParamsDifference; // 100000 -> 0.001% // max number of recursive calls for bisection algorithm uint256 public maxIterations; /** * @param _cToken : cToken address * @param _iToken : iToken address * @param _cWrapper : cWrapper address * @param _iWrapper : iWrapper address */ constructor(address _cToken, address _iToken, address _cWrapper, address _iWrapper) public { cToken = _cToken; iToken = _iToken; cWrapper = _cWrapper; iWrapper = _iWrapper; maxRateDifference = 10**17; // 0.1% maxSupplyedParamsDifference = 100000; // 0.001% //SWC-DoS With Block Gas Limit: L52 maxIterations = 30; } /** * Throws if called by any account other than IdleToken contract. */ modifier onlyIdle() { require(msg.sender == idleToken, "Ownable: caller is not IdleToken contract"); _; } // onlyOwner /** * sets idleToken address * @param _idleToken : idleToken address */ function setIdleToken(address _idleToken) external onlyOwner { idleToken = _idleToken; } /** * sets cToken address * @param _cToken : cToken address */ function setCToken(address _cToken) external onlyOwner { cToken = _cToken; } /** * sets iToken address * @param _iToken : iToken address */ function setIToken(address _iToken) external onlyOwner { iToken = _iToken; } /** * sets cToken wrapper address * @param _cWrapper : cToken wrapper address */ function setCTokenWrapper(address _cWrapper) external onlyOwner { cWrapper = _cWrapper; } /** * sets iToken wrapper address * @param _iWrapper : iToken wrapper address */ function setITokenWrapper(address _iWrapper) external onlyOwner { iWrapper = _iWrapper; } /** * sets maxIterations for bisection recursive calls * @param _maxIterations : max rate difference in percentage scaled by 10**18 */ function setMaxIterations(uint256 _maxIterations) external onlyOwner { maxIterations = _maxIterations; } /** * sets maxRateDifference * @param _maxDifference : max rate difference in percentage scaled by 10**18 */ function setMaxRateDifference(uint256 _maxDifference) external onlyOwner { maxRateDifference = _maxDifference; } /** * sets maxSupplyedParamsDifference * @param _maxSupplyedParamsDifference : max rate difference in percentage scaled by 10**18 */ function setMaxSupplyedParamsDifference(uint256 _maxSupplyedParamsDifference) external onlyOwner { maxSupplyedParamsDifference = _maxSupplyedParamsDifference; } // end onlyOwner /** * Used by IdleToken contract to calculate the amount to be lended * on each protocol in order to get the best available rate for all funds. * * @param _rebalanceParams : first param is the total amount to be rebalanced, * all other elements are client side calculated amounts to put on each lending protocol * @return tokenAddresses : array with all token addresses used, * currently [cTokenAddress, iTokenAddress] * @return amounts : array with all amounts for each protocol in order, * currently [amountCompound, amountFulcrum] */ function calcRebalanceAmounts(uint256[] calldata _rebalanceParams) external view onlyIdle returns (address[] memory tokenAddresses, uint256[] memory amounts) { // Get all params for calculating Compound nextSupplyRateWithParams CERC20 _cToken = CERC20(cToken); WhitePaperInterestRateModel white = WhitePaperInterestRateModel(_cToken.interestRateModel()); uint256[] memory paramsCompound = new uint256[](10); paramsCompound[0] = 10**18; // j paramsCompound[1] = white.baseRate(); // a paramsCompound[2] = _cToken.totalBorrows(); // b paramsCompound[3] = white.multiplier(); // c paramsCompound[4] = _cToken.totalReserves(); // d paramsCompound[5] = paramsCompound[0].sub(_cToken.reserveFactorMantissa()); // e paramsCompound[6] = _cToken.getCash(); // s paramsCompound[7] = white.blocksPerYear(); // k paramsCompound[8] = 100; // f // Get all params for calculating Fulcrum nextSupplyRateWithParams iERC20Fulcrum _iToken = iERC20Fulcrum(iToken); uint256[] memory paramsFulcrum = new uint256[](6); paramsFulcrum[0] = _iToken.avgBorrowInterestRate(); // a1 paramsFulcrum[1] = _iToken.totalAssetBorrow(); // b1 paramsFulcrum[2] = _iToken.totalAssetSupply(); // s1 paramsFulcrum[3] = _iToken.spreadMultiplier(); // o1 paramsFulcrum[4] = 10**20; // k1 tokenAddresses = new address[](2); tokenAddresses[0] = cToken; tokenAddresses[1] = iToken; // _rebalanceParams should be [totAmountToRebalance, amountCompound, amountFulcrum]; if (_rebalanceParams.length == 3) { (bool amountsAreCorrect, uint256[] memory checkedAmounts) = checkRebalanceAmounts(_rebalanceParams, paramsCompound, paramsFulcrum); if (amountsAreCorrect) { return (tokenAddresses, checkedAmounts); } } // Initial guess for shrinking initial bisection interval /* Compound: (getCash returns the available supply only, not the borrowed one) getCash + totalBorrows = totalSuppliedCompound Fulcrum: totalSupply = totalSuppliedFulcrum we try to correlate borrow and supply on both markets totC = totalSuppliedCompound + totalBorrowsCompound totF = totalSuppliedFulcrum + totalBorrowsFulcrum n : (totC + totF) = x : totF x = n * totF / (totC + totF) */ uint256 amountFulcrum = _rebalanceParams[0].mul(paramsFulcrum[2].add(paramsFulcrum[1])).div( paramsFulcrum[2].add(paramsFulcrum[1]).add(paramsCompound[6].add(paramsCompound[2]).add(paramsCompound[2])) ); // Recursive bisection algorithm amounts = bisectionRec( _rebalanceParams[0].sub(amountFulcrum), // amountCompound amountFulcrum, maxRateDifference, // 0.1% of rate difference, 0, // currIter maxIterations, // maxIter _rebalanceParams[0], paramsCompound, paramsFulcrum ); // returns [amountCompound, amountFulcrum] return (tokenAddresses, amounts); } /** * Used by IdleToken contract to check if provided amounts * causes the rates of Fulcrum and Compound to be balanced * (counting a tolerance) * * @param rebalanceParams : first element is the total amount to be rebalanced, * the rest is an array with all amounts for each protocol in order, * currently [amountCompound, amountFulcrum] * @param paramsCompound : array with all params (except for the newDAIAmount) * for calculating next supply rate of Compound * @param paramsFulcrum : array with all params (except for the newDAIAmount) * for calculating next supply rate of Fulcrum * @return bool : if provided amount correctly rebalances the pool */ function checkRebalanceAmounts( uint256[] memory rebalanceParams, uint256[] memory paramsCompound, uint256[] memory paramsFulcrum ) internal view returns (bool, uint256[] memory checkedAmounts) { // This is the amount that should be rebalanced no more no less uint256 actualAmountToBeRebalanced = rebalanceParams[0]; // n // interest is earned between when tx was submitted and when it is mined so params sent by users // should always be slightly less than what should be rebalanced uint256 totAmountSentByUser; for (uint8 i = 1; i < rebalanceParams.length; i++) { totAmountSentByUser = totAmountSentByUser.add(rebalanceParams[i]); } // check if amounts sent from user are less than actualAmountToBeRebalanced and // at most `actualAmountToBeRebalanced - 0.001% of (actualAmountToBeRebalanced)` if (totAmountSentByUser > actualAmountToBeRebalanced || totAmountSentByUser.add(totAmountSentByUser.div(maxSupplyedParamsDifference)) < actualAmountToBeRebalanced) { return (false, new uint256[](2)); } uint256 interestToBeSplitted = actualAmountToBeRebalanced.sub(totAmountSentByUser); // sets newDAIAmount for each protocol paramsCompound[9] = rebalanceParams[1].add(interestToBeSplitted.div(2)); paramsFulcrum[5] = rebalanceParams[2].add(interestToBeSplitted.sub(interestToBeSplitted.div(2))); // calculate next rates with amountCompound and amountFulcrum // For Fulcrum see https://github.com/bZxNetwork/bZx-monorepo/blob/development/packages/contracts/extensions/loanTokenization/contracts/LoanToken/LoanTokenLogicV3.sol#L1418 // fulcrumUtilRate = fulcrumBorrow.mul(10**20).div(assetSupply); uint256 currFulcRate = (paramsFulcrum[1].mul(10**20).div(paramsFulcrum[2])) > 90 ether ? ILendingProtocol(iWrapper).nextSupplyRate(paramsFulcrum[5]) : ILendingProtocol(iWrapper).nextSupplyRateWithParams(paramsFulcrum); uint256 currCompRate = ILendingProtocol(cWrapper).nextSupplyRateWithParams(paramsCompound); bool isCompoundBest = currCompRate > currFulcRate; // |fulcrumRate - compoundRate| <= tolerance bool areParamsOk = (currFulcRate.add(maxRateDifference) >= currCompRate && isCompoundBest) || (currCompRate.add(maxRateDifference) >= currFulcRate && !isCompoundBest); uint256[] memory actualParams = new uint256[](2); actualParams[0] = paramsCompound[9]; actualParams[1] = paramsFulcrum[5]; return (areParamsOk, actualParams); } /** * Internal implementation of our bisection algorithm * * @param amountCompound : amount to be lended in compound in current iteration * @param amountFulcrum : amount to be lended in Fulcrum in current iteration * @param tolerance : max % difference between next supply rate of Fulcrum and Compound * @param currIter : current iteration * @param maxIter : max number of iterations * @param n : amount of underlying tokens (eg. DAI) to rebalance * @param paramsCompound : array with all params (except for the newDAIAmount) * for calculating next supply rate of Compound * @param paramsFulcrum : array with all params (except for the newDAIAmount) * for calculating next supply rate of Fulcrum * @return amounts : array with all amounts for each protocol in order, * currently [amountCompound, amountFulcrum] */ function bisectionRec( uint256 amountCompound, uint256 amountFulcrum, uint256 tolerance, uint256 currIter, uint256 maxIter, uint256 n, uint256[] memory paramsCompound, uint256[] memory paramsFulcrum ) internal view returns (uint256[] memory amounts) { // sets newDAIAmount for each protocol paramsCompound[9] = amountCompound; paramsFulcrum[5] = amountFulcrum; // calculate next rates with amountCompound and amountFulcrum // For Fulcrum see https://github.com/bZxNetwork/bZx-monorepo/blob/development/packages/contracts/extensions/loanTokenization/contracts/LoanToken/LoanTokenLogicV3.sol#L1418 // fulcrumUtilRate = fulcrumBorrow.mul(10**20).div(assetSupply); uint256 currFulcRate = (paramsFulcrum[1].mul(10**20).div(paramsFulcrum[2])) > 90 ether ? ILendingProtocol(iWrapper).nextSupplyRate(amountFulcrum) : ILendingProtocol(iWrapper).nextSupplyRateWithParams(paramsFulcrum); uint256 currCompRate = ILendingProtocol(cWrapper).nextSupplyRateWithParams(paramsCompound); bool isCompoundBest = currCompRate > currFulcRate; // bisection interval update, we choose to halve the smaller amount uint256 step = amountCompound < amountFulcrum ? amountCompound.div(2) : amountFulcrum.div(2); // base case // |fulcrumRate - compoundRate| <= tolerance if ( ((currFulcRate.add(tolerance) >= currCompRate && isCompoundBest) || (currCompRate.add(tolerance) >= currFulcRate && !isCompoundBest)) || currIter >= maxIter ) { amounts = new uint256[](2); amounts[0] = amountCompound; amounts[1] = amountFulcrum; return amounts; } return bisectionRec( isCompoundBest ? amountCompound.add(step) : amountCompound.sub(step), isCompoundBest ? amountFulcrum.sub(step) : amountFulcrum.add(step), tolerance, currIter + 1, maxIter, n, paramsCompound, // paramsCompound[9] would be overwritten on next iteration paramsFulcrum // paramsFulcrum[5] would be overwritten on next iteration ); } } /** * @title: Idle Factory contract * @summary: Used for deploying and keeping track of IdleTokens instances * @author: William Bergamo, idle.finance */ pragma solidity 0.5.11; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./IdleToken.sol"; contract IdleFactory is Ownable { // tokenAddr (eg. DAI add) => idleTokenAddr (eg. idleDAI) mapping (address => address) public underlyingToIdleTokenMap; // array of underlying token addresses (eg. [DAIAddr, USDCAddr]) address[] public tokensSupported; /** * Used to deploy new instances of IdleTokens, only callable by owner * Ownership of IdleToken is then transferred to msg.sender. Same for Pauser role * * @param _name : IdleToken name * @param _symbol : IdleToken symbol * @param _decimals : IdleToken decimals * @param _token : underlying token address * @param _cToken : cToken address * @param _iToken : iToken address * @param _rebalancer : Idle Rebalancer address * @param _idleCompound : Idle Compound address * @param _idleFulcrum : Idle Fulcrum address * * @return : newly deployed IdleToken address */ function newIdleToken( string calldata _name, // eg. IdleDAI string calldata _symbol, // eg. IDLEDAI uint8 _decimals, // eg. 18 address _token, address _cToken, address _iToken, address _rebalancer, address _priceCalculator, address _idleCompound, address _idleFulcrum ) external onlyOwner returns(address) { IdleToken idleToken = new IdleToken( _name, // eg. IdleDAI _symbol, // eg. IDLEDAI _decimals, // eg. 18 _token, _cToken, _iToken, _rebalancer, _priceCalculator, _idleCompound, _idleFulcrum ); if (underlyingToIdleTokenMap[_token] == address(0)) { tokensSupported.push(_token); } underlyingToIdleTokenMap[_token] = address(idleToken); return address(idleToken); } /** * Used to transfer ownership and the ability to pause from IdleFactory to owner * * @param _idleToken : idleToken address who needs to change owner and pauser */ function setTokenOwnershipAndPauser(address _idleToken) external onlyOwner { IdleToken idleToken = IdleToken(_idleToken); idleToken.transferOwnership(msg.sender); idleToken.addPauser(msg.sender); idleToken.renouncePauser(); } /** * @return : array of supported underlying tokens */ function supportedTokens() external view returns(address[] memory) { return tokensSupported; } /** * @param _underlying : token address which maps to IdleToken address * @return : IdleToken address for that _underlying */ function getIdleTokenAddress(address _underlying) external view returns(address) { return underlyingToIdleTokenMap[_underlying]; } }
April 26th 2021— Quantstamp Verified Idle Finance This smart contract audit was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type Token Lending Aggregator Auditors Ed Zulkoski , Senior Security EngineerKacper Bąk , Senior Research EngineerPoming Lee , Research EngineerSebastian Banescu , Senior Research EngineerTimeline 2019-12-02 through 2021-04-23 EVM Muir Glacier Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification README.md Documentation Quality Medium Test Quality Medium Source Code Repository Commit idle-contracts 937f989 (initial audit) idle-contracts b5fb299 (latest audit) 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 39 (25 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 4 (4 Resolved)Low Risk Issues 11 (9 Resolved)Informational Risk Issues 18 (8 Resolved)Undetermined Risk Issues 6 (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 Idle contracts are generally well documented and well designed. Our main concerns below relate to centralized components of the system, and ensuring that users are aware of the roles and responsibilities of the Idle Finance team as owners of the smart contracts. We also noted some potential access control issues associated with rebalancing, which may lead to sub-optimal token allocations. Idle Finance has addressed our concerns as of commit . Update: bcb6f09 Recently, several attacks have occurred on bZx/Fulcrum (for reference, see and ), allowing lenders to create highly under-collateralized loans. Since Fulcrum is one of the underlying protocols that Idle may lend on, we recommend investigating these attacks to determine how much impact this may have on the Idle protocol. It may be prudent to temporarily disable Fulcrum as a potential lending platform until the full extent of the issues has been investigated. As a simple approach, we believe this could be accomplished in the following manner: Update 2:Attack 1 Attack 2 1. Deploy a new "dummy" wrapper contract that returns zero wheneveror are invoked. This essentially ensures that the rebalancer will always favor other wrappers when calculating the allocations. nextSupplyRate()nextSupplyRateWithParams() 2. As the owner, invoke. IdleToken.setProtocolWrapper("fulcrum address", "dummy wrapper address") Note that we also recommend adding additional tests to ensure that supply rates equal to zero do not cause any adverse affects. We have reviewed version 3 of the contracts based on commit . Our audit focused on the new wrapper contracts associated with and , and the new and . We noted several new sources of centralization, parts of the code which required further documentation, and possible gas-constant related issues. We recommend addressing these concerns before deploying the V3 contracts to production. Update 3:a71a706 Aave DyDx IdleTokenV3 IdleRebalancerV3 Several of our concerns have been addressed as of commit . Update 4: 64f22d0 Our concerns have been addressed as of commit . Update 5: fefd01d All concerns have been addressed as of commit . Update 6: 7d3b7e4 Quantstamp has reviewed updates to the contracts as of commit . Update 7: 93d3429 Quantstamp has reviewed updates as of commit . Update 8: f9c02d1 Quantstamp has reviewed updates as of commit . In this iteration, only , , and were audited (against the previously audited "V3" versions). New findings can be found in QSP-14 through QSP-20, and have been appended to the Best Practices and Documentation sections. Update 9:35d61ae IdleTokenV3_1.sol IdleRebalancerV3_1.sol IdleCompound.sol Quantstamp has reviewed updates as of commit . All existing issues have been resolved. However, there are several contracts such as , , and which we suggest improving coverage for. Update 10:338ec24 GSTConsumer*.sol IdleDSR.sol IdleDyDx.sol The Idle team has alerted Quantstamp of an issue in , in which the incorrect number of decimal places had been used. This issue has been resolved, and no new issues were found as of commit . Update 11:IdleTokenV3_1._tokenPrice() 1b40261 Several new issues of varying severity were noted during the audit of commit , as discussed in QSP-21 through QSP-31, and as appended to the best practices and documentation sections. Note that only was reviewed in this iteration. Update 12:50da42b9 IdleTokenV3_1.sol All issues have been addressed as of commit . Update 13: bd40915 The report has been updated based on the diff . This iteration is only scoped to changes in and . New findings are listed in QSP-32 through QSP-41, as well as appended to the best practices and documentation sections. Update 14:b928e84…e09d4f5 IdleTokenGovernance.sol IdleTokenHelper.sol The report has been updated based on commit . All previous issues have been resolved, mitigated, or acknowledged, and one new informational issue was added. Some acknowledged issues are not fully fixed due to contract bytecode size limits; we recommend refactoring the code into several contracts to avoid this problem. Update 15:b5fb299 ID Description Severity Status QSP- 1 Centralization of Power Medium Fixed QSP- 2 Missing modifier on and onlyIdle mint() redeem() Low Fixed QSP- 3 Gas Usage / Loop Concerns forInformational Fixed QSP- 4 Clone-and-Own Informational Fixed QSP- 5 Unlocked Pragma Informational Fixed QSP- 6 Undocumented magic constants Informational Fixed QSP- 7 Use of ABIEncoderV2 still experimental Informational Fixed QSP- 8 Unchecked constructor and setter address arguments Informational Fixed QSP- 9 Allowance Double-Spend Exploit Informational Acknowledged QSP- 10 Function may be blocked due to Fulcrum failure rebalance()Informational Fixed QSP- 11 Security of Idle contracts is dependent on underlying lending protocols Informational Acknowledged QSP- 12 may overwrite newIdleToken() underlyingToIdleTokenMap[_token] Undetermined Fixed QSP- 13 Gas constants may be affected by new EVM forks Undetermined Fixed QSP- 14 may fail if is reset to zero redeemIdleToken()fee Medium Fixed QSP- 15 Loss of precision due to truncation Low Fixed QSP- 16 Missing address sanitization Low Acknowledged QSP- 17 Length of input arrays can be different Low Fixed QSP- 18 Unclear update to mapping userAvgPricesLow Fixed QSP- 19 Potential flash loans attack vectors to claim COMP tokens Low Fixed QSP- 20 Privileged Roles and Ownership Informational Acknowledged QSP- 21 User may not be able to redeem Idle tokens Medium Fixed QSP- 22 Outdated could be used to influence the average APR govTokenLow Fixed QSP- 23 Incorrect hardcoded addresses Low Acknowledged QSP- 24 Inconsistent array lengths breaks invariants Low Fixed QSP- 25 Initialization can be done multiple times Informational Acknowledged QSP- 26 Missing input check Informational Acknowledged QSP- 27 Missing return value Informational Acknowledged QSP- 28 Privileged roles Informational Acknowledged QSP- 29 Incorrect average price computation Undetermined Fixed QSP- 30 Uninitialized inherited contracts and state variables Undetermined Acknowledged QSP- 31 Unclear functionality in _getFee Undetermined Fixed QSP- 32 Wrong comparison between lengths Medium Mitigated QSP- 33 The is not settable flashLoanFee Low Fixed QSP- 34 Inconsistent array lengths breaks invariant Low Mitigated IDDescription Severity Status QSP- 35 Flashloans may decrease funds if underlying protocols have redemption fees Informational Acknowledged QSP- 36 Unchecked function arguments Informational Acknowledged QSP- 37 Flashloan could be used as a tool to manipulate liquidities of the underlying lending protocols Informational Acknowledged QSP- 38 Uninitialized state variables Undetermined Acknowledged QSP- 39 Owner can front-run flash loaners to change loan fee Informational Mitigated 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: v4.1.12 • Trufflev0.5.8 • SolidityCoveragev0.22.8 • 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 . FindingsQSP-1 Centralization of Power Severity: Medium Risk Fixed Status: , , , , File(s) affected: IdleFulcrum.sol IdleRebalancer.sol IdleCompound.sol IdleTokenV3.sol IdleRebalancerV3.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. Description: owner In several contracts, the associated tokens may be changed by the owner. If the balances of the contracts are non-zero, users may not be able to retrieve funds or interact with the contract in a proper manner. In particular: In and , tokens may be updated by and . • IdleFulcrumIdleCompound setToken() setUnderlying() In , , , , , and may update underlying addresses. • IdleRebalancer.solsetIdleToken() setCToken() setIToken() setCTokenWrapper() setITokenWrapper() In and , the owner may add new token wrappers arbitrarily (which may not correspond to actual lending protocols). Additionally, the owner may pause/unpause certain functionalities, such as rebalancing. •IdleTokenV3IdleRebalancerV3.sol Limit the amount of centralized components in the system if possible. For example, if the underlying token is unlikely to change, consider setting it upon contract construction and removing the corresponding function. Additionally, 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. Recommendation:setUnderlying() Idle Finance has removed the corresponding setter functions. The centralization is mitigated as users may still redeem funds while the contract is paused. The centralization around adding new wrappers is mitigated through the use of a delay-scheme, such that new wrappers only go into effect after several days. Update:pausing QSP-2 Missing modifier on and onlyIdle mint() redeem() Severity: Low Risk Fixed Status: File(s) affected: IdleCompoundV2.sol For the functions and , there is no modifier, whereas the modifier exists in the corresponding functions in , , and . This would allow funds stored in the wrapper contract to be sent to an arbitrary address. Although the typical dApp workflow does not store funds directly in the wrapper contract (in favor of storing balances in , users interacting directly with the wrapper contract may mistakenly add funds to the contract directly. Adding the modifier to these functions would mitigate these incorrect interactions. Description:IdleCompoundV2.mint() IdleCompoundV2.redeem() onlyIdle IdleCompound.sol IdleFulcrum.sol IdleFulcrumV2.sol IdleCompoundV2 IdleToken IdleCompoundV2 onlyIdle Add the modifier to and . Recommendation: onlyIdle IdleCompoundV2.mint() IdleCompoundV2.redeem() QSP-3 Gas Usage / Loop Concerns forSeverity: Informational Fixed Status: , File(s) affected: IdleRebalancer.sol IdleToken.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 rebalancing functions may require several loops in the bisection algorithm. We recommend performing gas analysis to ensure that each loop-function will not run into gas limitations, particularly for large inputs. Recommendation: Idle Finance has indicated that each iteration of the bisection algorithm consumes approximately 12,500 gas, so the limit of (as defined in the constructor) should be sufficient to avoid gas limits. Update:maxIterations = 30 QSP-4 Clone-and-Own Severity: Informational Fixed Status: File(s) affected: IdleMcdBridge.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:In , there are several libraries that could be imported: , , , and . IdleMcdBridge.sol IERC20 SafeMathContext Address 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-5 Unlocked Pragma Severity: Informational Fixed Status: File(s) affected: IdleMcdBridge.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.4.* ^ and above The file has several instances of unlocked pragmas throughout. IdleMcdBridge.sol 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 Undocumented magic constantsSeverity: Informational Fixed Status: , File(s) affected: IdleAave.sol GST2Consumer.sol There are several defined constants in the code that were unclear, and would benefit from added inline documentation: Description: In , L161: the number 29; • IdleAave.solIn , the constant on L143 of : ; • IdleAave.solgetApr() 100/10^9 In , all numerical constants on L15, 19-20; • GST2Consumer.solIn , on L32, it is not immediately clear that the constant 100000 is 100%. • IdleRebalancerV3.solAdd documentation describing these constants. Recommendation: QSP-7 Use of ABIEncoderV2 still experimental Severity: Informational Fixed Status: File(s) affected: yxToken.sol Until solidity 0.6.0, the ABIEncoderV2 feature is still technically in experimental state. Although there are no known security risks associated with it, these features should be used judiciously. Description:Upgrade the contracts to a more recent solidity version such as or . All contracts that depend upon ABIEncoderV2 functionality should be tested thoroughly. Recommendation: 0.5.16 0.6.6 QSP-8 Unchecked constructor and setter address arguments Severity: Informational Fixed Status: File(s) affected: IdleRebalancerV3.sol * In , on L28, the constructor arguments and were not checked to be non-zero. Description: IdleRebalancerV3.sol _yxToken _rebalancerManager In , the constructor and all setter functions should check that addresses are non-zero. • IdleTokenV3.solAdd require statement ensuring that these parameters are non-zero. Recommendation: QSP-9 Allowance Double-Spend Exploit Severity: Informational Acknowledged Status: File(s) affected: IdleTokenV3.sol As it presently is constructed, the contract is vulnerable to the , as with other ERC20 tokens. Description: allowance double-spend exploit An example of an exploit goes as follows: 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 the method 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() QSP-10 Function may be blocked due to Fulcrum failure rebalance() Severity: Informational Fixed Status: File(s) affected: IdleTokenV3.sol On of , the modifier checks that function can only be executed when the iToken price has not decreased. However, since could get hacked (or the price of collateral may drop), it might not always be true. When this happens, the system would not be able to rebalance/reallocate funds for a period of time. Description:L508 IdleTokenV3.solwhenITokenPriceHasNotDecreased _rebalance Fulcrum There is a trade-off here -- including the modifier may cause delays in rebalancing, whereas removing it may cause adverse token allocations to Fulcrum. Documentationshould be added describing the need for the modifier if it remains. Recommendation:QSP-11 Security of Idle contracts is dependent on underlying lending protocols Severity: Informational Acknowledged Status: , File(s) affected: IdleTokenV3.sol IdleRebalancerV3.sol Although there is no immediate exploit known at this time, since protocol wrappers can be added arbitrarily in the future, this issue could occur, and further unforeseen issues could arise in the existing underlying protocols. Description:If a wrapped protocol is attackable, possibly through (but not limited to) flash loans, the following could occur. Suppose initially all funds are allocated to a secure protocol . Exploit Scenario: P S 1. Using a flash loan, the attacker creates a favorable price forand invokes . This causes the distribution to shift all underlying tokens to . P rebalance() P 2. The attacker attacks, which now has significantly more liquidity since all Idle funds are now allocated to it. PThis issue is partially mitigated already for Fulcrum through checks on the price, and further through the ability to pause rebalancing. New wrappers should be added cautiously. Recommendation:iToken QSP-12 may overwrite newIdleToken() underlyingToIdleTokenMap[_token] Severity: Undetermined Fixed Status: File(s) affected: IdleFactory.sol If is called with an existing address, the contract referenced in the will be overwritten. It is not clear if this is intended functionality. Description:newIdleToken() _token IdleToken underlyingToIdleTokenMap Document whether this is intended functionality. If not, prevent calls with existing addresses. Recommendation: newIdleToken() _token Idle Finance has addressed this concern through added documentation. Update: QSP-13 Gas constants may be affected by new EVM forks Severity: Undetermined Fixed Status: File(s) affected: GST2Consumer.sol In , several constants are defined related to gas usage. Since op-code gas costs may be updated in new forks, this may cause unforeseen gas issues in future forks. Description:GST2Consumer.sol Ensure that this functionality has been tested on the most recent EVM fork. In order to be resilient to future forks, setter functions could be added to update the gas variables. Recommendation:onlyOwner this has been fixed through the use of an setter function for the gas variables. Update: onlyOwner QSP-14 may fail if is reset to zero redeemIdleToken() fee Severity: Medium Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol Assume that: Description: A1: can only accumulated when is set to (according to the function). userNoFeeQty[msg.sender] fee 0 _updateAvgPrice() A2: the price of idleToken is and does not change a lot (this happens when the is large). 5 balanceUnderlying Consider the following scenario for some : user11. deposits underlying token when is set to . The will obtain idleToken, and we noted that equals to user1 100 fee 0 user1100/5 = 20 userNoFeeQty[user1] 20 2. Then the idleFinance team decides to change thefrom to . fee 0 10003. When thelater deposit again, with another underlaying token, the will obtain idleToken again. In addition to the formerly obtained idleToken, now the has idleTokens on hand. However, since now, the will remains equal to instead of equal to . user1100 user1 100/5 = 20 20 user1 20 + 20 = 40 fee != 0 userNoFeeQty[user1] 20 20 + 20 = 40 4. Then the idleFinance team decides to change thefrom to again. fee 1000 05. Finally, whendecides to redeem idleTokens through function by passing the parameter , we have that the is but the is . This will cause the revert of the function due to the statement: . user1redeemIdleToken() _amount = 40 _amount 40 userNoFeeQty[user1] 20 userNoFeeQty[msg.sender] = userNoFeeQty[msg.sender].sub(_amount); Revise the functionality to account for this scenario. Recommendation: userNoFeeQty QSP-15 Loss of precision due to truncation Severity: Low Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol The computation of the average APR inside thefunction, is performed by normalizing (dividing by ) the APR for each token separately and adding the normalized values together. Due to the limited precision and truncation of the division operation, there might be a loss of precision in this computation. Description:getAvgAPR() total Similarly the division by can be moved outside of the for-loop in the function. 10**18 _getCurrentPoolValue To increase the precision of the average APR (and save gas), one could first add all APRs multiplied by the amounts together and only divide by the at the end of the for-loop like so: Recommendation:total for (uint256 i = 0; i < allAvailableTokens.length; i++) { if (amounts[i] == 0) { continue; } avgApr = avgApr.add( ILendingProtocol(protocolWrappers[allAvailableTokens[i]]).getAPR().mul(amounts[i]); ); } avgApr = avgApr.div(total); QSP-16 Missing address sanitization Severity: Low Risk Acknowledged Status: File(s) affected: IdleTokenV3_1.sol The values inside the array input parameter are not checked to be different from inside the function. Description: _newGovTokens 0x0 setGovTokens Add statement that checks that the value of the is different from . Recommendation: require _newGovTokens 0x0 This has been acknowledged, however the check has not been added due to contract bytesize limitations. Update: QSP-17 Length of input arrays can be different Severity: Low Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol There are multiple occurrences of this issue: Description: 1. There is no check in place inside thefunction inside , which checks if the length of the , and the input arrays are equal. Since the for-loop inside this function goes up to it would be problematic if the lengths of the other arrays would be different (shorter or longer). redeemAllNeededIdleTokenV3_1 tokenAddresses amounts newAmounts amounts.length 2. There is no check in place inside thefunction inside , which checks if the length of the and the input arrays are equal. Since the for-loop inside this function goes up to it would be problematic if the lengths of the other array would be different (shorter or longer). _mintWithAmountsIdleTokenV3_1 tokenAddresses protocolAmounts protocolAmounts.length 3. There is no check in place inside thefunction inside , which checks if the length of the and the arrays have the same length. This could lead to removing or adding tokens and/or changing the order of the tokens w.r.t. the array order. setAllAvailableTokensAndWrappersIdleTokenV3_1 protocolTokens allAvailableTokens lastAllocations Check whether the lengths of input array parameters of functions are the same whenever this is a prerequisite. Recommendation: Regarding , those params come from which reads current contract data so it should not be a problem. Update: _redeemAllNeeded _getCurrentAllocations QSP-18 Unclear update to mapping userAvgPrices Severity: Low Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol In the function , the mapping is not updated if the . It is not clear why the mapping is not updated in this case, but since this case is not covered, the user's average price may not be correct in all scenarios. Description:_updateAvgPrice userAvgPrices fee == 0 Either update the function to update the average price in all branches, or consider renaming the mapping. Recommendation: QSP-19 Potential flash loans attack vectors to claim COMP tokens Severity: Low Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol After discussion with the Idle team, it appears that there may exist attack vectors that claim COMP tokens using flash loans, if a rebalance or redeem has not been invoked in a long time. This attack could occur if mint and redeem are invoked with a large balance in the same transaction (via a flash loan). Description:Add a lock variable that prevents a user from invoking mint and redeem functions within the same transaction. Recommendation: QSP-20 Privileged Roles and Ownership Severity: Informational Acknowledged Status: , File(s) affected: IdleRebalancerV3_1.sol IdleTokenV3_1.sol Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. Description: owner Within, the owner can perform the following actions: IdleRebalancerV3_1 1. Can set the idle token exactly once viasetIdleToken 2. Can set the rebalance manager address any number of times viasetRebalanceManager 3. Can add any number of new tokens viasetNewToken 4. Another role enforced bymodifier, which allows the rebalance manager or idle token to set completely new token allocations, for exactly the same token addresses, that sum up to 100% (any number of times). onlyRebalancerAndIdleThe contract contains the following privileged actions: IdleTokenV3_1.sol 1. Modify thearray any number of times allAvailableTokens 2. Set the address of theany number of times iToken3. Set the governance token addressany number of times govTokens 4. Set the rebalancer address any number of times5. Set the fee taken from end users any number of times to any value lower or equal to 10%6. Set the maximum unlent asset percentage to any value lower than 100%7. Set the fee address any number of times.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. Recommendation: Updated documentation will be provided as in . Update: here QSP-21 User may not be able to redeem Idle tokens Severity: Medium Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol If the is lower than the for that user, then the method call on L911 in will throw an error and revert the transaction. Given that the function is only called in it will lead to users not being able to redeem Idle tokens as long as the current price is lower than the for that user. Description:_tokenPrice() userAvgPrices sub _getFee _getFee redeemIdleToken userAvgPrices If then set the to zero in . Recommendation: currPrice < userAvgPrices[msg.sender] elegibleGains _getFee QSP-22 Outdated could be used to influence the average APR govToken Severity: Low Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol The following condition in , on L358: only checks if the length of is greater than zero. However, it does not check if the length of the is greater than (the loop iterator) or if the is in the array. Due to the way in which the function works, it may be the case that but is not included in the array. This could have very severe consequences because any user is allowed to call , which changes the allocations based on the results obtained from calling . The function would return the wrong results, because it would take into consideration removed . Description:_getAvgAPR if (govTokens.length > 0 && currGov != address(0)) govTokens govTokens i currGov govTokens setGovTokens currGov != address(0) currGov govTokens openRebalance _getAvgAPR _getAvgAPR govTokens Exploit Scenario: 1. Owner decides to callin order to remove some which are no longer valid (e.g. the projects corresponding to those were hacked). Note that the method does not set the entries for those removed tokens to . setGovTokensgovTokens gotTokens setGovTokens protocolTokenToGov address(0) 2. Malicious party callsand allocates a large portion of funds to a token that has a corresponding that was removed in step 1. The malicious party knows that the price oracle will return a large APR for that , which will skew the result of . openRebalancegovToken govToken _getAvgAPR Set the entries for the removed tokens to inside the method. Recommendation: protocolTokenToGov address(0) setGovTokens QSP-23 Incorrect hardcoded addresses Severity: Low Risk Acknowledged Status: File(s) affected: IdleTokenV3_1.sol 1. The address of the Idle governance token is hardcoded to on L85. Description: 0x0001 1. The address of theis hardcoded to on L111. oracle 0x0001 2. The address of theis hardcoded to on L112. idleController 0x0001 3. The following address seems to be an EOA, not a smart contract L131:rebalancer = address(0xB3C8e5534F0063545CBbb7Ce86854Bf42dB8872B); 4. The address of theis hardcoded to on L130 and there is no setter function to change the address. iToken address(0) iToken Update the values and remove TODO comments. Clarify why needs to be a hardcoded constant, instead of being updated via a setter/initialization function similar to and . Also why not allow these addresses to be passed as input parameters to the function instead of hardcoding them? Recommendation:IDLE oracle idleController manualInitialize All addresses will be se once the governance is deployed. The rebalancer address is an EOA now because we removed the need for by moving the functionalities directly in . The address set is the rebalancer address that was previously had in (before was just a proxy basically). The address is hardcoded to correctly because we don't support Fulcrum anymore and we don't use that variable anymore. IDLE address should not be upgradable once set, while and addresses can change (The is an upgradable contract actually so the address will be the same; we removed the method too.) Those addresses were not passed in the because we are at the very limit of the max bytecode size so any addition change needs to get some 'space' somewhere else. We removed also the method, which will be reintroduced later. Update from the Idle Finance team:IdleRebalancerV3_1 IdleTokenV3_1 IdleRebalancerV3_1 iToken address(0) PriceOracle IdleController IdleController setIdleControllerAddress manualInitialize setMaxUnlentPerc QSP-24 Inconsistent array lengths breaks invariantsSeverity: Low Risk Fixed Status: File(s) affected: IdleTokenV3_1.sol The length of the array and the and arrays may diverge after calling , even if they were the same length after . This is because the allocations are not adjusted or checked to be of the same length with the or input arrays. This means that the owner can remove tokens from the array and the sum of all corresponding allocations would not be 100% after that call. Description:allAvailableTokens lastRebalancerAllocations lastAllocations setAllAvailableTokensAndWrappers manualInitialize protocolTokens wrappers allAvailableTokens Exploit Scenario: 1. Owner (accidentally) removes 1 or more tokens by callingsetAllAvailableTokensAndWrappers 2. Either the owner forgets to callOR they call , but are front-run by an end-user that calls or . setAllocations setAllocations openRebalance rebalance Either add a check inside which does not let the owner remove tokens OR add another input array to which indicates the new allocations. Optionally, a Boolean input parameter could also be added to which indicates that the allocation should stay the same, in which case a statement must check if the length of the input parameter is the same as the length of . Recommendation:setAllAvailableTokensAndWrappers setAllAvailableTokensAndWrappers setAllAvailableTokensAndWrappers require protocolTokens allAvailableTokens QSP-25 Initialization can be done multiple times Severity: Informational Acknowledged Status: File(s) affected: IdleTokenV3_1.sol The owner of the could call multiple times. This would reset several state variables. The semantics of the function name gives the impression that it should only be called once. Description:IdleTokenV3_1.sol manualInitialize Add a flag which is checked to be when the function starts executing and is set to inside . Recommendation: false manualInitialize true manualInitialize Once deployed, should be called only once and then a new implementation of should be deployed and set for all proxies (I added a file which is a copy of with removed and reintroduced). The new implementation should simply have removed in order to save bytecode size for future updates by the governance and it will also allow us to use the compiler optimization runs which are currently set to 1 so we can also save some gas on calls, we avoided to add a flag checking this because of what said above and because we tried to save bytecode size everywhere possibile (Current bytecode size with some dummy address set instead of placeholders is 24567.5 vs max of 24576, and with the method removed.) Update from the Idle Finance team:manualInitialize IdleTokenV3_1 idleToken IdleTokenGovernance.sol IdleTokenV3_1.sol manualInitialize setMaxUnlentPerc manualInitialize setMaxUnlentPerc QSP-26 Missing input check Severity: Informational Acknowledged Status: File(s) affected: IdleTokenV3_1.sol Description: 1. Thefunction does not check if the length of the 2nd, 3rd and 4th input arrays is the same. The -loop inside this function assumes the length of , and input arrays is the same. manualInitializefor _protocolTokens _wrappers _lastRebalancerAllocations 2. A comment on L105 indicates that thearray "should include IDLE". However, this is not verified inside the function. It could be verified by setting a binary flag to true inside the -statement on , and then checking this flag after the -loop using a statement. _newGovTokensif L124: if (newGov == IDLE) { continue; } for require Add statements accordingly. Recommendation: require Some checks have not been added mostly to save on bytecode size. Update from the Idle Finance team: QSP-27 Missing return value Severity: Informational Acknowledged Status: File(s) affected: IdleTokenV3_1.sol The function does not have an explicit return value for the cases where the -statement is not entered, i.e. the -condition is not . Description: getGovApr if if true Add an explicit statement after the -statement. Recommendation: return if Some statements have not been added mostly to save on bytecode size. Update from the Idle Finance team: return QSP-28 Privileged roles Severity: Informational Acknowledged Status: File(s) affected: IdleTokenV3_1.sol The owner of the contract has the right to change the following state variables at any time, they can even front-run end-users: Description: IdleTokenV3_1 1. can be set to any address including EOAs setAllAvailableTokensAndWrappers 2. can be set to any address including EOAs setGovTokens 3.can be set to any address including an EOA setRebalancer 4. upper bounded by 10% setFee5. upper bounded to 100% setMaxUnlentPerc 6. can be set to any address including an EOA setFeeAddress 7. can be set to any address including an EOA setOracleAddress 8. can be set to any address including an EOA setIdleControllerAddress 9. setIsRiskAdjusted10. this can also be done by the address setAllocations rebalancer These privileged operations and their potential consequences should be clearly communicated to (non-technical) end-users via publicly available documentation. Recommendation: The owner will be transferred to the governance right on deployment; one multisig wallet controlled by us will have the ability to pause the contract in case of emergency (withdrawals are not paused) but other than that the owner of the contract will be the from governance right in the deployment. You can see the migration scripts number 5 and the newly added number 6 for transferring ownership to governance. Public documentation will get revamped prior to the governance launch. Update from the Idle Finance team:Timelock.sol QSP-29 Incorrect average price computation Severity: Undetermined Fixed Status: File(s) affected: IdleTokenV3_1.sol The part of the input parameter of the function is subtracted twice from : on deposits on L889 and L892. See the following code snippet: Description:userNoFeeQtyFrom qty _updateUserFeeInfo totBalance 889: uint256 totBalance = balanceOf(usr).sub(userNoFeeQty[usr]); 890: // noFeeQty should not be counted here 891: // (avgPrice * oldBalance) + (currPrice * newQty)) / totBalance 892: userAvgPrices[usr] = userAvgPrices[usr].mul(totBalance.sub(qty)).add(price.mul(qty)).div(totBalance); This happens because was already added to , which is first subtracted on L889. This leads to an incorrect for that user. Additionally, the should not be multiplied by on L892, because on transfers, the amount that is actually transfered to is equal to . userNoFeeQtyFromuserNoFeeQty[usr] userAvgPrice price qty usr userNoFeeQtyFrom Update the average price computation to take into account that an amount of was already subtracted from on deposits. Recommendation: userNoFeeQtyFrom totBalance QSP-30 Uninitialized inherited contracts and state variables Severity: Undetermined Acknowledged Status: File(s) affected: IdleTokenV3_1.sol The method has been replaced with the method, which is significantly different: Description: initialize manualInitialize 1. There are several inherited contracts which were initialized in the, but are not initialized in the method. The following code snippet indicates the initialization of these contracts, which was removed: initializemanualyInitialize // Initialize inherited contracts ERC20Detailed.initialize(_name, _symbol, 18); Ownable.initialize(msg.sender); Pausable.initialize(msg.sender); ReentrancyGuard.initialize(); GST2ConsumerV2.initialize(); 1. Similarly, the following state variables:, , and , were initialized in the method, but are not initialized in the method. tokentokenDecimalscToken maxUnlentPerc initialize manualyInitialize Clarify if this is intentionally left uninitialized for some reason. If not, add the initialization of the aforementioned inherited contracts and state variables. Recommendation: is an upgradable contract and that method has already been called once, hence it can be removed now (for deployments of new we would need to reintroduce it). will initialize this new implementation (storage is still the old one so no need to update). Update from the Idle Finance team:IdleTokenV3_1 initialize IdleTokens manualInitialize QSP-31 Unclear functionality in _getFee Severity: Undetermined Fixed Status: File(s) affected: IdleTokenV3_1.sol * The functionality of : , is unclear. It seems that what we want to achieve here is more like when and when . Description:L907 userNoFeeQty[msg.sender] = noFees ? noFeeQty.sub(amount) : 0;userNoFeeQty[msg.sender] = balanceOf(msg.sender).sub(_amount); fee == 0 userNoFeeQty[msg.sender] = noFeeQty.sub(amount) noFeeQty >= amount Clarify if the functionality is as-intended. Recommendation: QSP-32 Wrong comparison between lengths Severity: Medium Risk Mitigated Status: File(s) affected: IdleTokenGovernance.sol On L148 in we can see the following statement: From the other occurrences of we believe that it should indicate that the 2 terms being compared are not equal, which is different from what the Boolean expression in that Description:IdleTokenGovernance.sol require require(_newGovTokensEqualLen.length >= protocolTokens.length, '!EQ'); !EQ statement is comparing, that is the comparison is actually checking if the length of theis higher-or-equal to the length of . require _newGovTokensEqualLen protocolTokens Recommendation: 1. Change the condition on L148 fromto . >===2. It would additionally make sense to check that the length of theis higher-or-equal to the length of , which is currently not being checked. _newGovTokensEqualLen_newGovTokens The maximum length is because IDLE is not associated with any protocol token. Therefore, the statement could be restricted to . Update:_newGovTokensEqualLen protocolTokens.length + 1 require require(_newGovTokensEqualLen.length == protocolTokens.length + 1, '!EQ'); QSP-33 The is not settable flashLoanFee Severity: Low Risk Fixed Status: File(s) affected: IdleTokenGovernance.sol The cannot be changed by a function call after the contract is deployed. The only way to change it is to upgrade/redeploy the contract. Description: flashLoanFee We recommend adding a setter method such that the governance account could set it after a community vote. Recommendation: QSP-34 Inconsistent array lengths breaks invariant Severity: Low Risk Mitigated Status: File(s) affected: IdleTokenGovernance.sol this issue is essentially the same as QSP-24 from a previous audit; the fix appears to have been reverted. Description: Note: The length of the array and the and arrays may diverge after calling . This is because the allocations are not adjusted or checked to be of the same length with the or input arrays of the function. This means that the owner can effectively remove tokens from the array and the sum of all corresponding allocations would not be 100% by calling . allAvailableTokenslastRebalancerAllocations lastAllocations setAllAvailableTokensAndWrappers() protocolTokens wrappers setAllAvailableTokensAndWrappers() allAvailableTokens setAllAvailableTokensAndWrappers() Exploit Scenario: 1. Owner (accidentally) removes 1 or more tokens by callingsetAllAvailableTokensAndWrappers() 2. Either the owner forgets to callOR they call , but are front-run by an end-user that calls or any other function which uses the array. setAllocationssetAllocations redeemInterestBearingTokens allAvailableTokens This will lead to incorrect amounts being redeemed, loaned, etc. Either add a check inside which does not let the owner remove tokens OR add another input array to which indicates the new allocations. Optionally, a Boolean input parameter could also be added to which indicates that the allocation should stay the same, in which case a statement must check if the length of the input parameter is the same as the length of . Recommendation:setAllAvailableTokensAndWrappers setAllAvailableTokensAndWrappers setAllAvailableTokensAndWrappers require protocolTokens allAvailableTokens From the Idle team -- we won't be changing the , and instead a specific process should be followed when a protocol needs to be removed (i.e. set allocation for that protocol to 0, ensure that funds have been fully redeemed from that protocol and then do the proposal). method has been removed. Update:setAllAvailableTokensAndWrappers openRebalance QSP-35 Flashloans may decrease funds if underlying protocols have redemption fees Severity: Informational Acknowledged Status: File(s) affected: IdleTokenGovernance.sol The function can be used to force triggering the rebalance process and move funds in and out different underlying protocols. If any of the underlying lending protocols have a redemption fee, an attacker who seeks to damage IdleFinance can achieve this by rapidly performing large value flashloans that cause IdleFinance to redeem and mint the underlying protocol’s tokens and end up losing money. Description:flashLoan Ensure that the fee collected by the flash loan is larger than the sum of the redemption fee of the underlying protocols. Recommendation: From the Idle team: I think that this would only be true if they charge a fee at the redeem (not counted in their price), but even in that case we could fix it in the strategy itself probably. Update: QSP-36 Unchecked function arguments Severity: Informational Acknowledged Status: File(s) affected: IdleTokenGovernance.sol The function should ensure that is non-zero. Description: _init _tokenHelper Add a statement ensuring that . Recommendation: require _tokenHelper != address(0) This is done to save on bytcodesize. Update: QSP-37 Flashloan could be used as a tool to manipulate liquidities of the underlying lending protocols Severity: Informational Acknowledged Status: File(s) affected: IdleTokenGovernance.sol Thecan be used to force triggering the rebalance process and moving funds in and out different underlying protocols. A related security issue is described in . Description: flashLoan EIP-3156 While the underlying protocol's are expected to protect against flash loans themselves, this avenue of attack should be considered when adding new protocols to the Idle system. Recommendation:The Idle team noted that it is not clear how this could affect the protocol itself given that it's already possible to do this with other protocols. Update: However, we still stress that caution should be used when adding underlying protocols. One notable example of a related attack is . the yearn attack with the 3pool imbalance QSP-38 Uninitialized state variables Severity: Undetermined Acknowledged Status: File(s) affected: IdleTokenGovernance.sol Several important state variables: , , and , are not initialized anywhere. Description: token tokenDecimalsisRiskAdjusted Ensure that these variables are properly initialized. Recommendation: Those variables are only set once though the contract. The contract is then upgraded to upon the first deploy for each new token. Update: IdleTokenV3_1 IdleTokenGovernance QSP-39 Owner can front-run flash loaners to change loan fee Severity: Informational Mitigated Status: File(s) affected: IdleTokenGovernance.sol The owner of the contract has the privilege of front running any end-user who calls by calling and increasing the flash loan fee. Coupled with the fact that the can be set up to 100% inside the function, this could be detrimental to the caller if sufficient funds are available in the caller's balance. Description:IdleTokenGovernance flashLoan() setFlashLoanFee() flashLoanFee setFlashLoanFee() Recommendation: 1. We recommend that the caller of thefunction sends the expected flash loan fee as part of the parameter of that function. That user should check the expected flash loan fee inside the function and should revert if it is different than expected. flashLoan()_params onFlashLoan() 2. The maximum value of theshould be bounded to a reasonable amount, in a similar way to how the value of the is bounded inside of the function. flashLoanFeefee setFee() The owner is the governance which can act only through the . Any method takes at least 5 days so it's should not be an issue. Update: timelock onlyOwner Automated Analyses Mythril Mythril reported no issues. Slither Slither warns of several potential reentrancy issues, however as the associated external calls were to trusted contracts (either Idle contracts or underlying protocols), we classified these as false positives. •Slither detects that there are "divided-before-multiplies" operations in the following functions. Re-ordering these operations may improve precision. •IdleTokenV3_1.sol getAvgAPR() avgApr = avgApr.add(ILendingProtocol(protocolWrappers[allAvailableTokens[i]]).getAPR().mul(amounts[i].mul(10 ** 18).div(total)).div(10 ** 18)) ••: _redeemGovTokens() share = usrBal.mul(delta).div(10 ** 18) •feeDue = share.mul(fee).div(100000) ••As of commit : e09d4f5In , several important state variables: , , and , are not initialized anywhere. • IdleTokenGovernance.soltoken tokenDecimalsisRiskAdjusted Adherence to Specification The code adheres to the specification provided, as well as the inline documentation. Code Documentation The code is generally well-documented. We suggest several improvements related to magic constants above in QSP-6. Additionally, we noted the following: In , on L42 the comment "// Idle rebalancer current implementation address" does not relate to the code below. • Update: fixed.IdleTokenV3.sol In , comments describing and should be added. • Update: fixed.IdleTokenV3.sol userAvgPrices userNoFeeQty In , we recommend documenting that the Aave-Dai price will always be one-to-one (as per L133). • Update: fixed.IdleAave.sol There are several spelling errors throughout: "possibile", "supplyied", "aum" (should be "sum"), "crete", "DyDc". • Update: fixed.As of commitwe noted the following: 35d61aeThe comment of the function in contains the following text: “max settable is MAX_FEE constant”. However the constant is not defined. •Update: fixed.setFee IdleTokenV3_1 MAX_FEE The comment of the function in contains the following text, which seems to be wrongly copied from another function’s code comment: “max settable is MAX_FEE constant”. •Update: fixed.setMaxUnlentPerc IdleTokenV3_1 In the comment block of , it is not clear what is meant by "This method can be delayed". • Update: fixed.IdleTokenV3_1.setAllAvailableTokensAndWrappers In , the typo "shar" should be "share". • Update: fixed.IdleTokenV3_1.sol In , comments should be added to the functions indicating why the government tokens get redeemed for the from- address but not the to-address. •Update: fixed.IdleTokenV3_1.sol transfer* In , the comment "This method triggers a rebalance of the pools if needed" no longer applies to and . •Update: fixed.IdleTokenV3_1.sol mintIdleToken redeemIdleToken In in the function , the comment should instead say . •Update: fixed.IdleTokenV3_1.sol _updateUserGovIdxTransfer() // user _to should have -> shareTo + (sharePerTokenFrom * amount / 1e18) = (balanceTo + amount) * (govTokenIdx - userIdx) / 1e18 user _from ... As of commit , we noted the following: 50da42b9 * The function declared on L104 of does not have comments to describe its input parameters and return value. The comment that it has does not seem to reflect the actual implementation because the IDLE token address is a constant. •Update: fixed.manualInitialize IdleTokenV3_1.sol * The function in is missing the description of its 2nd parameter. • Update: fixed.setGovTokens IdleTokenV3_1.sol * The function in is missing the description of its 3rd parameter . • Update: fixed._getFee IdleTokenV3_1.sol currPrice * Typo on L628 in : "give" -> "gives" • Update: fixed.IdleTokenV3_1.sol As of commit we noted the following: e09d4f5L114 in : "The fee flash borrowed" -> "The flash loan fee" • Update: fixed.IdleTokenGovernance.sol The comments at the beginning of the and files are identical to those at the beginning of the file. These should be adjusted for token governance: •Update: fixed.IdleTokenGovernance.sol IdleTokenHelper.sol IdleTokenV3_1.sol /** * @title: Idle Token (V3) main contract * @summary: ERC20 that holds pooled user funds together * Each token rapresent a share of the underlying pools * and with each token user have the right to redeem a portion of these pools * @author: Idle Labs Inc., idle.finance */ In , "redeemd" is misspelled. • Update: fixed.IdleTokenGovernance.flashLoan In on L928: should be documented, particularly since the first parameter is now unused in . •Update: fixed._redeemGovTokensFromProtocol IdleController(idleController).claimIdle(holders, holders); claimIdle Adherence to Best Practices The code does not fully adhere to best practices. In particular: There is commented out code on L78-99 of that should be removed if not needed. • Update: fixed.iERC20Fulcrum.sol Although the user is intended to interact with the dApp through an (specifically through ), the user could instead try to directly interact with or , first transferring DAI to the contract and then attempting to . If that were the case, since the DAI transfer and are not autonomous, a different user could scoop the minted tokens by invoking first. As an added precaution to prevent this scenario, it may be beneficial to restrict calls to in and to only be callable from the contract. •Update: fixed.IdleToken mintIdleToken() IdleCompound IdleFulcrum mint() mint() mint() mint() IdleCompound IdleFulcrum IdleToken On L91 of : "// q = a1 * (s1 / (s1 + x1)) * (b1 / (s1 + x)1) * o1 / k1", the "x)1" is a typo. • Update: fixed.IdleFulcrum In , the address parameters should be checked to be non-zero with require-statements. • Update: fixed.IdleFactory.newIdleToken() In , there should be a check that . • Update: fixed.IdlePriceCalculator.tokenPrice() currentTokensUsed.length == protocolWrappersAddresses.length The conditional on L456 of could simply be the else-branch of the previous if-statement. • Update: fixed.IdleToken.sol On L219 of , it is not clear what the comment "// We should save the amount one has deposited to calc interests" is referring. • Update: fixed.IdleToken.sol On L95 of the constants and are used instead of the passed in parameters and . • Update: fixed.IdleCompound.sol 10**18 100 params[0] params[8] In , , and , the constructors should check that the passed in addresses are non-zero. • Update: fixed.IdleCompound IdleFulcrum IdleRebalancer In , the comments on L110 and L128 do not appear correct. • Update: fixed.IdleRebalancer.sol Functions such as and should check for non-zero arguments. Further, all the functions should ensure that the parameter is non-zero. •Update: fixed.IdleToken.setProtocolWrapper() IdleFactory.setTokenOwnershipAndPauser() setIdleToken() _idleToken In , since should be equal to , you may as well remove that argument and use . and the parameter are used to ensure that each allocation submitted by an off-chain bot is for the correct lending protocol. •IdleRebalancerV3.setAllocations()_addresses lastAmountsAddresses lastAmountsAddresses Update: setAllocations_addresses In , in why not just enforce length 1 for the input array? The parameter is an array in adherence with the interface. •IdleDyDx.solnextSupplyRateWithParams() Update: ILendingProtocol L540 of should be instead of . The reason is that once is true, there’s no need to rebalance even when the balance is not larger than 0. •Update: fixed.IdleTokenV3.sol if (_skipWholeRebalance || areAllocationsEqual) if (_skipWholeRebalance || (areAllocationsEqual && balance > 0)) areAllocationsEqual In , since is a known token, the address could be declared as a constant instead of a constructor parameter. this approach maintains uniformity amongst the wrapper constructors. •IdleDSR.solCHAI Update: As of commit we noted the following: 35d61aeIn the constructor ofon L35, there is a branch instruction that will be true only for the first iteration. Executing this branch instruction in each iteration will waste gas. Recommendation: perform the assignment for the first entry in the array outside of the loop and start the loop with : •Update: fixed.IdleRebalancerV3_1 i = 1 lastAmounts[0] = 100000; lastAmountsAddresses[0] = _protocolTokens[0]; for(uint256 i = 1; i < _protocolTokens.length; i++) { The variable inside the function from should be explicitly initialized to on L98. • totalsetAllocations IdleRebalancerV3_1 0 Replace inline constants with named constants: •Update: several constants have been fixed; others have not been updated due to upgradeability of storage concerns.The inline constant is used 2 times in . Update: fixed. 10000 IdleRebalancerV3_1 • The inline constant is used 1 time in . 10000 IdleTokenV3_1 • * The inline constant is used 8 times in . Update: fixed. 100000 IdleTokenV3_1 • The inline constant is used 9 times in . Update: fixed. 10**18 IdleTokenV3_1 • In , the expression could change to be , which would make the following if-statement unnecessary: . •Update: fixed.IdleTokenV3_1.sol (totalRedeemd < maxUnlentBalance) <= if (totalRedeemd > 1) { As of commit , we noted the following: 50da42b9 * Resolve and remove all TODO comments, e.g. such as those on L85, L111 and L112 in . • Update: fixed.IdleTokenV3_1.sol * Replace the following magic numbers with named constants: • Update: fixed.* appears several times in Update: fixed. 100000 IdleTokenV3_1.sol • As of commit we noted the following: e09d4f5Named constants should have a name which provide semantic meaning and not simply indicates the value of the constant. For example, the constant defined in multiple files including and , should be renamed to something like: , which conveys more semantic meaning. for the ONE_18 we prefer to keep it as is, but we will keep in mind the general advice. •ONE_18 IdleTokenGovernance.sol IdleTokenHelper.sol IDLE_TOKEN_DECIMALS Update from the Idle team: Magic numbers should be replaced with named constants. For example, on L986 in . the 10**23 is well documented and we didn't wanted to add other constant/variables. •10**23 IdleTokenGovernance.sol Update from the Idle team: Avoid code clones. Favor code reuse. For example, on L704 in : , the same computation as the one performed by the function is used. We recommend calling the function on L704 instead. This can be done by making the function instead of . •Update: fixed.IdleTokenGovernance.sol uint256 _flashFee = _amount.mul(flashLoanFee).div(FULL_ALLOC); flashFee() flashFee() public external Provide descriptive error messages in statements. These serve a double role: code documentation and debugging helpers. All statements in contain cryptic error messages such as: "0", "EXEC", "DONE", "LEN", "!EQ", which also do not indicate which function the error has occurred in. We recommend changing these error messages or providing user documentation to map such error messages/codes to a human readable description. for the require messages we kept them short to save a lot on bytecodesize; those should still be enough to debug txs, but the idea to have error code instead could be implemented in the future. •require require IdleTokenGovernance.sol Update from the Idle team: Commented code should be removed. For example, L983-984 in . • Update: fixed.IdleTokenGovernance.sol In , consider changing the into for better maintenance. • Update: fixed.IdleTokenGovernance.setFee 10000 FULL_ALLOC/10 should inherit the interface. we avoided to inherit from it just to be 110% sure to not break anything given that all contracts are upgradable (even though no storage is touched). •IdleTokenGovernance.solIERC3156FlashLender Update from the Idle team: In on L consider moving this entire statement into the body of to avoid unexpected results from happening. •Update: fixed.IdleTokenGovernance.sol L877 if-else if (supply > 0) Consider adding reentrancy protection to the function. • Update: fixed.IdleTokenGovernance.sol.flashLoan Test Results Test Suite Results **Update as of commit : some tests for previously audited contracts fail due to timeouts which influenced coverage and test results. e09d4f5Contract: IdleBatchConverter ✓ constructor set rebalanceManager addr (98ms) ✓ cannot withdraw before first migration (841ms) ✓ single user migration (576ms) ✓ multiple user migration, single batch (881ms) ✓ multiple user migration, multiple batch (2075ms) Contract: IdleTokenV3_1 ✓ initialize set a name (39ms) ✓ initialize set a symbol (145ms) ✓ initialize set a decimals (93ms) ✓ initialize set a token (DAI) address (276ms) ✓ initialize set a rebalancer address (136ms) ✓ initialize set owner ✓ initialize set pauser (217ms) ✓ manualInitialize set stuff (1098ms) 1) _init set stuff Events emitted during test: --------------------------- IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xA782e72F1D3befBd4DDC04F487ef10ab40340769 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x6043A7347F46EaAcDe0ED7C98B53584823D78A90 (type: address),value: 10000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xe7E39F27101a763cB55c0Fb8cf6844E8a07761f9 (type: address), value: 10000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x6DdFdEdB38822099547ef7E056Fb40d4d11f3C88 (type: address), value: 100000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x80c5d818C9a43e932dD94A0Ee161A3ebFA823be9 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x4a1CD0CF2819eF3f2B7f05BF5d02B858b9384165 (type: address), spender: <indexed> 0x6DdFdEdB38822099547ef7E056Fb40d4d11f3C88 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x078759ffb75b3bCEBfd6bF517bd896b1AF2FaaaC (type: address), spender: <indexed> 0x80c5d818C9a43e932dD94A0Ee161A3ebFA823be9 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xE96C48EA7F75D9957AdDAc74c707276f26eEE433 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 100000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), to: <indexed> 0x160eBf7F40d9889D834047f55e9BF5fC51e49EDF (type: address), value: 10000000000000000000000 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x035DE74e37A8f86c0C75dd6C8FF6BfBfB3c6888C (type: address), spender: <indexed> 0x077BD1BE91206a013CcC641C7983CaA1FBad0b28 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x22B0cD56859db4E9160b860fbD2b94a5C1B61153 (type: address), spender: <indexed> 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x22B0cD56859db4E9160b860fbD2b94a5C1B61153 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x22B0cD56859db4E9160b860fbD2b94a5C1B61153 (type: address), spender: <indexed> 0xA4dfa8e902CdEDcB6C1f3D3E79AFADaBBA60F839 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x2F6e1CD70fBBfD27cD512CFCc3d980a7Af4923a3 (type: address), spender: <indexed> 0x22B0cD56859db4E9160b860fbD2b94a5C1B61153 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x2F6e1CD70fBBfD27cD512CFCc3d980a7Af4923a3 (type: address), spender: <indexed> 0x22B0cD56859db4E9160b860fbD2b94a5C1B61153 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) Ambiguous event, possible interpretations: * IdleTokenV3_1Mock.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) * IdleTokenV3_1Mock.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) PauserRole.PauserAdded( account: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) PauserRole.PauserAdded( account: <indexed> 0xaDa343Cb6820F4f5001749892f6CAA9920129F2A (type: address) ) --------------------------- ✓ setAllAvailableTokensAndWrappers (1301ms) ✓ allows onlyOwner to setRebalancer (489ms) ✓ allows onlyOwner to setOracleAddress (465ms) ✓ allows onlyOwner to setFeeAddress (254ms)✓ allows onlyOwner to setFee (422ms) ✓ allows onlyOwner to setMaxUnlentPerc (374ms) ✓ calculates current tokenPrice when IdleToken supply is 0 (77ms) ✓ calculates current tokenPrice when funds are all in one (4578ms) ✓ calculates current tokenPrice when funds are all in one pool (5551ms) ✓ calculates current tokenPrice when funds are in different pools (8482ms) ✓ get all APRs from every protocol (538ms) ✓ get current avg apr of idle (with no COMP apr) (3339ms) ✓ get current avg apr of idle with COMP (1999ms) ✓ mints idle tokens (1757ms) ✓ cannot mints idle tokens when paused (710ms) ✓ does not redeem if idleToken total supply is 0 (168ms) ✓ redeems idle tokens (4349ms) ✓ redeems idle tokens using unlent pool (4193ms) ✓ redeemInterestBearingTokens (4897ms) ✓ cannot rebalance when paused (295ms) ✓ rebalances when _newAmount > 0 and only one protocol is used (1933ms) ✓ rebalances when _newAmount > 0 and only one protocol is used and no unlent pool (2627ms) ✓ rebalances and multiple protocols are used (5714ms) ✓ _amountsFromAllocations (public version) ✓ _mintWithAmounts (public version) (2138ms) ✓ _redeemAllNeeded (public version) when liquidity is available (3905ms) ✓ _redeemAllNeeded (public version) when liquidity is available and with reallocation of everything (5673ms) ✓ _redeemAllNeeded (public version) with low liquidity available (4669ms) ✓ rebalance when liquidity is availabler (7191ms) ✓ rebalance when liquidity is not available (6737ms) ✓ rebalance when liquidity is not available and no unlent perc (6399ms) ✓ rebalance when underlying tokens are in contract (ie after mint) and rebalance and idle allocations are equal (7093ms) ✓ rebalance with no new amount and allocations are equal (4505ms) ✓ rebalance when prev rebalance was not able to redeem all liquidity because a protocol has low liquidity (14144ms) ✓ calculates fee correctly when minting / redeeming and no unlent (7868ms) ✓ calculates fee correctly when minting / redeeming with unlent (9121ms) ✓ calculates fee correctly when minting multiple times and redeeming (10786ms) ✓ calculates fee correctly when minting multiple times and redeeming with different fees (14902ms) ✓ calculates fee correctly when redeeming a transferred idleToken amount (10250ms) ✓ calculates fee correctly when redeeming a transferred idleToken amount with different fees (12117ms) ✓ calculates fee correctly when redeeming a transferred idleToken amount after having previosly deposited (12842ms) ✓ calculates fee correctly when using transferFrom (7928ms) ✓ charges fee only to some part to whom previously deposited when there was not fee and deposited also when there was a fee (5093ms) ✓ charges fee only to some part to whom previously deposited when there was fee and deposited also when there was no fee (9842ms) ✓ redeemGovTokens complex test (6930ms) ✓ redeemGovTokens (6555ms) ✓ redeemGovTokens test 2 (3999ms) ✓ getGovTokensAmounts (4202ms) ✓ redeemGovTokens with fee (6699ms) ✓ redeemGovTokens on transfer to new user (5436ms) ✓ redeemGovTokens on transfer to existing user (5705ms) ✓ transfer correctly updates userAvgPrice when transferring an amount > of no fee qty (7263ms) ✓ setAllocations contract fix - setAllocations should not fail if wrappers count increased (935ms) ✓ setAllocations contract fix - setAllocations should not fail if wrappers count decreased (736ms) ✓ getGovTokens (57ms) ✓ getAllAvailableTokens (63ms) ✓ getProtocolTokenToGov (41ms) ✓ getAllocations (1858ms) 2) flashLoanFee Events emitted during test: --------------------------- IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x494CA97b571716177b91B1dF6e7b2Fd1d459B7A6 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x2569C597b5a36c3441D8FD82f5CB14128f70544e (type: address), value: 10000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x93C1837740373534cD6113d06cA032Ed735937DF (type: address), value: 10000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x5f74946317FB10f3899Ce0261a105C99068C0903 (type: address), value: 100000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xB53D5e67Aa9134f31E1D5dc78D22751b469e5172 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x3d743E270a1eE8332d7Ef63F63E060DEBDe43Dd4 (type: address), spender: <indexed> 0x5f74946317FB10f3899Ce0261a105C99068C0903 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x4d3853a48744cFDE8575347E1A31e8DB90BC046D (type: address), spender: <indexed> 0xB53D5e67Aa9134f31E1D5dc78D22751b469e5172 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x71DC02d2E39b4Dd7A7B825481002f6748A6644C0 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 100000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), to: <indexed> 0xb45ACDe13BAf56d71f54a6039F0739f06b6ac781 (type: address), value: 10000000000000000000000 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0xD5AAb05CA46F0adF19f648F0Af2cd69884Ad3700 (type: address),spender: <indexed> 0xC8CFfacf1958b163F024506B77eb50753f74129b (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x541F7171e3Ae58537dE9A1B7dDE2dA23AeAA6d25 (type: address), spender: <indexed> 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x541F7171e3Ae58537dE9A1B7dDE2dA23AeAA6d25 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x541F7171e3Ae58537dE9A1B7dDE2dA23AeAA6d25 (type: address), spender: <indexed> 0x6056248a0b3b469A16E285b69FE0D29d1D117ED4 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x440817F68675Af56c4A5460400CeAF421156a72a (type: address), spender: <indexed> 0x541F7171e3Ae58537dE9A1B7dDE2dA23AeAA6d25 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x440817F68675Af56c4A5460400CeAF421156a72a (type: address), spender: <indexed> 0x541F7171e3Ae58537dE9A1B7dDE2dA23AeAA6d25 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) Ambiguous event, possible interpretations: * IdleTokenV3_1Mock.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) * IdleTokenV3_1Mock.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) PauserRole.PauserAdded( account: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) PauserRole.PauserAdded( account: <indexed> 0xaDa343Cb6820F4f5001749892f6CAA9920129F2A (type: address) ) --------------------------- ✓ maxFlashLoan (5315ms) ✓ tokenPriceWithFee (8712ms) ✓ redeemIdleTokenSkipGov (11105ms) 3) executes a flash loan Events emitted during test: --------------------------- IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xe78652486a6cADC80f7ccefAFCC21D1C6215BF7e (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x0d793973d0c6F0d2e4FC11cB303d7A4991757c5B (type: address), value: 10000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xE82cD7b563201678755B5f9E0BdC1d35D073Ec63 (type: address), value: 10000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xAb6261B4f9E7997f41F5965001624b8090F0A57f (type: address), value: 100000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xBf15a702F770ea6aef3166633616Bb9B734E776a (type: address), value: 10000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 10000000000000000000000 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0xACc5f58366048b4107335cAb9987Cb9D3F5c703C (type: address), spender: <indexed> 0xAb6261B4f9E7997f41F5965001624b8090F0A57f (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x2811B081ecD440De1d623990b31A140c1d385927 (type: address), spender: <indexed> 0xBf15a702F770ea6aef3166633616Bb9B734E776a (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xF0169AE7f46d8bbC705E13f82Fcc808673351206 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer(from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 100000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), to: <indexed> 0x6A306c1bECDAD43da6e51AA7B4fB6373724d1c96 (type: address), value: 10000000000000000000000 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x84feFc456430E063EF164ae02e4f3E7B9B82F94e (type: address), spender: <indexed> 0xCE08F45dAf36F98A0e33a61dB95A5b6F8F2D1Ce5 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x1CaCa9F10B5dC472b7b14d28904eFA29Bb117C35 (type: address), spender: <indexed> 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x1CaCa9F10B5dC472b7b14d28904eFA29Bb117C35 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), value: 1000000000000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x1CaCa9F10B5dC472b7b14d28904eFA29Bb117C35 (type: address), spender: <indexed> 0x6707b74355b35D990CE0c3D39fB299D6c4e19943 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) IERC20.Approval( owner: <indexed> 0x097628F6bD655091ae13f99b4Af0DC3909A2787c (type: address), spender: <indexed> 0x1CaCa9F10B5dC472b7b14d28904eFA29Bb117C35 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x097628F6bD655091ae13f99b4Af0DC3909A2787c (type: address), spender: <indexed> 0x1CaCa9F10B5dC472b7b14d28904eFA29Bb117C35 (type: address), value: 115792089237316195423570985008687907853269984665640564039457584007913129639935 (type: uint256) ) Ownable.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) Ambiguous event, possible interpretations: * IdleTokenV3_1Mock.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) * IdleTokenV3_1Mock.OwnershipTransferred( previousOwner: <indexed> 0x0000000000000000000000000000000000000000 (type: address), newOwner: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) PauserRole.PauserAdded( account: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address) ) PauserRole.PauserAdded( account: <indexed> 0xaDa343Cb6820F4f5001749892f6CAA9920129F2A (type: address) ) IERC20.Transfer( from: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), to: <indexed> 0x7b94aC3E3AC4a2f5347E3e60616D9F1e51a1a25a (type: address), value: 1000000000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x7b94aC3E3AC4a2f5347E3e60616D9F1e51a1a25a (type: address), spender: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), value: 1000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x7b94aC3E3AC4a2f5347E3e60616D9F1e51a1a25a (type: address), to: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), value: 1000000000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x7b94aC3E3AC4a2f5347E3e60616D9F1e51a1a25a (type: address), spender: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), value: 0 (type: uint256) ) Ambiguous event, possible interpretations: * IdleTokenV3_1Mock.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x7b94aC3E3AC4a2f5347E3e60616D9F1e51a1a25a (type: address), value: 1000000000000000000000 (type: uint256) ) * IdleTokenV3_1Mock.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0x7b94aC3E3AC4a2f5347E3e60616D9F1e51a1a25a (type: address), value: 1000000000000000000000 (type: uint256) ) IdleTokenV3_1NoConst.Referral( _amount: 1000000000000000000000 (type: uint256), _ref: 0x0000000000000000000000000000000000000001 (type: address) ) IERC20.Transfer( from: <indexed> 0x47fCbA4f604F60087f046627E9323768b4339046 (type: address), to: <indexed> 0x4F4b696dd715829E4d9BF7A565Cb2D1AFe152F55 (type: address), value: 2000000000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), to: <indexed> 0x4F4b696dd715829E4d9BF7A565Cb2D1AFe152F55 (type: address), value: 1000000000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x4F4b696dd715829E4d9BF7A565Cb2D1AFe152F55 (type: address), spender: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), value: 1000800000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x4F4b696dd715829E4d9BF7A565Cb2D1AFe152F55 (type: address), to: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), value: 1000800000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0x4F4b696dd715829E4d9BF7A565Cb2D1AFe152F55 (type: address), spender: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), value: 0 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), to: <indexed> 0xACc5f58366048b4107335cAb9987Cb9D3F5c703C (type: address), value: 990792000000000000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0xACc5f58366048b4107335cAb9987Cb9D3F5c703C (type: address), to: <indexed> 0xAb6261B4f9E7997f41F5965001624b8090F0A57f (type: address),value: 990792000000000000000 (type: uint256) ) IERC20.Approval( owner: <indexed> 0xACc5f58366048b4107335cAb9987Cb9D3F5c703C (type: address), spender: <indexed> 0xAb6261B4f9E7997f41F5965001624b8090F0A57f (type: address), value: 115792089237316195423570985008687907853269984665640564038466792007913129639935 (type: uint256) ) IERC20.Transfer( from: <indexed> 0x0000000000000000000000000000000000000000 (type: address), to: <indexed> 0xACc5f58366048b4107335cAb9987Cb9D3F5c703C (type: address), value: 4953960000000 (type: uint256) ) IERC20.Transfer( from: <indexed> 0xACc5f58366048b4107335cAb9987Cb9D3F5c703C (type: address), to: <indexed> 0x348fD6DBc7105923Bc085021c4BAecB5E226A542 (type: address), value: 4953960000000 (type: uint256) ) IdleTokenV3_1NoConst.FlashLoan( target: <indexed> 0x4F4b696dd715829E4d9BF7A565Cb2D1AFe152F55 (type: address), initiator: <indexed> 0x7b94aC3E3AC4a2f5347E3e60616D9F1e51a1a25a (type: address), amount: 1000000000000000000000 (type: uint256), premium: 800000000000000000 (type: uint256) ) --------------------------- ✓ sets gov tokens when _newGovTokens and _protocolTokens lengths are different (645ms) Contract: MinimalInitializableProxyFactory ✓ deploys a minimal proxy and initializes it (626ms) Contract: IdleAave ✓ constructor set a token address (256ms) ✓ constructor set an underlying address (479ms) ✓ allows onlyOwner to setIdleToken (899ms) ✓ returns next supply rate given amount (178ms) ✓ returns next supply rate given params (counting fee) (557ms) ✓ getPriceInToken returns aToken price (67ms) ✓ getAPR returns current yearly rate (counting fee) (83ms) ✓ mint returns 0 if no tokens are presenti in this contract (80ms) ✓ mint creates aTokens and it sends them to msg.sender (1422ms) ✓ redeem creates aTokens and it sends them to msg.sender (1503ms) Contract: IdleAaveV2 ✓ constructor set a token address (457ms) ✓ constructor set an underlying address (365ms) ✓ returns next supply rate given amount (1185ms) ✓ getPriceInToken returns aToken price (136ms) ✓ getAPR returns current yearly rate (counting fee) (326ms) ✓ mint returns 0 if no tokens are present in this contract (581ms) ✓ mint creates aTokens and it sends them to msg.sender (2369ms) ✓ redeem creates aTokens and it sends them to msg.sender (3151ms) Contract: IdleCompound ✓ constructor set a token address ✓ constructor set an underlying address ✓ allows onlyOwner to setIdleToken (877ms) ✓ allows onlyOwner to setBlocksPerYear (939ms) ✓ returns next supply rate given amount (92ms) ✓ returns next supply rate given params (counting fee) (399ms) ✓ getPriceInToken returns cToken price (1330ms) ✓ getAPR returns current yearly rate (counting fee) (991ms) ✓ mint returns 0 if no tokens are presenti in this contract (39ms) ✓ mint creates cTokens and it sends them to msg.sender (3213ms) ✓ redeem creates cTokens and it sends them to msg.sender (1990ms) Contract: IdleCompoundETH ✓ constructor set a token address ✓ constructor set an underlying address (361ms) ✓ constructor set an underlying address (940ms) ✓ allows onlyOwner to setBlocksPerYear (2781ms) ✓ returns next supply rate given amount (3413ms) ✓ returns next supply rate given params (counting fee) (942ms) ✓ getPriceInToken returns cToken price (1372ms) ✓ getAPR returns current yearly rate (counting fee) (1650ms) ✓ mint returns 0 if no tokens are present in this contract (51ms) ✓ mint creates cTokens and it sends them to msg.sender (2947ms) ✓ redeem creates cTokens and it sends them to msg.sender (1912ms) Contract: IdleCompoundV2 ✓ constructor set a token address ✓ constructor set an underlying address (913ms) ✓ allows onlyOwner to setIdleToken (1161ms) ✓ allows onlyOwner to setBlocksPerYear (3980ms) ✓ returns next supply rate given amount (5458ms) ✓ returns next supply rate given params (counting fee) (3674ms) ✓ getPriceInToken returns cToken price (6283ms) ✓ getAPR returns current yearly rate (counting fee) (8676ms) ✓ mint returns 0 if no tokens are presenti in this contract (4051ms) ✓ mint creates cTokens and it sends them to msg.sender (12334ms) ✓ redeem creates cTokens and it sends them to msg.sender (2412ms) Contract: IdleDSR ✓ constructor set a token address ✓ constructor set an underlying address (941ms) ✓ constructor set CHAI contract infinite allowance to spend our DAI (1488ms) ✓ constructor set an secondsInAYear (1485ms) ✓ allows onlyOwner to setIdleToken (9626ms) ✓ returns next supply rate given 0 amount (6733ms) 4) "before each" hook for "returns next supply rate given amount != 0" Contract: IdleDyDx 5) "before each" hook for "constructor set a token address" Contract: IdleFulcrum ✓ constructor set a token address (10385ms) ✓ constructor set a underlying address (2725ms) ✓ allows onlyOwner to setIdleToken (2652ms) ✓ returns next supply rate given amount (656ms) ✓ returns next supply rate given params (501ms) ✓ getPriceInToken returns iToken price (941ms) ✓ getAPR returns current yearly rate (counting fee ie spreadMultiplier) (2515ms) ✓ mint returns 0 if no tokens are presenti in this contract (563ms) ✓ mint creates iTokens and it sends them to msg.sender (2288ms) ✓ redeem creates iTokens and it sends them to msg.sender (3582ms) ✓ redeem reverts if not all amount is available (2791ms) Contract: IdleFulcrumDisabled ✓ constructor set a token address (1030ms) ✓ constructor set a underlying address (364ms) ✓ allows onlyOwner to setIdleToken (3459ms) ✓ returns next supply rate given amount (2296ms) ✓ returns next supply rate given params (875ms) ✓ getPriceInToken returns iToken price (2893ms) ✓ getAPR returns current yearly rate (counting fee ie spreadMultiplier) (3033ms) ✓ mint returns 0 if no tokens are present in this contract (1512ms) ✓ mint creates iTokens and it sends them to msg.sender (6776ms) ✓ redeem creates iTokens and it sends them to msg.sender (8859ms) ✓ redeem reverts if not all amount is available (19439ms) Contract: IdleFulcrumV2 ✓ constructor set a token address (4487ms) ✓ constructor set a underlying address (7153ms) ✓ allows onlyOwner to setIdleToken (32148ms) ✓ returns next supply rate given amount (36846ms) ✓ returns next supply rate given params (55887ms) ✓ getPriceInToken returns iToken price (71970ms) 6) "before each" hook for "getAPR returns current yearly rate (counting fee ie spreadMultiplier)" Contract: yxToken 7) "before each" hook for "constructor set a underlying address" 161 passing (1h) 7 failing 1) Contract: IdleTokenV3_1 _init set stuff: AssertionError: expected '80' to equal '90' + expected - actual -80 +90 at Context.<anonymous> (test/IdleTokenV3_1.js:329:59) at runMicrotasks (<anonymous>) at processTicksAndRejections (internal/process/task_queues.js:93:5) 2) Contract: IdleTokenV3_1 flashLoanFee: AssertionError: expected '80' to equal '90'+ expected - actual -80 +90 at Context.<anonymous> (test/IdleTokenV3_1.js:2520:29) at runMicrotasks (<anonymous>) at processTicksAndRejections (internal/process/task_queues.js:93:5) 3) Contract: IdleTokenV3_1 executes a flash loan: AssertionError: expected '800000000000000000' to equal '900000000000000000' + expected - actual -800000000000000000 +900000000000000000 at executeFlashLoan (test/IdleTokenV3_1.js:2703:39) at runMicrotasks (<anonymous>) at processTicksAndRejections (internal/process/task_queues.js:93:5) at Context.<anonymous> (test/IdleTokenV3_1.js:2730:5) 4) Contract: IdleDSR "before each" hook for "returns next supply rate given amount != 0": Error: Timeout of 300000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/ezulkosk/audits/idle-contracts/test/wrappers/IdleDSR.js) at listOnTimeout (internal/timers.js:554:17) at processTimers (internal/timers.js:497:7) 5) Contract: IdleDyDx "before each" hook for "constructor set a token address": Error: Timeout of 300000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/ezulkosk/audits/idle-contracts/test/wrappers/IdleDyDx.js) at listOnTimeout (internal/timers.js:554:17) at processTimers (internal/timers.js:497:7) 6) Contract: IdleFulcrumV2 "before each" hook for "getAPR returns current yearly rate (counting fee ie spreadMultiplier)": Error: Timeout of 300000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/ezulkosk/audits/idle-contracts/test/wrappers/IdleFulcrumV2.js) at listOnTimeout (internal/timers.js:554:17) at processTimers (internal/timers.js:497:7) 7) Contract: yxToken "before each" hook for "constructor set a underlying address": Error: Timeout of 300000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/home/ezulkosk/audits/idle-contracts/test/wrappers/yxToken.js) at listOnTimeout (internal/timers.js:554:17) at processTimers (internal/timers.js:497:7) Code Coverage The code is generally well covered by the tests. Coverage of several wrappers and token contracts are reported as zero because mock files were tested instead of the primary contracts. We recommend ensuring that the tests exercise code in the primary contracts. Update:**Update as of commit : some tests fail due to timeouts which influenced coverage and test results. However the two contracts in scope, and had full coverage. e09d4f5IdleTokenGovernance.sol IdleTokenHelper.sol File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 8.65 4.88 9.47 8.71 GST2Consumer.sol 0 0 0 0 … 38,39,40,42 GST2ConsumerV2.sol 100 100 100 100 IdleBatchConverter.sol 92 75 80 92 47,63 IdleRebalancerV3_1.sol 38.71 16.67 25 37.5 … 106,111,116 IdleTokenGovernance.sol 0 0 0 0 … 9,1170,1175 IdleTokenHelper.sol 0 0 0 0 … 115,116,117 IdleTokenV3_1.sol 0 0 0 0 … 213,222,231 IdleViewHelper.sol 0 0 0 0 … 106,107,108 MinimalInitializableProxyFactory.sol 88.89 50 75 81.82 37,38 contracts/ interfaces/ 100 100 100 100 AToken.sol 100 100 100 100 AaveInterestRateStrategy.sol 100 100 100 100 AaveInterestRateStrategyV2.sol 100 100 100 100 AaveLendingPool.sol 100 100 100 100 AaveLendingPoolCore.sol 100 100 100 100 AaveLendingPoolProvider.sol 100 100 100 100 AaveLendingPoolProviderV2.sol 100 100 100 100 AaveLendingPoolV2.sol 100 100 100 100 CERC20.sol 100 100 100 100 CETH.sol 100 100 100 100 CHAI.sol 100 100 100 100 Comptroller.sol 100 100 100 100 DataTypes.sol 100 100 100 100 DyDx.sol 100 100 100 100 File% Stmts % Branch % Funcs % Lines Uncovered Lines DyDxStructs.sol 100 100 100 100 GasToken.sol 100 100 100 100 Gauge.sol 100 100 100 100 GovernorAlpha.sol 100 100 100 100 IAToken.sol 100 100 100 100 IAdminUpgradeabilityProxy.sol 100 100 100 100 IERC20Detailed.sol 100 100 100 100 IERC20Mintable.sol 100 100 100 100 IERC3156FlashBorrower.sol 100 100 100 100 IERC3156FlashLender.sol 100 100 100 100 IGovToken.sol 100 100 100 100 IGovernorAlpha.sol 100 100 100 100 IIdleRebalancer.sol 100 100 100 100 IIdleRebalancerV3.sol 100 100 100 100 IIdleToken.sol 100 100 100 100 IIdleTokenGovernance.sol 100 100 100 100 IIdleTokenHelper.sol 100 100 100 100 IIdleTokenV3.sol 100 100 100 100 IIdleTokenV3_1.sol 100 100 100 100 IInterestSetter.sol 100 100 100 100 ILendingProtocol.sol 100 100 100 100 IProxyAdmin.sol 100 100 100 100 IStableDebtToken.sol 100 100 100 100 IUniswapV2Router02.sol 100 100 100 100 IVariableDebtToken.sol 100 100 100 100 IWETH.sol 100 100 100 100 Idle.sol 100 100 100 100 IdleController.sol 100 100 100 100 PotLike.sol 100 100 100 100 PriceOracle.sol 100 100 100 100 RealUSDC.sol 100 100 100 100 USDT.sol 100 100 100 100 UniswapExchangeInterface.sol 100 100 100 100 UniswapV2Router.sol 100 100 100 100 Vester.sol 100 100 100 100 VesterFactory.sol 100 100 100 100 WhitePaperInterestRateModel.sol 100 100 100 100 iERC20Fulcrum.sol 100 100 100 100 contracts/ libraries/ 0 0 0 0 DSMath.sol 0 0 0 0 20,23,29,68 contracts/ mocks/ 69.87 55.31 57.37 69.88 AaveInterestRateStrategyMockV2.sol 75 100 80 75 14 AaveStableDebtTokenMock.sol 100 100 100 100 AaveVariableDebtTokenMock.sol 100 100 100 100 CHAIMock.sol 30 0 16.67 30 … 30,31,35,36 COMPMock.sol 100 100 100 100 File% Stmts % Branch % Funcs % Lines Uncovered Lines ComptrollerMock.sol 85.71 50 60 85.71 27 DAIMock.sol 100 100 100 100 DyDxMock.sol 3.85 0 6.25 3.85 … 88,90,91,92 FlashLoanerMock.sol 100 100 100 100 ForceSend.sol 0 100 0 0 5 GasTokenMock.sol 100 100 0 100 IDLEMock.sol 0 100 0 0 11,12 IdleAaveNoConst.sol 94.12 70 90.91 94.29 196,197 IdleControllerMock.sol 83.33 50 37.5 83.33 26 IdleDSRNoConst.sol 12.9 7.14 8.33 12.5 … 159,160,164 IdleDyDxNoConst.sol 60 50 54.55 61.11 … 140,155,183 IdleTokenHelperMock.sol 40 100 50 40 16,17,18 IdleTokenHelperNoConst.sol 100 83.33 100 100 IdleTokenV3_1Mock.sol 100 50 100 100 IdleTokenV3_1NoConst.sol 91.12 70.34 92.45 90.91 … 23,957,1034 InterestSetterMock.sol 0 100 0 0 10,13 PotLikeMock.sol 0 100 0 0 … 17,20,23,26 PriceOracleMock.sol 100 100 100 100 USDCMock.sol 0 100 0 0 11,12 WETHMock.sol 65 37.5 57.14 65 … 55,56,70,71 WhitePaperMock.sol 60 100 20 60 19,22 aDAIMock.sol 100 50 100 100 aDAIWrapperMock.sol 60 100 63.64 60 24,27,30,33 aaveInterestRateStrategyMock.sol 75 100 80 75 14 aaveLendingPoolCoreMock.sol 66.67 100 66.67 66.67 25,32,39,46 aaveLendingPoolMock.sol 23.08 100 28.57 23.08 … 46,47,48,49 aaveLendingPoolMockV2.sol 100 100 100 100 aaveLendingPoolProviderMock.sol 100 100 100 100 cDAIMock.sol 100 50 93.33 100 cDAIWrapperMock.sol 84.62 50 78.57 84.62 37,59,65,68 cUSDCMock.sol 0 0 0 0 … 73,76,79,82 cUSDCWrapperMock.sol 0 0 0 0 … 77,80,86,89 cWETHMock.sol 88 50 75 88 60,63,84 iDAIMock.sol 47.06 37.5 16 47.06 … 117,124,130 iDAIWrapperMock.sol 78.95 50 78.57 78.95 34,43,49,52 idleBatchMock.sol 100 100 100 100 idleNewBatchMock.sol 100 100 100 100 yxDAIWrapperMock.sol 60 100 63.64 60 24,27,30,33 yxTokenMock.sol 85.71 50 71.43 85.71 29,33 yxTokenNoConst.sol 9.09 50 11.11 9.09 … 136,140,141 contracts/ others/ 0 0 0 0 BasicMetaTransaction.sol 0 0 0 0 … 66,67,68,73 EIP712Base.sol 0 100 0 0 17,27,33,44 EIP712MetaTransaction.sol 0 0 0 0 … 65,66,71,73 contracts/ tests/ 100 100 100 100 Foo.sol 100 100 100 100 File% Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ wrappers/ 34.1 17.24 25.89 33.99 IdleAave.sol 0 0 0 0 … 185,189,190 IdleAaveV2.sol 92.59 50 77.78 92.86 69,159 IdleCompound.sol 97.83 62.5 90.91 97.87 217 IdleCompoundETH.sol 97.56 50 90.91 97.62 204 IdleCompoundV2.sol 22.22 18.75 18.18 21.62 … 178,179,183 IdleDSR.sol 0 0 0 0 … 151,152,156 IdleDyDx.sol 0 0 0 0 … 147,162,166 IdleFulcrum.sol 0 0 0 0 … 145,146,150 IdleFulcrumDisabled.sol 0 0 0 0 … 137,138,142 IdleFulcrumV2.sol 0 0 0 0 … 137,138,142 yxToken.sol 0 0 0 0 … 136,140,141 All files 44.84 29.2 42.39 44.6 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 cb50e8e3e594a81dc83e0cf49f617941a18d1af83d386943d1f20fa0dd200c86 ./contracts/GST2Consumer.sol 6341f0c902b0651922968bac1b1e5b8e797489faf7ef5e763a544a450d9532cc ./contracts/GST2ConsumerV2.sol 438cdf1986f293e4450935308634df9f2c3e46f962a40941b2e841f3a0f6bf26 ./contracts/IdleBatchConverter.sol 56b6894d0659ffa4f19047613503696b87e31d342055b7a9617f62d6ed4e3e95 ./contracts/IdleRebalancerV3_1.sol b1ad8f1cb504167d4922fb1815f407d1f4e3c01ae0fc87c08a4131339ad2d0ec ./contracts/IdleTokenGovernance.sol 27b8f77d310a8ca4e3c2ee7550c5aab56e2b904896a1e4138e64b5945ba6a817 ./contracts/IdleTokenHelper.sol 21feafdfe57a4713f5c4a230740257949b2bbf691a39c1b3ca3e368e30dbed01 ./contracts/IdleTokenV3_1.sol 600dfee96cf6c6fd38a218fb27928f5e6adf430616cf678ec9d3cd0479019076 ./contracts/IdleViewHelper.sol ffd751a32d9fb50ae7fd3b1724dc30556d83c33367b28a1ee66e4f56af9d65e7 ./contracts/Migrations.sol 09801d7f5658c723d314cf03a0878c8a84edfd9e3dc354d88e16e5ca5d5d1694 ./contracts/MinimalInitializableProxyFactory.sol ae9c56710189a2541ee0164e4a01a0728e03aebdb4c1e60076f81fc343a5ae81 ./contracts/wrappers/IdleAave.sol 14ad3f5658df7c5dfc4ca3a49ba2063d859024774ab00975d1eb24fc46611c6a ./contracts/wrappers/IdleAaveV2.sol 042c9a2781853d5ed66b3d8d6201a973d5071230ca4fa23b7d06e82fd2f3f493 ./contracts/wrappers/IdleCompound.sol 8edc23b10d723319b7e1828c9e2ee2d42bbd85127b30820f581421354a1f78e3 ./contracts/wrappers/IdleCompoundETH.sol 516b144e5fb9f08b65235d21aa89705741d2e269ca5f170bc37cbb07cb0f87cd ./contracts/wrappers/IdleCompoundV2.sol dd032d7fcc9143dd79025fc615d28b7c382eafe24b0fe4e0fdfd8f9b723a223c ./contracts/wrappers/IdleDSR.sol de5c8e471accbb077ad6793e1c60683e67bb1575f415390d7e71b97b8fbeaf66 ./contracts/wrappers/IdleDyDx.sol 452c9e06ec3a218229259b20a0ae26ac140d10e6ee3c6f3c8e1a1ee542732647 ./contracts/wrappers/IdleFulcrum.sol ed3e0a41a28490cbef139927143bf85ea776dcba90fdf0d88b652689e949f2f0 ./contracts/wrappers/IdleFulcrumDisabled.sol e9a689cfb6fb46cdf3644e9e52ec9e3f2576da8724439d8d05e7845724cbde60 ./contracts/wrappers/IdleFulcrumV2.sol fe50d4a334e03b70e55a8d159570070238e2a16d2213f2ae997d80cf398fe6b1 ./contracts/wrappers/yxToken.sol 1cab6221e40bebe7cfc8eb26bb049a6406b1c6d27b244fe33433e2ada194d306 ./contracts/tests/Foo.sol 1d53dfc9360c4975560a07e99bcb5c8882e0fc00a3c5fe23064631f051392356 ./contracts/others/BasicMetaTransaction.sol 304b03c570cb413afb28ed850aed112f0ef28b01850339e5c46f6479143873b7 ./contracts/others/EIP712Base.sol 513597938e062f74be0751429228d3b77d4a2e0fdee04510be9a23defd8c2ffc ./contracts/others/EIP712MetaTransaction.sol 7690baa9f464e5b9005b5ac3f32f68ad79f01ff69a57f3a96d58fd2f598dc67e ./contracts/mocks/aaveInterestRateStrategyMock.sol 95c589f05e2a9e3ab360dad60a39491a62489896b044ada67b1e24533b7e044f ./contracts/mocks/AaveInterestRateStrategyMockV2.sol 46b1695469eec18088c22842468a76cae83c429e135792e58af3cdd4f8684f97 ./contracts/mocks/aaveLendingPoolCoreMock.sol 4d6700a12609c826a559cf9111ec12c665e0c5a225027bb541c08cdea26b160e ./contracts/mocks/aaveLendingPoolMock.sol e3e1e2656454004893c17c15c09aca9952b20bbdc53bb1de57496ab30f00b062 ./contracts/mocks/aaveLendingPoolMockV2.sol a7ceeafde8ac95c36bb1d1756521a686d225b1e62a8ce7510d302b513f28e85d ./contracts/mocks/aaveLendingPoolProviderMock.sol d61d046e28fc88d36fc490e86286e2f3e269718bcdc8b5615f7aef03307e37e4 ./contracts/mocks/AaveStableDebtTokenMock.sol 183cb180870733fa51cdc382cec5aa306bac91d14483e8d53581bdf121436279 ./contracts/mocks/AaveVariableDebtTokenMock.sol 084e2dee6aad484af4d2104331dd6c262815bc478fbb9a346cf43367482ed459 ./contracts/mocks/aDAIMock.sol ebf4a51e421e210584e40e951f67efc1d8e5ee18584697d2dc05cd9887a3a02c ./contracts/mocks/aDAIWrapperMock.sol d08719e992bb6088cbc198b50c4e1a0d5e506f126b4787b7fd484cb267500c32 ./contracts/mocks/cDAIMock.sol 78fbeef0d9d0c111d5252bd9da7fc5841b8ecc04002e834aaa304b130519988c./contracts/mocks/cDAIWrapperMock.sol f93b6b4f22b3eff48fa00a89f8ec8ef9b8dbc4f14ad79c39f00161233b7d1d18 ./contracts/mocks/CHAIMock.sol ff3d0f6903ab36c587f9a6f56f682068e23278843b9a6775d85d984760a3b4d1 ./contracts/mocks/COMPMock.sol 693b69819db0b74712299c245bbb6d574aa1fa24cc7183153ad5f72b5908562d ./contracts/mocks/ComptrollerMock.sol a9f670d48a6f1b757429f3bcb5e9e9682b88b87a73667ed1850e822a588f65c7 ./contracts/mocks/cUSDCMock.sol cae54665d5c87a410b103621a8d92fb9fc0465f4ffcff2a5eea1055c0220b30e ./contracts/mocks/cUSDCWrapperMock.sol 49cd31818be45e5c50c1b414f979ebe121ee4539619ced940c00c99e65551a32 ./contracts/mocks/cWETHMock.sol cebe2c9dadad843bc01fe5e188773248e779e061fb72d11c34eed9a3de0ac5ff ./contracts/mocks/DAIMock.sol a14f262292dee9a5c072f40586ad1e98645efbefbfb1bb28fadd9852f2ea21e5 ./contracts/mocks/DyDxMock.sol 9f6fd266d87523ce293ab6be43c2f4707a88330d6d15ca5ae3334fb0298d9a4e ./contracts/mocks/FlashLoanerMock.sol 226302828e1e6801e388a780a7e1f5ec7c6d00f2a21d5b23e395b6fa03b5ac0e ./contracts/mocks/ForceSend.sol c908417ccf62bf91587e749e21cbf25106c32e82d8d2df7f2ee4a1de5d6635c8 ./contracts/mocks/GasTokenMock.sol 6a7a8776097cb1874b7408e849a5cfc31acb46fede6b787ecf27b14303626587 ./contracts/mocks/iDAIMock.sol fa63babd02cabca4b03ed47de2e46c7d21a287325a7a41c8b182e92f2670cbd9 ./contracts/mocks/iDAIWrapperMock.sol 20f1ed2a6763a04fca95f4618fb5807a5b7b205b5621cb217587693e33124770 ./contracts/mocks/IdleAaveNoConst.sol eaf098d90370f307503d822006d69e4060a45acdd22863570e5f01df6f85b876 ./contracts/mocks/idleBatchMock.sol 4e47686c53566da4cf7d3429df9a737af1a8b547ca0eb1098f3a576a23f410fc ./contracts/mocks/IdleControllerMock.sol 275f276629c16be57e3297e80093ee68d0584cbffac7cb6a0fd4a0d6d22577d7 ./contracts/mocks/IdleDSRNoConst.sol ad7b05f3e17e363ed602d74e0c2175fdbba25384f4a4e2f363cdb5943893f5b5 ./contracts/mocks/IdleDyDxNoConst.sol c9acfdaea6dde4913dc686b281a199eaafa3822f6becd2f8911d96555d947e2e ./contracts/mocks/IDLEMock.sol d325c5366317657684d220d19c65379a6b594aa11bbdb1b4d0ad8ed570d8f286 ./contracts/mocks/idleNewBatchMock.sol e064f2ac2b3fe18eca14cb83203a3b903df28d4663cd569f919f20d0d610f39b ./contracts/mocks/IdleTokenHelperMock.sol de425dd525723e6b7239210cdcbb20e51a6e1e2813a6c01f2bdeed073c56ecc0 ./contracts/mocks/IdleTokenHelperNoConst.sol af86c5013b5b82039049e573bf8a41874f8f230cd0ad11f097b1fcd9f47effec ./contracts/mocks/IdleTokenV3_1Mock.sol 5cf7090f5710828c899450b35e3baf77a87b0ea8d34ce0b4723f1b765d2643fe ./contracts/mocks/IdleTokenV3_1NoConst.sol 615bdc68fb899fc4589085acfe8216e3ca53ce149036bc426fcc05be411b3015 ./contracts/mocks/InterestSetterMock.sol e4b8ae54d5bdcbd3537223fb96f2cdbdfe1861064ff22f9005911f04b950391e ./contracts/mocks/PotLikeMock.sol 31b93924b10ab3642fa618dc9275f9f3ac138795648aa92346a102e7819dc40b ./contracts/mocks/PriceOracleMock.sol fcc07f5f3da7ad6330e5876745bb8040e260dc958bdea8dc41585fe2e0e4df23 ./contracts/mocks/USDCMock.sol 764e043e89425d5541862af2a927be5d468071a12cd0a59c2f9f40704f8b302b ./contracts/mocks/WETHMock.sol 88b2f7f39a492552df9a8162ca4963211a5db6972aa5abc13836524f9681ff17 ./contracts/mocks/WhitePaperMock.sol 7e79e9711c53374379691defac075de72a56f37e3d07e27ff7ac8ffda820b23a ./contracts/mocks/yxDAIWrapperMock.sol 1b194f50c9528c8e77434c765a94a8f97040153633c39c968a124453646bbee3 ./contracts/mocks/yxTokenMock.sol 5f91d951ded04bc114597b848acf070b2d9781dd2b283f17c0f5a697834d5f4e ./contracts/mocks/yxTokenNoConst.sol 36e8d3f881312f1575c1d73feed068768587ebef76e19a8c55e80c7d5ecf548c ./contracts/libraries/DSMath.sol 7947bc218c29bef6b9311ec3b0ba5883c6067d6fa191bcaeddaae400d3783aea ./contracts/interfaces/AaveInterestRateStrategy.sol fb453193300a1ea84d35436536ee01b7cef2ad7eadd1829c57aa7840ae4994ba ./contracts/interfaces/AaveInterestRateStrategyV2.sol c1b64db188c22aa2f8dd8f8fc664f163b53071cdd98c85d67ab5888acf0d63fb ./contracts/interfaces/AaveLendingPool.sol d2ba6c9c8f02946bf98e53295e84b29c334bba2a3b9a755e78342e2621522419 ./contracts/interfaces/AaveLendingPoolCore.sol 1d3c1c096be8bbfb05392fd97c77d9d957dbb2f47b2a8d978da502e8bc8398e6 ./contracts/interfaces/AaveLendingPoolProvider.sol 77851eebeb0039af84466e76ff5c2067de12e3ba4e28983652e706da8691f5e0 ./contracts/interfaces/AaveLendingPoolProviderV2.sol e6112b547d55f40705ef0d633707350ac4f391a165dd11438b7dcf31386c1061 ./contracts/interfaces/AaveLendingPoolV2.sol 42f8369de2db5026fbf056992ca219645d98f9a623274784ea5d1a779c92ad26 ./contracts/interfaces/AToken.sol f22f7508591b8b41a13511c01e336416a772dda310b29d6df88de1b5b8d06854 ./contracts/interfaces/CERC20.sol e4d92cd3688939509570b286100fd6d65b16eb2427b321af5f2bb50d87732e7d ./contracts/interfaces/CETH.sol 206de751b0486eaadccdf76fa95e2d5978be9ea190f1561f12c3413cfff16969 ./contracts/interfaces/CHAI.sol d36649910a636ee1da75d0f33d71f5873b83b169a6d86c06fcdc6412c8e9828d ./contracts/interfaces/Comptroller.sol dba1842d6936dcf06e65aff0ea9d10d7b2e987e531774d58488503d6f9b23f35 ./contracts/interfaces/DataTypes.sol f9282a625866967b49f511894146d3bc8fe6a96f0467eeb39ff6a2df477d98c7 ./contracts/interfaces/DyDx.sol 9ddd041518883d7c8cf7e923c7446ef580bc43aa54db69cd2fd23f4b47be4649 ./contracts/interfaces/DyDxStructs.sol c3f95d558bd27571e06cffd518760bfbcbcbc3df68c05e8db55516de38774229 ./contracts/interfaces/GasToken.sol d3a6cb8c8bcf3312f169da866ae7b1c2aa430861e8c9796410fcaf8a31a65cd1 ./contracts/interfaces/Gauge.sol 07806c507c46dcecbac86a1b3d7e19ad350cce4912ae77b9bb2c97ee888ebbeb ./contracts/interfaces/GovernorAlpha.sol 1464b7d71602f83ad4ee283395aeea50951605765c46df2de968ba26b18b87b3 ./contracts/interfaces/IAdminUpgradeabilityProxy.sol 03fc731b1fba6162bb7bdb2041ed2e077f90a793e8f3f7c1e1d174dd24435473 ./contracts/interfaces/IAToken.sol ff45c284cad657ecd2e97de49e6385ae8dad5acab43f66fcc249f6fb0b652da5 ./contracts/interfaces/Idle.sol b13da4dcaee4a1cc3482baa39154b734a1d6c4d2e172035bf870e33b08043743 ./contracts/interfaces/IdleController.sol 65660b683ee4701fc7a1307bef629d25c14486c6a313f1eb7c9b08248788dce3 ./contracts/interfaces/IERC20Detailed.sol 6356b102e82c77f72c68597645d8d31cc5ea05a78af3e88e48b645b7b6e419ba ./contracts/interfaces/iERC20Fulcrum.sol b42481fd402344cedc5ab082aa415bc1df1f3082cd316dccc05ca00d1be4fd86 ./contracts/interfaces/IERC20Mintable.sol 7f4694524424d65aa60d313b51e931f8e96a2e450610afcf54978480d50d3e29 ./contracts/interfaces/IERC3156FlashBorrower.sol 99cda61bea419a5e9c66fa8659b0a5610694d50650ea6baf3bf15c72a78d3866./contracts/interfaces/IERC3156FlashLender.sol c3144402bb42ded093e2d021d25589fb325bb3ea852eca20bfdcfea45e93d0b2 ./contracts/interfaces/IGovernorAlpha.sol 0252f8f3886f5ac56a520bb36ddffe1f791bd162955b96905f648adf1b6891fa ./contracts/interfaces/IGovToken.sol 587c4202daafdb6616abf906031e7e1bd1535a4d7738389b540f271b5b46292d ./contracts/interfaces/IIdleRebalancer.sol db81c6219c2a4cb02215a7093173b8a0c999833298490009b157b78007bcd110 ./contracts/interfaces/IIdleRebalancerV3.sol f14bf430e2e9ef517d54400de1b6eac9cee26c4a6ba2d5ff1ebc8791512c5ec8 ./contracts/interfaces/IIdleToken.sol 7065f6cfbde2b05f345557a63ac932a48145803119c1df2d6f0d9d8780ab77de ./contracts/interfaces/IIdleTokenGovernance.sol 9cb8659a552afc12fbbe93989d81b7f3bb688357a3750f709d87708db96310f3 ./contracts/interfaces/IIdleTokenHelper.sol 106537974d5c921e415642cd9466409d9e13f0b7ef6d1cab498dd1aac18ef024 ./contracts/interfaces/IIdleTokenV3.sol 30d9d400c05924dd61b8c647c5b563d088aec977db4b5acacf42170f9b30c384 ./contracts/interfaces/IIdleTokenV3_1.sol afd940f2f0f9aa927a3418f01e218962f3033aae5a468b5302b3d4f5b309d366 ./contracts/interfaces/IInterestSetter.sol f3735c051754aaf8d305c94099640d58131454f2c63b2db01cfa27e5aef8810f ./contracts/interfaces/ILendingProtocol.sol bb53d48dc5a9bdfd81792141702186fd14ce628b226e317f40e5df29425d8019 ./contracts/interfaces/IProxyAdmin.sol 69fd7ce938e4f8958b97e54f2b2bf975c5346878cb2f916f26bb917152402e7d ./contracts/interfaces/IStableDebtToken.sol eb5736ae93253b39d8c1564eee8339ea63d08cd8b546bcd76c8fd2b39ab73c17 ./contracts/interfaces/IUniswapV2Router02.sol 5b10cf8281631b3377df2542c8b7da2a76b7b3fbfeaffb8e574827e953724d8a ./contracts/interfaces/IVariableDebtToken.sol a9509ad47c77c28c299f6f2b64f3497fa5c32ce6158599edfe55582248236f19 ./contracts/interfaces/IWETH.sol 9f37dbe5f1e0698275b4c047a21f645244601a9545f7ba20279127d01b274a28 ./contracts/interfaces/PotLike.sol 7030da4cd7de8e1a0481c27db004afacd0133a6bb6427c5d7da8457f0b991286 ./contracts/interfaces/PriceOracle.sol f750845cd5ffdfce07c8a52138b6c0a59f23944218734557c9f0275e2b0aaa8e ./contracts/interfaces/RealUSDC.sol 50099dc807351b99408b1df47a6cdd331823641f4b1fd252a579313e52a494de ./contracts/interfaces/UniswapExchangeInterface.sol 73465ebd1211ca589d042b95bf7ae2330c8022219e93c1a70d0a2d83f6bea779 ./contracts/interfaces/UniswapV2Router.sol b4b1a5bbdba60b0b99e1e6f6311d5d899226af1f72781f5015f19d3bb910a629 ./contracts/interfaces/USDT.sol 690589027c7fa15807705073215e5c1725ace965b209ae52604b41b955051952 ./contracts/interfaces/Vester.sol 7ac6b52da475b0e86f18cd9b1ebbbecc31a047d2ca321db8ca8b22e73f6efe1c ./contracts/interfaces/VesterFactory.sol db96470d5844ab22a99451dee8baced828f0a8614f5e1c4a2e7c21848f978a7e ./contracts/interfaces/WhitePaperInterestRateModel.sol Tests dc6239773c8bb05e00358c8ba93d3755c63d43f4ea2f2f5969fc9f86a45102b0 ./test/IdleBatchConverter.js a7878d3cf4eaec576594be595e00948b8757dc65072ef514c7528a2293a159b1 ./test/IdleTokenV3_1.js 3f0b64e8b21a36f8ca0e268a739b76da6eddcf50dcf197ce2506fff3c04fb0fb ./test/MinimalInitializableProxyFactoryTest.js 011e9182887a9c4a67502cb272c759fd8d81f18ae8b87380e3bbb4ce21b3d12b ./test/wrappers/IdleAave.js 9d76ca81064fcb3a16584b81cc7d2559b2dda58abcece6ccd338e97d871a04d8 ./test/wrappers/IdleAaveV2.js b1c156694d1fe3073ee8181d0f5fe637d8f37e4a93c53d7ee3333586ff1625cd ./test/wrappers/IdleCompound.js 2ae10a4aef755303aafee42c7ae6028cb2d137c5c136f6423c8e842f9a7d3f25 ./test/wrappers/IdleCompoundETH.js f6a29c23b832b3f7226ca0e7b8b9060bc28bc3bf1601b4364ad7e06685cb6843 ./test/wrappers/IdleCompoundV2.js b822cd7c853d87e409587c2598357a4a19279e9a6cfe6d6a6b461d7cdd07496c ./test/wrappers/IdleDSR.js cce2f1e6b0b6b4dc24d929878a9161108072720c09bc2846bb7e3dfc7b467197 ./test/wrappers/IdleDyDx.js 1a45883869155b57c725857fa7461127b3ecb723425edaec77c476d0fab270b8 ./test/wrappers/IdleFulcrum.js 8b71421f1664acfb5eb63da9d61ba508bbec76f69d3d7e36b05512d868470490 ./test/wrappers/IdleFulcrumDisabled.js 00de4f2b89491398082fcbfb8a7db30b63b2da481248aee8ee810a5417d27cd9 ./test/wrappers/IdleFulcrumV2.js c7b7b4755e1faf8ae58a1014665a092de3d89fd4181a288571f723ed795bc7e8 ./test/wrappers/yxToken.js Changelog 2019-12-13 - Initial report •2019-12-19 - Revised report based on commit •9732bc 2020-01-30 - Revised report based on commit •c6fa71c 2020-01-30 - Revised report based on commit •bcb6f09 2020-04-09 - Revised report based on commit •a71a706 2020-04-22 - Revised report based on commit •64f22d0 2020-04-24 - Revised report based on commit •fefd01d 2020-04-27 - Revised report based on commit •7d3b7e4 2020-05-15 - Revised report based on commit •93d3429 2020-05-18 - Revised report based on commit •f9c02d1 2020-08-04 - Revised report based on commit •338ec24 2020-08-12 - Revised report based on commit •1b40261 2020-10-29 - Revised report based on commit •bd40915 2021-04-16 - Revised report based on commit •e09d4f5 2021-04-22 - Revised report based on commit •b5fb299 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. Idle Finance Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 11 (9 Resolved) - Moderate: 4 (4 Resolved) - Major: 0 (0 Resolved) - Critical: 0 (0 Resolved) Minor Issues - Problem: Potential access control issues associated with rebalancing, which may lead to sub-optimal token allocations. - Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Moderate Issues - Problem: Centralized components of the system, and ensuring that users are aware of the roles and responsibilities of the Idle Finance team as owners of the smart contracts. - Fix: Implemented actions to minimize the impact or likelihood of the risk. Major Issues - None Critical Issues - None Observations - The Idle contracts are generally well documented and well designed. - Our main concerns relate to centralized components of the system, and ensuring that users are aware of the roles and responsibilities of the Idle Finance team as owners of the smart contracts. Conclusion Idle Finance has addressed our concerns as of commit b5fb299. Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 2 - Major: 0 - Critical: 0 Minor Issues - Problem (QSP-14): Unchecked return value in IdleTokenV3_1.sol (bcb6f09) - Fix (f9c02d1): Return value checked in IdleTokenV3_1.sol (f9c02d1) - Problem (QSP-15): Unchecked return value in IdleRebalancerV3_1.sol (bcb6f09) - Fix (f9c02d1): Return value checked in IdleRebalancerV3_1.sol (f9c02d1) - Problem (QSP-16): Unchecked return value in IdleCompound.sol (bcb6f09) - Fix (f9c02d1): Return value checked in IdleCompound.sol (f9c02d1) - Problem (QSP-17): Unchecked return value in GSTConsumer*.sol (bcb6f09) - Fix (f9c02d1): Return value checked in GST Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Inaccurate documentation of the IdleTokenGovernance.sol contract (QSP-32) 2.b Fix: Updated documentation of the IdleTokenGovernance.sol contract (QSP-32) Moderate: None Major: None Critical: None Observations: - All previous issues have been resolved, mitigated, or acknowledged - One new informational issue was added Conclusion: The report has been updated based on the commit and all issues have been addressed.
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.10; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IVat.sol"; import "./interfaces/IPot.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IController.sol"; import "./interfaces/IYDai.sol"; import "./helpers/Delegable.sol"; import "./helpers/DecimalMath.sol"; import "./helpers/Orchestrated.sol"; /** * @dev The Controller manages collateral and debt levels for all users, and it is a major user entry point for the Yield protocol. * Controller keeps track of a number of yDai contracts. * Controller allows users to post and withdraw Chai and Weth collateral. * Any transactions resulting in a user weth collateral below dust are reverted. * Controller allows users to borrow yDai against their Chai and Weth collateral. * Controller allows users to repay their yDai debt with yDai or with Dai. * Controller integrates with yDai contracts for minting yDai on borrowing, and burning yDai on repaying debt with yDai. * Controller relies on Treasury for all other asset transfers. * Controller allows orchestrated contracts to erase any amount of debt or collateral for an user. This is to be used during liquidations or during unwind. * Users can delegate the control of their accounts in Controllers to any address. */ contract Controller is IController, Orchestrated(), Delegable(), DecimalMath { using SafeMath for uint256; event Posted(bytes32 indexed collateral, address indexed user, int256 amount); event Borrowed(bytes32 indexed collateral, uint256 indexed maturity, address indexed user, int256 amount); bytes32 public constant CHAI = "CHAI"; bytes32 public constant WETH = "ETH-A"; uint256 public constant DUST = 50000000000000000; // 0.05 ETH uint256 public constant THREE_MONTHS = 7776000; IVat internal _vat; IPot internal _pot; ITreasury internal _treasury; mapping(uint256 => IYDai) public override series; // YDai series, indexed by maturity uint256[] public override seriesIterator; // We need to know all the series mapping(bytes32 => mapping(address => uint256)) public override posted; // Collateral posted by each user mapping(bytes32 => mapping(uint256 => mapping(address => uint256))) public override debtYDai; // Debt owed by each user, by series bool public live = true; /// @dev Set up addresses for vat, pot and Treasury. constructor ( address vat_, address pot_, address treasury_ ) public { _vat = IVat(vat_); _pot = IPot(pot_); _treasury = ITreasury(treasury_); } /// @dev Modified functions only callable while the Controller is not unwinding due to a MakerDAO shutdown. modifier onlyLive() { require(live == true, "Controller: Not available during unwind"); _; } /// @dev Only valid collateral types are Weth and Chai. modifier validCollateral(bytes32 collateral) { require( collateral == WETH || collateral == CHAI, "Controller: Unrecognized collateral" ); _; } /// @dev Only series added through `addSeries` are valid. modifier validSeries(uint256 maturity) { require( containsSeries(maturity), "Controller: Unrecognized series" ); _; } /// @dev Safe casting from uint256 to int256 function toInt256(uint256 x) internal pure returns(int256) { require( x <= 57896044618658097711785492504343953926634992332820282019728792003956564819967, "Controller: Cast overflow" ); return int256(x); } /// @dev Disables post, withdraw, borrow and repay. To be called only when Treasury shuts down. function shutdown() public override { require( _treasury.live() == false, "Controller: Treasury is live" ); live = false; } /// @dev Return if the borrowing power for a given collateral of a user is equal or greater /// than its debt for the same collateral /// @param collateral Valid collateral type /// @param user Address of the user vault function isCollateralized(bytes32 collateral, address user) public view override returns (bool) { return powerOf(collateral, user) >= totalDebtDai(collateral, user); } /// @dev Return if the collateral of an user is between zero and the dust level /// @param collateral Valid collateral type /// @param user Address of the user vault function aboveDustOrZero(bytes32 collateral, address user) public view returns (bool) { uint256 postedCollateral = posted[collateral][user]; return postedCollateral == 0 || DUST < postedCollateral; } /// @dev Return the total number of series registered function totalSeries() public view override returns (uint256) { return seriesIterator.length; } /// @dev Returns if a series has been added to the Controller. /// @param maturity Maturity of the series to verify. function containsSeries(uint256 maturity) public view override returns (bool) { return address(series[maturity]) != address(0); } /// @dev Adds an yDai series to this Controller /// After deployment, ownership should be renounced, so that no more series can be added. /// @param yDaiContract Address of the yDai series to add. function addSeries(address yDaiContract) public onlyOwner { uint256 maturity = IYDai(yDaiContract).maturity(); require( !containsSeries(maturity), "Controller: Series already added" ); series[maturity] = IYDai(yDaiContract); seriesIterator.push(maturity); } /// @dev Dai equivalent of a yDai amount. /// After maturity, the Dai value of a yDai grows according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param yDaiAmount Amount of yDai to convert. /// @return Dai equivalent of an yDai amount. function inDai(bytes32 collateral, uint256 maturity, uint256 yDaiAmount) public view override validCollateral(collateral) returns (uint256) { IYDai yDai = series[maturity]; if (yDai.isMature()){ if (collateral == WETH){ return muld(yDaiAmount, yDai.rateGrowth()); } else if (collateral == CHAI) { return muld(yDaiAmount, yDai.chiGrowth()); } } else { return yDaiAmount; } } /// @dev yDai equivalent of a Dai amount. /// After maturity, the yDai value of a Dai decreases according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param daiAmount Amount of Dai to convert. /// @return yDai equivalent of a Dai amount. function inYDai(bytes32 collateral, uint256 maturity, uint256 daiAmount) public view override validCollateral(collateral) returns (uint256) { IYDai yDai = series[maturity]; if (yDai.isMature()){ if (collateral == WETH){ return divd(daiAmount, yDai.rateGrowth()); } else if (collateral == CHAI) { return divd(daiAmount, yDai.chiGrowth()); } } else { return daiAmount; } } /// @dev Debt in dai of an user /// After maturity, the Dai debt of a position grows according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param user Address of the user vault /// @return Debt in dai of an user // // rate_now // debt_now = debt_mat * ---------- // rate_mat // function debtDai(bytes32 collateral, uint256 maturity, address user) public view returns (uint256) { return inDai(collateral, maturity, debtYDai[collateral][maturity][user]); } /// @dev Total debt of an user across all series, in Dai /// The debt is summed across all series, taking into account interest on the debt after a series matures. /// This function loops through all maturities, limiting the contract to hundreds of maturities. /// @param collateral Valid collateral type /// @param user Address of the user vault /// @return Total debt of an user across all series, in Dai function totalDebtDai(bytes32 collateral, address user) public view override returns (uint256) { uint256 totalDebt; uint256[] memory _seriesIterator = seriesIterator; for (uint256 i = 0; i < _seriesIterator.length; i += 1) { if (debtYDai[collateral][_seriesIterator[i]][user] > 0) { totalDebt = totalDebt + debtDai(collateral, _seriesIterator[i], user); } } // We don't expect hundreds of maturities per controller return totalDebt; } /// @dev Borrowing power (in dai) of a user for a specific series and collateral. /// @param collateral Valid collateral type /// @param user Address of the user vault /// @return Borrowing power of an user in dai. // // powerOf[user](wad) = posted[user](wad) * price()(ray) // function powerOf(bytes32 collateral, address user) public view returns (uint256) { // dai = price * collateral if (collateral == WETH){ (,, uint256 spot,,) = _vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return muld(posted[collateral][user], spot); } else if (collateral == CHAI) { uint256 chi = _pot.chi(); return muld(posted[collateral][user], chi); } return 0; } /// @dev Returns the amount of collateral locked in borrowing operations. /// @param collateral Valid collateral type. /// @param user Address of the user vault. function locked(bytes32 collateral, address user) public view validCollateral(collateral) returns (uint256) { if (collateral == WETH){ (,, uint256 spot,,) = _vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return divdrup(totalDebtDai(collateral, user), spot); } else if (collateral == CHAI) { return divdrup(totalDebtDai(collateral, user), _pot.chi()); } } /// @dev Takes collateral assets from `from` address, and credits them to `to` collateral account. /// `from` can delegate to other addresses to take assets from him. Also needs to use `ERC20.approve`. /// Calling ERC20.approve for Treasury contract is a prerequisite to this function /// @param collateral Valid collateral type. /// @param from Wallet to take collateral from. /// @param to Yield vault to put the collateral in. /// @param amount Amount of collateral to move. // from --- Token ---> us(to) function post(bytes32 collateral, address from, address to, uint256 amount) public override validCollateral(collateral) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { posted[collateral][to] = posted[collateral][to].add(amount); if (collateral == WETH){ require( aboveDustOrZero(collateral, to), "Controller: Below dust" ); _treasury.pushWeth(from, amount); } else if (collateral == CHAI) { _treasury.pushChai(from, amount); } emit Posted(collateral, to, toInt256(amount)); } /// @dev Returns collateral to `to` wallet, taking it from `from` Yield vault account. /// `from` can delegate to other addresses to take assets from him. /// @param collateral Valid collateral type. /// @param from Yield vault to take collateral from. /// @param to Wallet to put the collateral in. /// @param amount Amount of collateral to move. // us(from) --- Token ---> to // SWC-Unprotected Ether Withdrawal: L294 - L320 function withdraw(bytes32 collateral, address from, address to, uint256 amount) public override validCollateral(collateral) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { posted[collateral][from] = posted[collateral][from].sub(amount); // Will revert if not enough posted require( isCollateralized(collateral, from), "Controller: Too much debt" ); if (collateral == WETH){ require( aboveDustOrZero(collateral, to), "Controller: Below dust" ); _treasury.pullWeth(to, amount); } else if (collateral == CHAI) { _treasury.pullChai(to, amount); } emit Posted(collateral, from, -toInt256(amount)); } /// @dev Mint yDai for a given series for wallet `to` by increasing the user debt in Yield vault `from` /// `from` can delegate to other addresses to borrow using his vault. /// The collateral needed changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Yield vault that gets an increased debt. /// @param to Wallet to put the yDai in. /// @param yDaiAmount Amount of yDai to borrow. // // posted[user](wad) >= (debtYDai[user](wad)) * amount (wad)) * collateralization (ray) // // us(from) --- yDai ---> to // debt++ function borrow(bytes32 collateral, uint256 maturity, address from, address to, uint256 yDaiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { IYDai yDai = series[maturity]; debtYDai[collateral][maturity][from] = debtYDai[collateral][maturity][from].add(yDaiAmount); require( isCollateralized(collateral, from), "Controller: Too much debt" ); yDai.mint(to, yDaiAmount); emit Borrowed(collateral, maturity, from, toInt256(yDaiAmount)); } /// @dev Burns yDai from `from` wallet to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and yDai series, in Yield vault `to`. /// `from` can delegate to other addresses to take yDai from him for the repayment. /// Calling yDai.approve for Controller contract is a prerequisite to this function /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Wallet providing the yDai for repayment. /// @param to Yield vault to repay debt for. /// @param yDaiAmount Amount of yDai to use for debt repayment. // // debt_nominal // debt_discounted = debt_nominal - repay_amount * --------------- // debt_now // // user(from) --- yDai ---> us(to) // debt-- function repayYDai(bytes32 collateral, uint256 maturity, address from, address to, uint256 yDaiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { uint256 toRepay = Math.min(yDaiAmount, debtYDai[collateral][maturity][to]); series[maturity].burn(from, toRepay); _repay(collateral, maturity, to, toRepay); } /// @dev Burns Dai from `from` wallet to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and yDai series, in Yield vault `to`. /// The amount of debt repaid changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// `from` can delegate to other addresses to take Dai from him for the repayment. /// Calling ERC20.approve for Treasury contract is a prerequisite to this function /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Wallet providing the Dai for repayment. /// @param to Yield vault to repay debt for. /// @param daiAmount Amount of Dai to use for debt repayment. // // debt_nominal // debt_discounted = debt_nominal - repay_amount * --------------- // debt_now // // user --- dai ---> us // debt-- function repayDai(bytes32 collateral, uint256 maturity, address from, address to, uint256 daiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { uint256 toRepay = Math.min(daiAmount, debtDai(collateral, maturity, to)); _treasury.pushDai(from, toRepay); // Have Treasury process the dai _repay(collateral, maturity, to, inYDai(collateral, maturity, toRepay)); } /// @dev Removes an amount of debt from an user's vault. /// Internal function. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param user Yield vault to repay debt for. /// @param yDaiAmount Amount of yDai to use for debt repayment. // // principal // principal_repayment = gross_repayment * ---------------------- // principal + interest // function _repay(bytes32 collateral, uint256 maturity, address user, uint256 yDaiAmount) internal { debtYDai[collateral][maturity][user] = debtYDai[collateral][maturity][user].sub(yDaiAmount); emit Borrowed(collateral, maturity, user, -toInt256(yDaiAmount)); } /// @dev Removes all collateral and debt for an user, for a given collateral type. /// This function can only be called by other Yield contracts, not users directly. /// @param collateral Valid collateral type. /// @param user Address of the user vault /// @return The amounts of collateral and debt removed from Controller. function erase(bytes32 collateral, address user) public override validCollateral(collateral) onlyOrchestrated("Controller: Not Authorized") returns (uint256, uint256) { uint256 userCollateral = posted[collateral][user]; delete posted[collateral][user]; uint256 userDebt; uint256[] memory _seriesIterator = seriesIterator; for (uint256 i = 0; i < _seriesIterator.length; i += 1) { uint256 maturity = _seriesIterator[i]; userDebt = userDebt.add(debtDai(collateral, maturity, user)); // SafeMath shouldn't be needed delete debtYDai[collateral][maturity][user]; } // We don't expect hundreds of maturities per controller return (userCollateral, userDebt); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "./interfaces/IController.sol"; import "./interfaces/ILiquidations.sol"; import "./interfaces/ITreasury.sol"; import "./helpers/DecimalMath.sol"; import "./helpers/Delegable.sol"; import "./helpers/Orchestrated.sol"; /** * @dev The Liquidations contract allows to liquidate undercollateralized weth vaults in a reverse Dutch auction. * Undercollateralized vaults can be liquidated by calling `liquidate`. * Collateral from vaults can be bought with Dai using `buy`. * Debt and collateral records will be adjusted in the Controller using `controller.grab`. * Dai taken in payment will be handed over to Treasury, and collateral assets bought will be taken from Treasury as well. * If a vault becomes colalteralized, the liquidation can be stopped with `cancel`. */ contract Liquidations is ILiquidations, Orchestrated(), Delegable(), DecimalMath { event Liquidation(address indexed user, uint256 started, uint256 collateral, uint256 debt); bytes32 public constant WETH = "ETH-A"; uint256 public constant AUCTION_TIME = 3600; uint256 public constant DUST = 25000000000000000; // 0.025 ETH uint128 public constant FEE = 25000000000000000; // 0.025 ETH IERC20 internal _dai; ITreasury internal _treasury; IController internal _controller; struct Vault { uint128 collateral; uint128 debt; } mapping(address => uint256) public liquidations; mapping(address => Vault) public vaults; Vault public override totals; bool public live = true; /// @dev The Liquidations constructor links it to the Dai, Treasury and Controller contracts. constructor ( address dai_, address treasury_, address controller_ ) public { _dai = IERC20(dai_); _treasury = ITreasury(treasury_); _controller = IController(controller_); } /// @dev Only while Liquidations is not unwinding due to a MakerDAO shutdown. modifier onlyLive() { require(live == true, "Controller: Not available during unwind"); _; } /// @dev Overflow-protected addition, from OpenZeppelin function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 c = a + b; require(c >= a, "Market: Dai reserves too high"); return c; } /// @dev Overflow-protected substraction, from OpenZeppelin function sub(uint128 a, uint128 b) internal pure returns (uint128) { require(b <= a, "Market: yDai reserves too low"); uint128 c = a - b; return c; } /// @dev Safe casting from uint256 to uint128 function toUint128(uint256 x) internal pure returns(uint128) { require( x <= 340282366920938463463374607431768211455, "Market: Cast overflow" ); return uint128(x); } /// @dev Disables buying at liquidations. To be called only when Treasury shuts down. function shutdown() public override { require( _treasury.live() == false, "Liquidations: Treasury is live" ); live = false; } /// @dev Return if the debt of an user is between zero and the dust level /// @param user Address of the user vault function aboveDustOrZero(address user) public view returns (bool) { uint256 collateral = vaults[user].collateral; return collateral == 0 || DUST < collateral; } /// @dev Starts a liquidation process for an undercollateralized vault. /// A liquidation fee is transferred from the liquidated user to a designated account as payment. /// @param user Address of the user vault to liquidate. /// @param to Address of the liquidations account to receive the liquidation fee. function liquidate(address user, address to) public onlyLive { require( !_controller.isCollateralized(WETH, user), "Liquidations: Vault is not undercollateralized" ); // A user in liquidation can be liquidated again, but doesn't restart the auction clock // solium-disable-next-line security/no-block-members if (liquidations[user] == 0) liquidations[user] = now; (uint256 userCollateral, uint256 userDebt) = _controller.erase(WETH, user); totals = Vault({ collateral: add(totals.collateral, toUint128(userCollateral)), debt: add(totals.debt, toUint128(userDebt)) }); Vault memory vault = Vault({ // TODO: Test a user that is liquidated twice collateral: add(vaults[user].collateral, sub(toUint128(userCollateral), FEE)), debt: add(vaults[user].debt, toUint128(userDebt)) }); vaults[user] = vault; vaults[to].collateral = add(vaults[to].collateral, FEE); emit Liquidation(user, now, userCollateral, userDebt); } /// @dev Buy a portion of a position under liquidation. /// The caller pays the debt of `user`, and `from` receives an amount of collateral. /// `from` can delegate to other addresses to buy for him. Also needs to use `ERC20.approve`. /// @param liquidated Address of the user vault to liquidate. /// @param from Address of the wallet paying Dai for liquidated collateral. /// @param to Address of the wallet to send the obtained collateral to. /// @param daiAmount Amount of Dai to give in exchange for liquidated collateral. /// @return The amount of collateral obtained. function buy(address from, address to, address liquidated, uint256 daiAmount) public onlyLive onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") returns (uint256) { require( vaults[liquidated].debt > 0, "Liquidations: Vault is not in liquidation" ); _treasury.pushDai(from, daiAmount); // calculate collateral to grab. Using divdrup stops rounding from leaving 1 stray wei in vaults. uint256 tokenAmount = divdrup(daiAmount, price(liquidated)); totals = Vault({ collateral: sub(totals.collateral, toUint128(tokenAmount)), debt: sub(totals.debt, toUint128(daiAmount)) }); Vault memory vault = Vault({ collateral: sub(vaults[liquidated].collateral, toUint128(tokenAmount)), debt: sub(vaults[liquidated].debt, toUint128(daiAmount)) }); vaults[liquidated] = vault; _treasury.pullWeth(to, tokenAmount); require( aboveDustOrZero(liquidated), "Liquidations: Below dust" ); return tokenAmount; } /// @dev Retrieve weth from a liquidations account. This weth could come from liquidator fees or as remainders of liquidations. /// `from` can delegate to other addresses to withdraw from him. /// @param from Address of the liquidations user vault to withdraw weth from. /// @param to Address of the wallet receiving the withdrawn weth. /// @param tokenAmount Amount of Weth to withdraw. function withdraw(address from, address to, uint256 tokenAmount) public onlyLive onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") { Vault storage vault = vaults[from]; require( vault.debt == 0, "Liquidations: User still in liquidation" ); totals.collateral = sub(totals.collateral, toUint128(tokenAmount)); vault.collateral = sub(vault.collateral, toUint128(tokenAmount)); _treasury.pullWeth(to, tokenAmount); } /// @dev Removes all collateral and debt for an user. /// This function can only be called by other Yield contracts, not users directly. /// @param user Address of the user vault /// @return The amounts of collateral and debt removed from Liquidations. function erase(address user) public override onlyOrchestrated("Liquidations: Not Authorized") returns (uint128, uint128) { Vault storage vault = vaults[user]; uint128 collateral = vault.collateral; uint128 debt = vault.debt; totals = Vault({ collateral: sub(totals.collateral, collateral), debt: sub(totals.debt, debt) }); delete vaults[user]; return (collateral, debt); } /// @dev Return price of a collateral unit, in dai, at the present moment, for a given user /// @param user Address of the user vault in liquidation. // dai = price * collateral // // collateral 1 min(auction, elapsed) // price = 1 / (------------- * (--- + -----------------------)) // debt 2 2 * auction function price(address user) public view returns (uint256) { require( liquidations[user] > 0, "Liquidations: Vault is not targeted" ); uint256 dividend1 = uint256(vaults[user].collateral); uint256 divisor1 = uint256(vaults[user].debt); uint256 term1 = dividend1.mul(UNIT).div(divisor1); uint256 dividend3 = Math.min(AUCTION_TIME, now - liquidations[user]); // - unlikely to overflow uint256 divisor3 = AUCTION_TIME.mul(2); uint256 term2 = UNIT.div(2); uint256 term3 = dividend3.mul(UNIT).div(divisor3); return divd(UNIT, muld(term1, term2 + term3)); // + unlikely to overflow } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev The Migrations contract is a standard truffle contract that keeps track of which migrations were done on the current network. * For yDai, we have updated it and added functionality that enables it as well to work as a deployed contract registry. */ contract Migrations is Ownable() { uint public lastCompletedMigration; /// @dev Deployed contract to deployment address mapping(bytes32 => address) public contracts; /// @dev Contract name iterator bytes32[] public names; /// @dev Amount of registered contracts function length() external view returns (uint) { return names.length; } /// @dev Register a contract name and address function register(bytes32 name, address addr ) external onlyOwner { contracts[name] = addr; names.push(name); } /// @dev Register the index of the last completed migration function setCompleted(uint completed) public onlyOwner { lastCompletedMigration = completed; } /// @dev Copy the index of the last completed migration to a new version of the Migrations contract function upgrade(address newAddress) public onlyOwner { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IVat.sol"; import "./interfaces/IDaiJoin.sol"; import "./interfaces/IGemJoin.sol"; import "./interfaces/IPot.sol"; import "./interfaces/IEnd.sol"; import "./interfaces/IChai.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IController.sol"; import "./interfaces/IYDai.sol"; import "./interfaces/ILiquidations.sol"; import "./helpers/DecimalMath.sol"; /** * @dev Unwind allows everyone to recover their assets from the Yield protocol in the event of a MakerDAO shutdown. * During the unwind process, the system debt to MakerDAO is settled first with `settleTreasury`, extracting all free weth. * Once the Treasury is settled, any system savings are converted from Chai to Weth using `cashSavings`. * At this point, users can settle their positions using `settle`. The MakerDAO rates will be used to convert all debt and collateral to a Weth payout. * Users can also redeem here their yDai for a Weth payout, using `redeem`. */ contract Unwind is Ownable(), DecimalMath { using SafeMath for uint256; bytes32 public constant CHAI = "CHAI"; bytes32 public constant WETH = "ETH-A"; IVat internal _vat; IDaiJoin internal _daiJoin; IERC20 internal _weth; IGemJoin internal _wethJoin; IPot internal _pot; IEnd internal _end; IChai internal _chai; ITreasury internal _treasury; IController internal _controller; ILiquidations internal _liquidations; uint256 public _fix; // Dai to weth price on DSS Unwind uint256 public _chi; // Chai to dai price on DSS Unwind uint256 internal _treasuryWeth; // Weth that was held by treasury before settling bool public settled; bool public cashedOut; bool public live = true; /// @dev The constructor links to vat, daiJoin, weth, wethJoin, jug, pot, end, chai, treasury, controller and liquidations. /// Liquidations should have privileged access to treasury, controller and liquidations using orchestration. /// The constructor gives treasury and end permission on unwind's MakerDAO vaults. constructor ( address vat_, address daiJoin_, address weth_, address wethJoin_, address pot_, address end_, address chai_, address treasury_, address controller_, address liquidations_ ) public { // These could be hardcoded for mainnet deployment. _vat = IVat(vat_); _daiJoin = IDaiJoin(daiJoin_); _weth = IERC20(weth_); _wethJoin = IGemJoin(wethJoin_); _pot = IPot(pot_); _end = IEnd(end_); _chai = IChai(chai_); _treasury = ITreasury(treasury_); _controller = IController(controller_); _liquidations = ILiquidations(liquidations_); _vat.hope(address(_treasury)); _vat.hope(address(_end)); } /// @dev max(0, x - y) function subFloorZero(uint256 x, uint256 y) public pure returns(uint256) { if (y >= x) return 0; else return x - y; } /// @dev Safe casting from uint256 to int256 function toInt(uint256 x) internal pure returns(int256) { require( x <= 57896044618658097711785492504343953926634992332820282019728792003956564819967, "Treasury: Cast overflow" ); return int256(x); } /// @dev Disables treasury, controller and liquidations. function unwind() public { require( _end.tag(WETH) != 0, "Unwind: MakerDAO not shutting down" ); live = false; _treasury.shutdown(); _controller.shutdown(); _liquidations.shutdown(); } /// @dev Return the Dai equivalent value to a Chai amount. /// @param chaiAmount The Chai value to convert. /// @param chi The `chi` value from `Pot`. function chaiToDai(uint256 chaiAmount, uint256 chi) public pure returns(uint256) { return muld(chaiAmount, chi); } /// @dev Return the Weth equivalent value to a Dai amount, during Dss Shutdown /// @param daiAmount The Dai value to convert. /// @param fix The `fix` value from `End`. function daiToFixWeth(uint256 daiAmount, uint256 fix) public pure returns(uint256) { return muld(daiAmount, fix); } /// @dev Settle system debt in MakerDAO and free remaining collateral. function settleTreasury() public { require( live == false, "Unwind: Unwind first" ); (uint256 ink, uint256 art) = _vat.urns(WETH, address(_treasury)); _treasuryWeth = ink; // We will need this to skim profits _vat.fork( // Take the treasury vault WETH, address(_treasury), address(this), toInt(ink), toInt(art) ); _end.skim(WETH, address(this)); // Settle debts _end.free(WETH); // Free collateral uint256 gem = _vat.gem(WETH, address(this)); // Find out how much collateral we have now _wethJoin.exit(address(this), gem); // Take collateral out settled = true; } /// @dev Put all chai savings in MakerDAO and exchange them for weth function cashSavings() public { require( _end.tag(WETH) != 0, "Unwind: End.sol not caged" ); require( _end.fix(WETH) != 0, "Unwind: End.sol not ready" ); uint256 daiTokens = _chai.dai(address(_treasury)); // Find out how much is the chai worth _chai.draw(address(_treasury), _treasury.savings()); // Get the chai as dai _daiJoin.join(address(this), daiTokens); // Put the dai into MakerDAO _end.pack(daiTokens); // Into End.sol, more exactly _end.cash(WETH, daiTokens); // Exchange the dai for weth uint256 gem = _vat.gem(WETH, address(this)); // Find out how much collateral we have now _wethJoin.exit(address(this), gem); // Take collateral out cashedOut = true; _fix = _end.fix(WETH); _chi = _pot.chi(); } /// @dev Settles a series position in Controller for any user, and then returns any remaining collateral as weth using the unwind Dai to Weth price. /// @param collateral Valid collateral type. /// @param user User vault to settle, and wallet to receive the corresponding weth. function settle(bytes32 collateral, address user) public { require(settled && cashedOut, "Unwind: Not ready"); (uint256 tokens, uint256 debt) = _controller.erase(collateral, user); uint256 remainder; if (collateral == WETH) { remainder = subFloorZero(tokens, daiToFixWeth(debt, _fix)); } else if (collateral == CHAI) { remainder = daiToFixWeth(subFloorZero(chaiToDai(tokens, _chi), debt), _fix); } require(_weth.transfer(user, remainder)); } /// @dev Settles a user vault in Liquidations, and then returns any remaining collateral as weth using the unwind Dai to Weth price. /// @param user User vault to settle, and wallet to receive the corresponding weth. function settleLiquidations(address user) public { require(settled && cashedOut, "Unwind: Not ready"); (uint256 weth, uint256 debt) = _liquidations.erase(user); uint256 remainder = subFloorZero(weth, daiToFixWeth(debt, _fix)); require(_weth.transfer(user, remainder)); } /// @dev Redeems YDai for weth for any user. YDai.redeem won't work if MakerDAO is in shutdown. /// @param maturity Maturity of an added series /// @param user Wallet containing the yDai to burn. function redeem(uint256 maturity, address user) public { require(settled && cashedOut, "Unwind: Not ready"); IYDai yDai = _controller.series(maturity); uint256 yDaiAmount = yDai.balanceOf(user); yDai.burn(user, yDaiAmount); require( _weth.transfer( user, daiToFixWeth(muld(yDaiAmount, yDai.chiGrowth()), _fix) ) ); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.10; import "@openzeppelin/contracts/math/Math.sol"; import "./interfaces/IVat.sol"; import "./interfaces/IPot.sol"; import "./interfaces/ITreasury.sol"; import "./interfaces/IYDai.sol"; import "./interfaces/IFlashMinter.sol"; import "./helpers/Delegable.sol"; import "./helpers/DecimalMath.sol"; import "./helpers/Orchestrated.sol"; import "./helpers/ERC20Permit.sol"; /** * @dev yDai is a yToken targeting Chai. * Each yDai contract has a specific maturity time. One yDai is worth one Chai at or after maturity time. * At maturity, the yDai can be triggered to mature, which records the current rate and chi from MakerDAO and enables redemption. * Redeeming an yDai means burning it, and the contract will retrieve Dai from Treasury equal to one Dai times the growth in chi since maturity. * yDai also tracks the MakerDAO stability fee accumulator at the time of maturity, and the growth since. This is not used internally. * Minting and burning of yDai is restricted to orchestrated contracts. Redeeming and flash-minting is allowed to anyone. */ contract YDai is Orchestrated(), Delegable(), DecimalMath, ERC20Permit, IYDai { event Redeemed(address indexed from, address indexed to, uint256 yDaiIn, uint256 daiOut); event Matured(uint256 rate, uint256 chi); bytes32 public constant WETH = "ETH-A"; IVat internal _vat; IPot internal _pot; ITreasury internal _treasury; bool public override isMature; uint256 public override maturity; uint256 public override chi0; // Chi at maturity uint256 public override rate0; // Rate at maturity /// @dev The constructor: /// Sets the name and symbol for the yDai token. /// Connects to Vat, Jug, Pot and Treasury. /// Sets the maturity date for the yDai, in unix time. /// Initializes chi and rate at maturity time as 1.0 with 27 decimals. constructor( address vat_, address pot_, address treasury_, uint256 maturity_, string memory name, string memory symbol ) public ERC20(name, symbol) { _vat = IVat(vat_); _pot = IPot(pot_); _treasury = ITreasury(treasury_); maturity = maturity_; chi0 = UNIT; rate0 = UNIT; } /// @dev Chi differential between maturity and now in RAY. Returns 1.0 if not mature. /// If rateGrowth < chiGrowth, returns rate. // // chi_now // chi() = --------- // chi_mat // function chiGrowth() public view override returns(uint256){ if (isMature != true) return chi0; return Math.min(rateGrowth(), divd(_pot.chi(), chi0)); // Rounding in favour of the protocol } /// @dev Rate differential between maturity and now in RAY. Returns 1.0 if not mature. /// rateGrowth is floored to 1.0. // // rate_now // rateGrowth() = ---------- // rate_mat // function rateGrowth() public view override returns(uint256){ if (isMature != true) return rate0; (, uint256 rate,,,) = _vat.ilks(WETH); return Math.max(UNIT, divdrup(rate, rate0)); // Rounding in favour of the protocol } /// @dev Mature yDai and capture chi and rate function mature() public override { require( // solium-disable-next-line security/no-block-members now > maturity, "YDai: Too early to mature" ); require( isMature != true, "YDai: Already matured" ); (, rate0,,,) = _vat.ilks(WETH); // Retrieve the MakerDAO Vat rate0 = Math.max(rate0, UNIT); // Floor it at 1.0 chi0 = _pot.chi(); isMature = true; emit Matured(rate0, chi0); } /// @dev Burn yTokens and return their dai equivalent value, pulled from the Treasury /// During unwind, `_treasury.pullDai()` will revert which is right. /// `from` needs to tell yDai to approve the burning of the yDai tokens. /// `from` can delegate to other addresses to redeem his yDai and put the Dai proceeds in the `to` wallet. /// The collateral needed changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// @param from Wallet to burn yDai from. /// @param to Wallet to put the Dai in. /// @param yDaiAmount Amount of yDai to burn. // from --- yDai ---> us // us --- Dai ---> to function redeem(address from, address to, uint256 yDaiAmount) public onlyHolderOrDelegate(from, "YDai: Only Holder Or Delegate") { require( isMature == true, "YDai: yDai is not mature" ); _burn(from, yDaiAmount); // Burn yDai from `from` uint256 daiAmount = muld(yDaiAmount, chiGrowth()); // User gets interest for holding after maturity _treasury.pullDai(to, daiAmount); // Give dai to `to`, from Treasury emit Redeemed(from, to, yDaiAmount, daiAmount); } /// @dev Flash-mint yDai. Calls back on `IFlashMinter.executeOnFlashMint()` /// @param to Wallet to mint the yDai in. /// @param yDaiAmount Amount of yDai to mint. /// @param data User-defined data to pass on to `executeOnFlashMint()` function flashMint(address to, uint256 yDaiAmount, bytes calldata data) external override { _mint(to, yDaiAmount); IFlashMinter(msg.sender).executeOnFlashMint(to, yDaiAmount, data); _burn(to, yDaiAmount); } /// @dev Mint yDai. Only callable by Controller contracts. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to mint the yDai in. /// @param yDaiAmount Amount of yDai to mint. function mint(address to, uint256 yDaiAmount) public override onlyOrchestrated("YDai: Not Authorized") { _mint(to, yDaiAmount); } /// @dev Burn yDai. Only callable by Controller contracts. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to burn the yDai from. /// @param yDaiAmount Amount of yDai to burn. function burn(address from, uint256 yDaiAmount) public override onlyOrchestrated("YDai: Not Authorized") { _burn(from, yDaiAmount); } /// @dev Creates `yDaiAmount` tokens and assigns them to `to`, increasing the total supply, up to a limit of 2**112. /// @param to Wallet to mint the yDai in. /// @param yDaiAmount Amount of yDai to mint. function _mint(address to, uint256 yDaiAmount) internal override { super._mint(to, yDaiAmount); require(totalSupply() <= 5192296858534827628530496329220096, "YDai: Total supply limit exceeded"); // 2**112 } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.10; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IVat.sol"; import "./interfaces/IDaiJoin.sol"; import "./interfaces/IGemJoin.sol"; import "./interfaces/IPot.sol"; import "./interfaces/IChai.sol"; import "./interfaces/ITreasury.sol"; import "./helpers/DecimalMath.sol"; import "./helpers/Orchestrated.sol"; /** * @dev Treasury manages asset transfers between all contracts in the Yield Protocol and other external contracts such as Chai and MakerDAO. * Treasury doesn't have any transactional functions available for regular users. * All transactional methods are to be available only for orchestrated contracts. * Treasury will ensure that all Weth is always stored as collateral in MAkerDAO. * Treasury will use all Dai to pay off system debt in MakerDAO first, and if there is no system debt the surplus Dai will be wrapped as Chai. * Treasury will use any Chai it holds when requested to provide Dai. If there isn't enough Chai, it will borrow Dai from MakerDAO. */ contract Treasury is ITreasury, Orchestrated(), DecimalMath { bytes32 constant WETH = "ETH-A"; IERC20 internal _dai; IChai internal _chai; IPot internal _pot; IERC20 internal _weth; IDaiJoin internal _daiJoin; IGemJoin internal _wethJoin; IVat internal _vat; address internal _unwind; bool public override live = true; /// @dev As part of the constructor: /// Treasury allows the `chai` and `wethJoin` contracts to take as many tokens as wanted. /// Treasury approves the `daiJoin` and `wethJoin` contracts to move assets in MakerDAO. constructor ( address vat_, address weth_, address dai_, address wethJoin_, address daiJoin_, address pot_, address chai_ ) public { // These could be hardcoded for mainnet deployment. _dai = IERC20(dai_); _chai = IChai(chai_); _pot = IPot(pot_); _weth = IERC20(weth_); _daiJoin = IDaiJoin(daiJoin_); _wethJoin = IGemJoin(wethJoin_); _vat = IVat(vat_); _vat.hope(wethJoin_); _vat.hope(daiJoin_); _dai.approve(address(_chai), uint256(-1)); // Chai will never cheat on us _weth.approve(address(_wethJoin), uint256(-1)); // WethJoin will never cheat on us } /// @dev Only while the Treasury is not unwinding due to a MakerDAO shutdown. modifier onlyLive() { require(live == true, "Treasury: Not available during unwind"); _; } /// @dev Safe casting from uint256 to int256 function toInt(uint256 x) internal pure returns(int256) { require( x <= 57896044618658097711785492504343953926634992332820282019728792003956564819967, "Treasury: Cast overflow" ); return int256(x); } /// @dev Disables pulling and pushing. Can only be called if MakerDAO shuts down. function shutdown() public override { require( _vat.live() == 0, "Treasury: MakerDAO is live" ); live = false; } /// @dev Returns the Treasury debt towards MakerDAO, in Dai. /// We have borrowed (rate * art) /// Borrowing limit (rate * art) <= (ink * spot) function debt() public view override returns(uint256) { (, uint256 rate,,,) = _vat.ilks(WETH); // Retrieve the MakerDAO stability fee for Weth (, uint256 art) = _vat.urns(WETH, address(this)); // Retrieve the Treasury debt in MakerDAO return muld(art, rate); } /// @dev Returns the Treasury borrowing capacity from MakerDAO, in Dai. /// We can borrow (ink * spot) function power() public view returns(uint256) { (,, uint256 spot,,) = _vat.ilks(WETH); // Collateralization ratio for Weth (uint256 ink,) = _vat.urns(WETH, address(this)); // Treasury Weth collateral in MakerDAO return muld(ink, spot); } /// @dev Returns the amount of chai in this contract, converted to Dai. function savings() public view override returns(uint256){ return muld(_chai.balanceOf(address(this)), _pot.chi()); } /// @dev Takes dai from user and pays as much system debt as possible, saving the rest as chai. /// User needs to have approved Treasury to take the Dai. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to take Dai from. /// @param daiAmount Dai quantity to take. function pushDai(address from, uint256 daiAmount) public override onlyOrchestrated("Treasury: Not Authorized") onlyLive { require(_dai.transferFrom(from, address(this), daiAmount)); // Take dai from user to Treasury // Due to the DSR being mostly lower than the SF, it is better for us to // immediately pay back as much as possible from the current debt to // minimize our future stability fee liabilities. If we didn't do this, // the treasury would simultaneously owe DAI (and need to pay the SF) and // hold Chai, which is inefficient. uint256 toRepay = Math.min(debt(), daiAmount); if (toRepay > 0) { _daiJoin.join(address(this), toRepay); // Remove debt from vault using frob (, uint256 rate,,,) = _vat.ilks(WETH); // Retrieve the MakerDAO stability fee _vat.frob( WETH, address(this), address(this), address(this), 0, // Weth collateral to add -toInt(divd(toRepay, rate)) // Dai debt to remove ); } uint256 toSave = daiAmount - toRepay; // toRepay can't be greater than dai if (toSave > 0) { _chai.join(address(this), toSave); // Give dai to Chai, take chai back } } /// @dev Takes Chai from user and pays as much system debt as possible, saving the rest as chai. /// User needs to have approved Treasury to take the Chai. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to take Chai from. /// @param chaiAmount Chai quantity to take. function pushChai(address from, uint256 chaiAmount) public override onlyOrchestrated("Treasury: Not Authorized") onlyLive { require(_chai.transferFrom(from, address(this), chaiAmount)); uint256 dai = _chai.dai(address(this)); uint256 toRepay = Math.min(debt(), dai); if (toRepay > 0) { _chai.draw(address(this), toRepay); // Grab dai from Chai, converted from chai _daiJoin.join(address(this), toRepay); // Remove debt from vault using frob (, uint256 rate,,,) = _vat.ilks(WETH); // Retrieve the MakerDAO stability fee _vat.frob( WETH, address(this), address(this), address(this), 0, // Weth collateral to add -toInt(divd(toRepay, rate)) // Dai debt to remove ); } // Anything that is left from repaying, is chai savings } /// @dev Takes Weth collateral from user into the Treasury Maker vault /// User needs to have approved Treasury to take the Weth. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to take Weth from. /// @param wethAmount Weth quantity to take. function pushWeth(address from, uint256 wethAmount) public override onlyOrchestrated("Treasury: Not Authorized") onlyLive { require(_weth.transferFrom(from, address(this), wethAmount)); _wethJoin.join(address(this), wethAmount); // GemJoin reverts if anything goes wrong. // All added collateral should be locked into the vault using frob _vat.frob( WETH, address(this), address(this), address(this), toInt(wethAmount), // Collateral to add - WAD 0 // Normalized Dai to receive - WAD ); } /// @dev Returns dai using chai savings as much as possible, and borrowing the rest. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to send Dai to. /// @param daiAmount Dai quantity to send. function pullDai(address to, uint256 daiAmount) public override onlyOrchestrated("Treasury: Not Authorized") onlyLive { uint256 toRelease = Math.min(savings(), daiAmount); if (toRelease > 0) { _chai.draw(address(this), toRelease); // Grab dai from Chai, converted from chai } uint256 toBorrow = daiAmount - toRelease; // toRelease can't be greater than dai if (toBorrow > 0) { (, uint256 rate,,,) = _vat.ilks(WETH); // Retrieve the MakerDAO stability fee // Increase the dai debt by the dai to receive divided by the stability fee // `frob` deals with "normalized debt", instead of DAI. // "normalized debt" is used to account for the fact that debt grows // by the stability fee. The stability fee is accumulated by the "rate" // variable, so if you store Dai balances in "normalized dai" you can // deal with the stability fee accumulation with just a multiplication. // This means that the `frob` call needs to be divided by the `rate` // while the `GemJoin.exit` call can be done with the raw `toBorrow` // number. _vat.frob( WETH, address(this), address(this), address(this), 0, toInt(divdrup(toBorrow, rate)) // We need to round up, otherwise we won't exit toBorrow ); _daiJoin.exit(address(this), toBorrow); // `daiJoin` reverts on failures } require(_dai.transfer(to, daiAmount)); // Give dai to user } /// @dev Returns chai using chai savings as much as possible, and borrowing the rest. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to send Chai to. /// @param chaiAmount Chai quantity to send. function pullChai(address to, uint256 chaiAmount) public override onlyOrchestrated("Treasury: Not Authorized") onlyLive { uint256 chi = _pot.chi(); uint256 daiAmount = muld(chaiAmount, chi); // dai = price * chai uint256 toRelease = Math.min(savings(), daiAmount); // As much chai as the Treasury has, can be used, we borrwo dai and convert it to chai for the rest uint256 toBorrow = daiAmount - toRelease; // toRelease can't be greater than daiAmount if (toBorrow > 0) { (, uint256 rate,,,) = _vat.ilks(WETH); // Retrieve the MakerDAO stability fee // Increase the dai debt by the dai to receive divided by the stability fee _vat.frob( WETH, address(this), address(this), address(this), 0, toInt(divdrup(toBorrow, rate)) // We need to round up, otherwise we won't exit toBorrow ); // `vat.frob` reverts on failure _daiJoin.exit(address(this), toBorrow); // `daiJoin` reverts on failures _chai.join(address(this), toBorrow); // Grab chai from Chai, converted from dai } require(_chai.transfer(to, chaiAmount)); // Give dai to user } /// @dev Moves Weth collateral from Treasury controlled Maker Eth vault to `to` address. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to send Weth to. /// @param wethAmount Weth quantity to send. function pullWeth(address to, uint256 wethAmount) public override onlyOrchestrated("Treasury: Not Authorized") onlyLive { // Remove collateral from vault using frob _vat.frob( WETH, address(this), address(this), address(this), -toInt(wethAmount), // Weth collateral to remove - WAD 0 // Dai debt to add - WAD ); _wethJoin.exit(to, wethAmount); // `GemJoin` reverts on failures } /// @dev Registers the one contract that will take assets from the Treasury if MakerDAO shuts down. /// This function can only be called by the contract owner, which should only be possible during deployment. /// This function allows Unwind to take all the Chai savings and operate with the Treasury MakerDAO vault. /// @param unwind_ The address of the Unwild.sol contract. function registerUnwind(address unwind_) public onlyOwner { require( _unwind == address(0), "Treasury: Unwind already set" ); _unwind = unwind_; _chai.approve(address(_unwind), uint256(-1)); // Unwind will never cheat on us _vat.hope(address(_unwind)); // Unwind will never cheat on us } }
  Y i e l d 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   August 21, 2020                           Prepared For:     Allan Niemerg | ​ Yield   allan@yield.is       Prepared By:     Gustavo Grieco | ​ Trail of Bits   gustavo.grieco@trailofbits.com       Michael Colburn | ​ Trail of Bits   michael.colburn@trailofbits.com            Executive Summary   Project Dashboard   Code Maturity Evaluation   Engagement Goals   Coverage   Automated Testing and Verification   System properties   General properties   ABDK arithmetic properties   YieldMath properties   Recommendations Summary   Short term   Long term   Findings Summary   1. Flash minting can be used to redeem fyDAI   2. Permission-granting is too simplistic and not flexible enough   3. pot.chi() value is never updated   4. Lack of validation when setting the maturity value   5. Delegates can be added or removed repeatedly to bloat logs   6. Withdrawing from the Controller allows accounts to contain dust   7. Solidity compiler optimizations can be dangerous   8. Lack of chainID validation allows signatures to be re-used across forks   9. Permit opens the door for griefing contracts that interact with the Yield Protocol   10. Pool initialization is unprotected   11. Computation of DAI/fyDAI to buy/sell is imprecise   A. Vulnerability Classifications   B. Code Maturity Classifications   C. Code Quality Recommendations   General   Controller   Liquidations   D. Fix Log   Detailed fix log     © 2020 Trail of Bits   Yield Protocol Assessment | 1      E x e c u t i v e S u m m a r y   From August 3 through August 21, 2020, Yield engaged Trail of Bits to review the security of   the Yield Protocol. Trail of Bits conducted this assessment over the course of six   person-weeks with two engineers working from commit hash ​ 4422fda ​ from the   yieldprotocol/fyDai ​ repository.     Week one: ​ We familiarized ourselves with the codebase and whitepapers. We also began   checking for common Solidity flaws and identifying areas that would benefit from   tool-assisted analysis.       Week two: ​ We continued manual review of the various Yield Protocol contracts, focusing   on interactions between the different contracts as well as with the external MakerDAO   system. We also began to develop properties for Echidna.       Final week: ​ As we concluded our manual review, we focused on the custom arithmetic   libraries, the Pool market maker, and Unwind contracts, and finalized the set of properties   that were tested.     Our review resulted in 11 findings ranging from high to informational severity.     Interestingly, the issues we found do not have any particularity in common: They affect a   variety of different areas, but most of them allow us to break some internal invariants, e.g.,   the redemption of more ​ fyDAI ​ tokens than expected (​ TOB-YP-001​ ), the use of invalid   maturity values (​ TOB-YP-004​ ), or only dust amounts of assets remaining in the controller   accounts (​ TOB-YP-006​ ). We also make several code quality recommendations in ​ Appendix   C​ .     During the assessment, Yield provided fixes for issues when possible. Trail of Bits verified   the fixes for ​ TOB-YP-002​ , ​ TOB-YP-005​ , and ​ TOB-YP-006​ , as well as a partial fix for   TOB-YP-001​ .       Overall, the code follows a high-quality software development standard and best practices.   It has suitable architecture and is properly documented. The interactions between   components are well-defined. The functions are small, with a clear purpose.     Trail of Bits recommends addressing the findings presented and integrating the   property-based testing into the codebase. Yield must be careful with the deployment of the   contracts and the interactions of its early users and their advantages. Finally, we   recommend performing an economic assessment to make sure the monetary incentives   are properly designed.       © 2020 Trail of Bits   Yield Protocol Assessment | 2      Update: On September 14, 2020, Trail of Bits reviewed fixes proposed by Yield for the issues   presented in this report. See a detailed review of the current status of each issue in ​ Appendix D​ .     The name of the yDAI token was changed to fyDAI subsequent to our assessment but prior to the   finalization of this report. The report has been modified such that all references to the “yDAI”   token were replaced with “fyDAI”. However, all references to source code artifacts (e.g., smart   contract names such as YDai) remain as they were in the assessed version of the codebase.       © 2020 Trail of Bits   Yield Protocol Assessment | 3      P r o j e c t D a s h b o a r d   Application Summary   Name   Yield Protocol   Version   4422fda Type   Solidity   Platforms   Ethereum     Engagement Summary   Dates   August 3–August 21, 2020   Method   Whitebox   Consultants Engaged   2   Level of Effort   6 person-weeks     Vulnerability Summary     Total High-Severity Issues   1   ◼   Total Medium-Severity Issues   1   ◼   Total Low-Severity Issues   5   ◼ ◼ ◼ ◼ ◼   Total Informational-Severity Issues   2   ◼ ◼   Total Undetermined-Severity Issues   2   ◼ ◼   Total   11         Category Breakdown   Undefined Behavior   2   ◼ ◼   Access Controls   3   ◼ ◼ ◼   Data Validation   4   ◼ ◼ ◼ ◼   Auditing and Logging   1   ◼   Timing   1   ◼   Total   11           © 2020 Trail of Bits   Yield Protocol Assessment | 4      C o d e M a t u r i t y E v a l u a t i o n   In the table below, we review the maturity of the codebase and the likelihood of future   issues. In each area of control, we rate the maturity from strong to weak, or missing, and   give a brief explanation of our reasoning.     Category Name   Description   Access Controls   Satisfactory.​ Appropriate access controls were in place for   performing privileged operations.   Arithmetic   Satisfactory.​ The contracts included use of safe arithmetic and   casting functions. No potential overflows were possible in areas   where these functions were not used.     Assembly Use   Strong.​ The contracts only used assembly to fetch the ​ chainID ​ for   ERC2612 ​ permit ​ functionality.   Centralization   Satisfactory. ​ While the protocol relied on an owner to correctly   deploy the initial contracts, ownership could be renounced later and   users would verify this using on-chain events.   Contract   Upgradeability Not Applicable.​ The contracts contained no upgradeability   mechanisms.   Function   Composition   Strong.​ Functions and contracts were organized and scoped   appropriately.   Front-Running   Satisfactory.​ Although some functionality could have been affected   by front-running attacks, the impact was low.   Monitoring Satisfactory. ​ The events produced by the smart contract code were   sufficient to monitor on-chain activity.   Specification   Satisfactory.​ White papers describing the functionality of the   protocol and accompanying pool were available. The contract source   code included NatSpec comments for all contracts and functions.   Testing &   Verification   Moderate.​ While the contracts included a large number of unit tests,   the testing did not include any use of automatic tools such as   fuzzers.           © 2020 Trail of Bits   Yield Protocol Assessment | 5      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 Yield Protocol smart   contracts in the ​ yieldprotocol/fyDAI ​ repository.     Specifically, we sought to answer the following questions:     ● Are appropriate access controls set for the user and the smart contract interactions?   ● Does arithmetic regarding token minting, burning, and pool operations hold?   ● Is there any arithmetic overflow or underflow affecting the code?   ● Can participants manipulate or block tokens or pool operations?   ● Is it possible to manipulate the pools by front-running transactions?   ● Is it possible for participants to steal or lose tokens?   ● Can participants perform denial-of-service or phishing attacks against any of the   components?   C o v e r a g e     Controller.​ The Controller contract contains the main business logic and acts as the entry   point for users within the Yield Protocol. It allows users to manage collateral and debt   levels. We manually reviewed the contract's interactions with the MakerDAO system to   ensure proper behavior. We also used property-based testing tools to make sure its   invariants held and users were able to perform operations with the contract without   unexpected reverts.     YDai ​ . ​ The​ ​ YDai ​ contract implements an ERC20 token that allows a user to mint tokens by   locking up their ​ Dai ​ until a fixed maturity date. These tokens can then be bought or sold to   other users and later redeemed for ​ Dai ​ . This contract also implements a standard ERC20   token. We verified that all of the expected ERC20 properties hold. Additionally, we   conducted a manual review to ensure the flash-minting feature cannot be abused to   manipulate the protocol’s expected behavior.     Treasury. ​ The Treasury contract manages asset transfers between all contracts in the Yield   Protocol and other external contracts such as Chai and MakerDAO. Since users do not use   the Treasury contract directly, we manually reviewed all of its interactions with other smart   contracts of the protocol as well as its access control system to make sure external users   cannot interfere with it.     Liquidations. ​ The Liquidations contract allows liquidation of undercollateralized vaults   using a reverse Dutch auction mechanism. We manually reviewed exactly how and when     © 2020 Trail of Bits   Yield Protocol Assessment | 6      each user could be liquidated by any other user, and how the Liquidations contract   interacts with the rest of the system.     Unwind.​ The Unwind contract allows users to recover their assets from the Yield Protocol   in the event of a MakerDAO shutdown. We manually reviewed this contract to ensure that   it can only be used after the shutdown and that users will receive their corresponding   collateral.     Pool. ​ The Pool contract implements an automatic market maker that exchanges ​ DAI ​ for   fyDAI ​ at a price defined by a specific formula that also incorporates time to maturity. We   manually reviewed this contract for common flaws affecting exchanges, including incorrect   price computation, market manipulation, and front-running.       Access controls.​ Many parts of the system expose privileged functionality, such as setting   protocol parameters or minting/burning tokens. We reviewed these functions to ensure   they can only be triggered by the intended actors and that they do not contain unnecessary   privileges that may be abused.     Arithmetic.​ We reviewed calculations for logical consistency, as well as rounding issues   and scenarios where reverts due to overflow may negatively impact use of the protocol.     During the course of the assessment the Yield Protocol team made several pull requests   that we also reviewed in addition to the version listed in the Project Dashboard: ​ 246​ , ​ 247​ ,   251​ , ​ 252​ , ​ 253​ , ​ 254​ , ​ 268​ , ​ 271​ , and ​ 279​ .     Contracts located in the ​ external ​ , ​ mocks ​ , and ​ peripheral ​ directories were out of scope for   this review.         © 2020 Trail of Bits   Yield Protocol Assessment | 7      A u t o m a t e d T e s t i n g a n d V e r i f i c a t i o n   To enhance coverage of certain areas of the contracts, Trail of Bits used automated testing   techniques, including:     ● Slither​ , a Solidity static analysis framework. Slither can statically verify algebraic   relationships between Solidity variables. We used Slither to detect common flaws   across the entire codebase.   ● Echidna​ , a smart contract fuzzer. Echidna can rapidly test security properties via   malicious, coverage-guided test case generation. We used Echidna to test the   expected system properties of the Controller contract and its dependencies.   ● Manticore​ , a symbolic execution framework. Manticore can exhaustively test   security properties via symbolic execution.       Automated testing techniques augment our manual security review but do not replace it.   Each technique has limitations:       ● Slither may identify security properties that fail to hold when Solidity is compiled to   EVM bytecode.   ● Echidna may not randomly generate an edge case that violates a property.   ● Manticore may fail to complete its analysis.       To mitigate these risks, we generate 50,000 test cases per property with Echidna, run   Manticore for a minimum of one hour, and then manually review all results.   S y s t e m p r o p e r t i e s   System properties can be broadly divided into two categories: general properties of the   contracts that state what users can and cannot do, and arithmetic properties for the ABDK   and the ​ YieldMath ​ libraries.       Additionally, properties can have three outcomes: Either the verification fails (and we list   the corresponding issue), it passes after 50,000 Echidna tests, or it’s formally verified using   Manticore.   G e n e r a l p r o p e r t i e s   #   Property   Result   1   Calling ​ erase ​ in the Controller never reverts.   PASSED   2   Calling ​ locked ​ in the Controller never reverts.   PASSED     © 2020 Trail of Bits   Yield Protocol Assessment | 8      3   Calling ​ powerOf ​ in the Controller never reverts.   PASSED   4   Calling ​ totalDebtDai ​ in the Controller never reverts.   PASSED   5   Posting, borrowing, repaying, and withdrawing using ​ CHAI ​ as   collateral properly updates the state variables.     PASSED   6   Posting, borrowing, repaying, and withdrawing using ​ WETH ​ as   collateral properly updates the state variables.   PASSED   7   All the WETH balances are above dust or zero in the   Controller.   FAILED​ (​ TOB-YP-006​ )   8   All the WETH balances are above dust or zero in the   Liquidations.   PASSED   9   Calling ​ price ​ never reverts on Liquidations   PASSED   10   Transferring tokens to the null address (​ 0x0 ​ ) causes a revert.   PASSED   11   The null address (​ 0x0 ​ ) owns no tokens.   PASSED   12   Transferring a valid amount of tokens to a non-null address   reduces the current balance.   PASSED   13   Transferring an invalid amount of tokens to a non-null   address reverts or returns false.   PASSED   14   Self-transferring a valid amount of tokens keeps the current   balance constant.   PASSED   15   Approving overwrites the previous allowance value.   PASSED   16   The balances are consistent with the ​ totalSupply ​ .   PASSED   17   Burning all the balance of a user resets it zero.   PASSED   18   Burning more than the balance of a user reverts.   PASSED     A B D K a r i t h m e t i c p r o p e r t i e s   #   Property   Result   1   Addition is associative.   VERIFIED   2   Zero is the identity element in addition.   VERIFIED   3   Zero is the identity element in subtraction.   VERIFIED     © 2020 Trail of Bits   Yield Protocol Assessment | 9      4   Subtracting a number from itself is zero.   VERIFIED   5   Negation operation is the same as subtracting from zero.   VERIFIED   6   Negation operation is inverse to itself.   VERIFIED   7   One is the identity element in multiplication.   PASSED   8   Zero is the absorbing element in multiplication.   PASSED   9   Square root is the inverse of multiplying a number by itself.   PASSED   10   Multiplication and addition give consistent results.     PASSED   Y i e l d M a t h p r o p e r t i e s   #   Property   Result   1   yDaiOutForDaiIn ​ and ​ daiInForYDaiOut ​ are inverse   functions.   FAILED​ (​ TOB-YP-011​ )   2   daiOutForYDaiIn ​ and ​ yDaiInForDaiOut ​ are inverse   functions.   FAILED​ (​ TOB-YP-011​ )         © 2020 Trail of Bits   Yield Protocol 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   ❑ Disallow calls to ​ redeem ​ in the ​ YDai ​ and ​ Unwind ​ contracts during flash minting.​ This   will prevent users from abusing the flash minting feature. (​ TOB-YP-001​ )     ❑ Rewrite the authorization system to allow only certain addresses to access certain   functions.​ This will increase users’ confidence in the deployment of the contracts.   (​ TOB-YP-002​ )     ❑ Add a call to ​ pot.drip ​ every time the ​ pot.chi ​ is used. ​ This will ensure that users   receive the correct amount of interest after maturation​ .​ (​ TOB-YP-003​ )     ❑ Add checks to the ​ YDai ​ contract constructor to ensure maturity timestamps fall   within an acceptable range.​ This will prevent maturity dates from being mistakenly set in   the past or too far in the future. (​ TOB-YP-004​ )     ❑ Add a ​ require ​ statement to check that the delegate address is not already enabled   or disabled for the user.​ This will ensure log messages are only emitted when a delegate   is activated or deactivated. (​ TOB-YP-005​ )     ❑ Enforce the ​ aboveDustOrZero ​ function in the ​ from ​ address instead of the ​ to   address, after modifying its balance during the ​ withdraw ​ call.​ This will ensure the   correct address has an appropriate balance after calls to ​ withdraw ​ . (​ TOB-YP-006​ )     ❑ Measure the gas savings from optimizations,​ and carefully weigh them against the   possibility of an optimization-related bug. (​ TOB-YP-007​ )     ❑ Include the ​ chainID ​ opcode in the ​ permit ​ schema.​ This will make replay attacks   impossible in the event of a post-deployment hard fork.​ ​ (​ TOB-YP-008​ )     ❑ Properly document the possibility of griefing ​ permit ​ calls to warn users interacting   with ​ fyDAI ​ tokens.​ This will allow users to anticipate this possibility and develop alternate   workflows in case they are targeted by it. (​ TOB-YP-009​ )       © 2020 Trail of Bits   Yield Protocol Assessment | 11      ❑ Consider restricting calls to ​ init ​ to the contract owner and enforce that it can   only be called once.​ This will ensure initialization is carried out as Yield intends.   (​ TOB-YP-010​ )     ❑ Review the specification of the ​ YieldMath ​ functions and make sure it matches the   implementation.​ Use Echidna to validate the implementation. (​ TOB-YP-011​ )     L o n g t e r m   ❑ Do not include operations that allow any user to manipulate an arbitrary amount   of funds, even if it is in a single transaction.​ This will prevent attackers from gaining   leverage to manipulate the market and break internal invariants. (​ TOB-YP-001​ )     ❑ Review the rest of the components to make sure they are suitable for their   purpose and can be used only for their intended purpose.​ (​ TOB-YP-002​ ), (​ TOB-YP-010​ )     ❑ Review every interaction with the MakerDAO contracts to make sure your code   will work as expected.​ (​ TOB-YP-003​ )     ❑ Always perform validation of parameters passed to contract constructors.​ This will   help detect and prevent errors during deployment. (​ TOB-YP-004​ )     ❑ Review all operations and avoid emitting events in repeated calls to idempotent   operations.​ This will help prevent bloated logs. (​ TOB-YP-005​ )     ❑ Use Echidna or Manticore to properly test the contract invariants.​ Automated   testing can cover a wide array of inputs that unit testing may miss. (​ TOB-YP-006​ )     ❑ ​ ​ Monitor the development and adoption of Solidity compiler optimizations.​ This will   allow you to assess their maturity and whether they are appropriate to enable.   (​ TOB-YP-007​ )     ❑ Document and carefully review any signature schemas, including their robustness   to replay on different wallets, contracts, and blockchains.​ Make sure users are aware   of signing best practices and the danger of signing messages from untrusted sources.   (​ TOB-YP-008​ )     ❑ Carefully monitor the blockchain to detect front-running attempts.​ (​ TOB-YP-009​ )     ❑ Develop robust unit and automated test suites for the custom math functions.   This will help ensure the correct functionality of this complex arithmetic. (​ TOB-YP-011​ )       © 2020 Trail of Bits   Yield Protocol Assessment | 12        F i n d i n g s S u m m a r y   #   Title   Type   Severity   1   Flash minting can be used to redeem   fyDAI Undefined   Behavior   Medium   2   Permission-granting is too simplistic and   not flexible enough   Access Controls   Low   3   pot.chi() ​ value is never updated   Data Validation   Low   4   Lack of validation when setting the   maturity value   Data Validation   Low   5   Delegates can be added or removed   repeatedly to bloat logs   Auditing and   Logging   Informational   6   Withdrawing from the controller allows   accounts to contain dust   Data Validation   Low   7   Solidity compiler optimizations can be   dangerous   Undefined   Behavior   Undetermined   8   Lack of ​ chainID ​ validation allows   signatures to be re-used across forks   Access Controls   High   9   Permit opens the door for griefing   contracts that interact with the Yield   Protocol   Timing   Informational   10   Pool initialization is unprotected   Access Controls   Low   11   Computation of ​ DAI ​ /​ fyDAI ​ to buy/sell is   imprecise     Data Validation   Undetermined           © 2020 Trail of Bits   Yield Protocol Assessment | 13      1 . F l a s h m i n t i n g c a n b e u s e d t o r e d e e m ​ fyDAI Severity: Medium Difficulty: Medium   Type: Undefined Behavior Finding ID: TOB-YP-001   Target: ​ YDai.sol, Unwind.sol   Description   The flash-minting feature from the ​ fyDAI ​ token can be used to redeem an arbitrary   amount of funds from a mature token.     The ​ fyDAI ​ token has a special function that allows users to mint and burn an arbitrary   amount of tokens in a single transaction:     ​ /// @dev Flash-mint yDai. Calls back on `IFlashMinter.executeOnFlashMint()` ​ /// @param to Wallet to mint the yDai in. ​ /// @param yDaiAmount Amount of yDai to mint. ​ /// @param data User-defined data to pass on to `executeOnFlashMint()` ​ function ​ flashMint ​ ( ​ address ​ ​ to ​ , ​ uint256 ​ ​ yDaiAmount ​ , ​ bytes ​ ​ calldata ​ ​ data ​ ) ​ external ​ ​ override { ​ _mint ​ (to, yDaiAmount); ​ IFlashMinter ​ ( ​ msg ​ . ​ sender ​ ). ​ executeOnFlashMint ​ (to, yDaiAmount, data); ​ _burn ​ (to, yDaiAmount); } Figure 1.1: ​ flashMint ​ function in ​ YDai.sol ​ .     This function allows an arbitrary contract to be called with the ​ executeOnFlashMint   interface. This arbitrary contract can then call any function. In particular, it can call ​ redeem   from the same contract if the token is mature:     function ​ redeem ​ ( ​ address ​ ​ from ​ , ​ address ​ ​ to ​ , ​ uint256 ​ ​ yDaiAmount ​ ) ​ public ​ ​ onlyHolderOrDelegate ​ (from, ​ "YDai: Only Holder Or Delegate" ​ ) { ​ require ​ ( isMature ​ == ​ ​ true ​ , ​ "YDai: yDai is not mature" ); ​ _burn ​ (from, yDaiAmount); ​ // Burn yDai from `from` ​ uint256 ​ daiAmount = ​ muld ​ (yDaiAmount, ​ chiGrowth ​ ()); ​ // User gets interest for holding after maturity _treasury. ​ pullDai ​ (to, daiAmount); ​ // Give dai to `to`, from Treasury ​ emit ​ ​ Redeemed ​ (from, to, yDaiAmount, daiAmount);   © 2020 Trail of Bits   Yield Protocol Assessment | 14      } Figure 1.2: ​ redeem ​ ​ function in ​ YDai.sol ​ .     The same transaction can also pull an arbitrary number of funds from the treasure (if   available), which can be deposited to mint ​ fyDAI ​ tokens again.       Additionally, this attack could also target the ​ redeem ​ function in the ​ Unwind ​ contract in the   event of a MakerDAO shutdown:     ​ /// @dev Redeems YDai for weth for any user. YDai.redeem won't work if MakerDAO is in shutdown. ​ /// @param maturity Maturity of an added series ​ /// @param user Wallet containing the yDai to burn. ​ function ​ redeem ​ ( ​ uint256 ​ ​ maturity ​ , ​ address ​ ​ user ​ ) ​ public ​ { ​ require ​ (settled ​ && ​ cashedOut, ​ "Unwind: Not ready" ​ ); IYDai yDai ​ = ​ _controller. ​ series ​ (maturity); ​ uint256 ​ yDaiAmount = yDai. ​ balanceOf ​ (user); yDai. ​ burn ​ (user, yDaiAmount); ​ require ​ ( _weth. ​ transfer ​ ( user, ​ daiToFixWeth ​ ( ​ muld ​ (yDaiAmount, yDai. ​ chiGrowth ​ ()), _fix) ) ); } Figure 1.3: ​ redeem ​ function in ​ Unwind.sol ​ .     Exploit Scenario   Eve calls ​ flashMint ​ on a ​ YDai ​ contract that has already matured and mints a large quantity   of tokens to a contract she controls. This contract's ​ executeOnFlashMint ​ hook in turn calls   redeem ​ in the matured ​ YDai ​ contract, and Eve’s contract receives a large quantity of ​ Dai ​ .   Eve's contract may now negatively impact markets to her advantage.     Recommendation   Short term, disallow calls to ​ redeem ​ in the ​ YDai ​ and ​ Unwind ​ contracts during flash minting.     Long term, do not include operations that allow any user to manipulate an arbitrary   amount of funds, even if it is in a single transaction. This will prevent attackers from gaining   leverage to manipulate the market and break internal invariants.       © 2020 Trail of Bits   Yield Protocol Assessment | 15      2 . P e r m i s s i o n - g r a n t i n g i s t o o s i m p l i s t i c a n d n o t f l e x i b l e e n o u g h   Severity: Low Difficulty: High   Type: Access Controls Finding ID: TOB-YP-002   Target: ​ Orchestrated.sol   Description   The Yield Protocol contracts implement an oversimplified permission system that can be   abused by the administrator.     The Yield Protocol implements several contracts that need to call privileged functions from   each other. For instance, only the ​ borrow ​ function in Controller can call the ​ mint ​ function in   YDai ​ :     ​ function ​ borrow ​ ( ​ bytes32 ​ ​ collateral ​ , ​ uint256 ​ ​ maturity ​ , ​ address ​ ​ from ​ , ​ address ​ ​ to ​ , ​ uint256 yDaiAmount ​ ) ​ public ​ ​ override ​ validCollateral ​ (collateral) ​ validSeries ​ (maturity) ​ onlyHolderOrDelegate ​ (from, ​ "Controller: Only Holder Or Delegate" ​ ) onlyLive { IYDai yDai ​ = ​ series[maturity]; debtYDai[collateral][maturity][from] ​ = debtYDai[collateral][maturity][from]. ​ add ​ (yDaiAmount); ​ require ​ ( ​ isCollateralized ​ (collateral, from), ​ "Controller: Too much debt" ); yDai. ​ mint ​ (to, yDaiAmount); ​ emit ​ ​ Borrowed ​ (collateral, maturity, from, ​ toInt256 ​ (yDaiAmount)); } Figure 2.1: ​ borrow ​ function in ​ Controller.sol ​ .     ​ /// @dev Mint yDai. Only callable by Controller contracts. ​ /// This function can only be called by other Yield contracts, not users directly. ​ /// @param to Wallet to mint the yDai in. ​ /// @param yDaiAmount Amount of yDai to mint. ​ function ​ mint ​ ( ​ address ​ ​ to ​ , ​ uint256 ​ ​ yDaiAmount ​ ) ​ public ​ ​ override ​ ​ onlyOrchestrated ​ ( ​ "YDai: Not   © 2020 Trail of Bits   Yield Protocol Assessment | 16      Authorized" ​ ) { ​ _mint ​ (to, yDaiAmount); } Figure 2.2: ​ mint ​ function in ​ YDai.sol ​ .     For implementing permissions, there is a special function called ​ orchestrate ​ which allows   certain addresses to be added into the list of authorized users:     contract ​ Orchestrated ​ is ​ Ownable ​ { ​ event ​ GrantedAccess ​ ( ​ address ​ ​ access ​ ); ​ mapping ​ ( ​ address ​ => ​ bool ​ ) ​ public ​ authorized; ​ constructor ​ () ​ public ​ ​ Ownable ​ () {} ​ /// @dev Restrict usage to authorized users ​ modifier ​ onlyOrchestrated ​ ( ​ string ​ ​ memory ​ ​ err ​ ) { ​ require ​ (authorized[ ​ msg ​ . ​ sender ​ ], err); _; } ​ /// @dev Add user to the authorized users list ​ function ​ orchestrate ​ ( ​ address ​ ​ user ​ ) ​ public ​ onlyOwner { authorized[user] ​ = ​ ​ true ​ ; ​ emit ​ ​ GrantedAccess ​ (user); } } Figure 2.2: ​ Orchestrated ​ contract.     However, there is no way to specify which operation can be called for every privileged user.   All the authorized addresses can call any restricted function, and the owner can add any   number of them. Also, the privileged addresses are supposed to be smart contracts;   however, there is no check for that. Moreover, once an address is added, it cannot be   deleted.     Exploit Scenario   Eve gains access to the owner's private key and uses it to call the ​ orchestrate ​ function   with an additional address to backdoor one of the contracts. As a result, any user   interacting with the contracts is advised to review the ​ authorized ​ mapping to make sure   the contracts don’t allow additional addresses to call restricted functions.     Recommendation   Short term, rewrite the authorization system to allow only certain addresses to access   certain functions (e.g., the minter address can only call ​ mint ​ in ​ YDai ​ ).     © 2020 Trail of Bits   Yield Protocol Assessment | 17        Long term, review the rest of the components to make sure they are suitable for their   purpose and can be used only for their intended purpose.         © 2020 Trail of Bits   Yield Protocol Assessment | 18      3 . ​ pot.chi() ​ v a l u e i s n e v e r u p d a t e d   Severity: Low Difficulty: High   Type: Data Validation Finding ID: TOB-YP-003   Target: ​ YDai.sol   Description   The Yield contracts interact with the Dai Savings Rate (DSR) contracts from MakerDAO to   obtain the rate accumulator value without properly calling a function to update its value.     DSR works using the ​ pot ​ contracts from MakerDAO. Once these contracts are deployed,   they require the ​ drip ​ function to be called in order to update the accumulated interest   rate:     Figure 3.1: ​ pot ​ documentation at ​ MakerDAO.     The Yield Protocol uses DSR. In particular, ​ YDai ​ uses the pot contracts directly to provide   interest to its users:     ​ /// @dev Mature yDai and capture chi and rate ​ function ​ mature ​ () ​ public ​ ​ override ​ { ​ require ​ ( ​ // solium-disable-next-line security/no-block-members ​ now ​ ​ > ​ maturity, ​ "YDai: Too early to mature" ); ​ require ​ (   © 2020 Trail of Bits   Yield Protocol Assessment | 19      isMature ​ != ​ ​ true ​ , ​ "YDai: Already matured" ); (, rate0,,,) ​ = ​ _vat. ​ ilks ​ (WETH); ​ // Retrieve the MakerDAO Vat rate0 ​ = ​ Math. ​ max ​ (rate0, UNIT); ​ // Floor it at 1.0 chi0 ​ = ​ _pot. ​ chi ​ (); isMature ​ = ​ ​ true ​ ; ​ emit ​ ​ Matured ​ (rate0, chi0); } Figure 3.1: ​ mature ​ function in ​ YDai ​ .     However, the drip function is never called on any contract. It could be called manually by   the users or the Yield off-chain components; however, this was not documented.     Exploit Scenario   Alice locks ​ DAI ​ in a ​ fyDAI ​ token expecting to obtain a certain interest rate. However, the call   to ​ drip ​ is never performed, so Alice obtains less interest than expected after the ​ fyDAI   token matures.     Recommendation   Short term, add a call to ​ pot.drip ​ every time the ​ pot.chi ​ is used. This will ensure that   users receive the correct amount of interest after maturation​ .       Long term, review every interaction with the MakerDAO contracts to make sure your code   works as expected.         © 2020 Trail of Bits   Yield Protocol Assessment | 20      4 . L a c k o f v a l i d a t i o n w h e n s e t t i n g t h e m a t u r i t y v a l u e   Severity: Low Difficulty: Low   Type: Data Validation Finding ID: TOB-YP-004   Target: ​ YDai.sol   Description   When a ​ fyDAI ​ contract is deployed, one of the deployment parameters is a maturity date,   passed as a Unix timestamp. This is the date at which point ​ fyDAI ​ tokens can be redeemed   for the underlying ​ Dai ​ . Currently, the contract constructor performs no validation on this   timestamp to ensure it is within an acceptable range. As a result, it is possible to mistakenly   deploy a ​ YDai ​ contract that has a maturity date in the past or many years in the future,   which may not be immediately noticed.     ​ /// @dev The constructor: ​ /// Sets the name and symbol for the yDai token. ​ /// Connects to Vat, Jug, Pot and Treasury. ​ /// Sets the maturity date for the yDai, in unix time. ​ /// Initializes chi and rate at maturity time as 1.0 with 27 decimals. ​ constructor ​ ( ​ address ​ ​ vat_ ​ , ​ address ​ ​ pot_ ​ , ​ address ​ ​ treasury_ ​ , ​ uint256 ​ ​ maturity_ ​ , ​ string ​ ​ memory ​ ​ name ​ , string ​ memory ​ symbol ) ​ public ​ ​ ERC20 ​ (name, symbol) { _vat ​ = ​ ​ IVat ​ (vat_); _pot ​ = ​ ​ IPot ​ (pot_); _treasury ​ = ​ ​ ITreasury ​ (treasury_); maturity ​ = ​ maturity_; chi0 ​ = ​ UNIT; rate0 ​ = ​ UNIT; } Figure 4.1: The constructor of the ​ YDai ​ contract.     Exploit Scenario   The Yield Protocol team deploys a new suite of ​ YDai ​ contracts with a variety of target   maturity dates. One of the maturity timestamps contains a typo, and the maturity date is   set for 10 years from now instead of the intended 6 months. Before this is noticed by either   the team or the community, users begin locking up ​ fyDAI ​ in this longer-term contract.     Recommendation   Short term, add checks to the ​ YDai ​ contract constructor to ensure maturity timestamps fall   within an acceptable range. This will prevent maturity dates from being mistakenly set in   the past or too far in the future.     Long term, always perform validation of parameters passed to contract constructors. This   will help detect and prevent errors during deployment.         © 2020 Trail of Bits   Yield Protocol Assessment | 21      5 . D e l e g a t e s c a n b e a d d e d o r r e m o v e d r e p e a t e d l y t o b l o a t l o g s   Severity: Informational Difficulty: Low   Type: Auditing and Logging Finding ID: TOB-YP-005   Target: ​ helpers/Delegable.sol   Description   Several contracts in the Yield Protocol system inherit the ​ Delegable ​ contract. This contract   allows users to delegate the ability to perform certain operations on their behalf to other   addresses. When a user adds or removes a delegate, a corresponding event is emitted to   log this operation. However, there is no check to prevent a user from repeatedly adding or   removing a delegation that is already enabled or revoked, which could allow redundant   events to be emitted repeatedly.     ​ /// @dev Enable a delegate to act on the behalf of caller ​ function ​ addDelegate ​ ( ​ address ​ ​ delegate ​ ) ​ public ​ { delegated[ ​ msg ​ . ​ sender ​ ][delegate] ​ = ​ ​ true ​ ; ​ emit ​ ​ Delegate ​ ( ​ msg ​ . ​ sender ​ , delegate, ​ true ​ ); } ​ /// @dev Stop a delegate from acting on the behalf of caller ​ function ​ revokeDelegate ​ ( ​ address ​ ​ delegate ​ ) ​ public ​ { delegated[ ​ msg ​ . ​ sender ​ ][delegate] ​ = ​ ​ false ​ ; ​ emit ​ ​ Delegate ​ ( ​ msg ​ . ​ sender ​ , delegate, ​ false ​ ); } Figure 5.1: The ​ addDelegate ​ and ​ revokeDelegate ​ function definitions.     Exploit Scenario   Alice calls ​ addDelegate ​ on the Pool contract with Bob’s address several hundred times. For   each call, a new event is emitted. This bloats the event logs for the contract and degrades   performance of off-chain systems that ingest these events.     Recommendation   Short term, add a ​ require ​ statement to check that the delegate address is not already   enabled or disabled for the user. This will ensure log messages are only emitted when a   delegate is activated or deactivated.     Long term, review all operations and avoid emitting events in repeated calls to idempotent   operations. This will help prevent bloated logs.         © 2020 Trail of Bits   Yield Protocol Assessment | 22      6 . W i t h d r a w i n g f r o m t h e C o n t r o l l e r a l l o w s a c c o u n t s t o c o n t a i n d u s t   Severity: Low Difficulty: Low   Type: Data Validation Finding ID: TOB-YP-006   Target: ​ Controller.sol   Description   The ​ withdraw ​ operation can break the assumption that no account can contain dust for   certain collaterals.       The ​ aboveDustOrZero ​ function enforces an invariant that prevents accounts from holding   an amount of collateral smaller than ​ DUST ​ (0.025 ETH):     ​ /// @dev Return if the collateral of an user is between zero and the dust level ​ /// @param collateral Valid collateral type ​ /// @param user Address of the user vault ​ function ​ aboveDustOrZero ​ ( ​ bytes32 ​ ​ collateral ​ , ​ address ​ ​ user ​ ) ​ public ​ ​ view ​ ​ returns ​ ( ​ bool ​ ) { ​ uint256 ​ postedCollateral = posted[collateral][user]; ​ return ​ postedCollateral ​ == ​ ​ 0 ​ ​ || ​ DUST ​ < ​ postedCollateral; } Figure 6.1: ​ aboveDustOrZero ​ function in ​ Controller.sol ​ .     While this function is correctly used in the ​ post ​ operation, it fails to enforce this invariant in   withdraw ​ :     ​ function ​ withdraw ​ ( ​ bytes32 ​ ​ collateral ​ , ​ address ​ ​ from ​ , ​ address ​ ​ to ​ , ​ uint256 ​ ​ amount ​ ) ​ public ​ ​ override ​ validCollateral ​ (collateral) ​ onlyHolderOrDelegate ​ (from, ​ "Controller: Only Holder Or Delegate" ​ ) onlyLive { posted[collateral][from] ​ = ​ posted[collateral][from]. ​ sub ​ (amount); ​ // Will revert if not enough posted ​ require ​ ( ​ isCollateralized ​ (collateral, from), ​ "Controller: Too much debt" );   © 2020 Trail of Bits   Yield Protocol Assessment | 23      ​ if ​ (collateral ​ == ​ WETH){ ​ require ​ ( ​ aboveDustOrZero ​ (collateral, to), ​ "Controller: Below dust" ); _treasury. ​ pullWeth ​ (to, amount); } ​ else ​ ​ if ​ (collateral ​ == ​ CHAI) { _treasury. ​ pullChai ​ (to, amount); } ​ emit ​ ​ Posted ​ (collateral, from, ​ - ​ toInt256 ​ (amount)); } Figure 6.2: ​ withdraw ​ function in ​ Controller.sol ​ .     The invariant is enforced for the ​ to ​ address (which is not modified) instead of the ​ from   address.     Exploit Scenario   Alice calls ​ withdraw ​ on the Controller assuming that it cannot leave a positive amount of   WETH ​ that is lower than ​ DUST ​ in her account. However, the transaction succeeds, leaving the   contract in an invalid state.     Recommendation   Short term, enforce the ​ aboveDustOrZero ​ function in the ​ from ​ address instead of the ​ to   address, after modifying its balance during the ​ withdraw ​ call. This will ensure the correct   address has an appropriate balance after calls to ​ withdraw ​ .     Long term, use Echidna or Manticore to properly test the contract invariants. Automated   testing can cover a wide array of inputs that unit testing may miss.       © 2020 Trail of Bits   Yield Protocol Assessment | 24      7 . 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 d a n g e r o u s   Severity: Undetermined Difficulty: Low   Type: Undefined Behavior Finding ID: TOB-YP-007   Target: ​ truffle-config.js, buidler.config.ts Description   Yield Protocol has enabled optional compiler optimizations in Solidity.     There have been several bugs with security implications related to optimizations.   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​ .     A ​ compiler audit of Solidity​ from November, 2018 concluded that ​ the optional   optimizations may not be safe​ . Moreover, the Common Subexpression Elimination (CSE)   optimization procedure is “implemented in a very fragile manner, with manual access to   indexes, multiple structures with almost identical behavior, and up to four levels of   conditional nesting in the same function.” Similar code in other large projects has resulted   in bugs.     There are likely latent bugs related to optimization, and/or new bugs that 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 <> contracts.     Recommendation   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.       © 2020 Trail of Bits   Yield Protocol Assessment | 25      8 . ​ L a c k o f ​ chainID ​ v a l i d a t i o n a l l o w s s i g n a t u r e s t o b e r e - u s e d a c r o s s f o r k s   Severity: High Difficulty: High   Type: Access Controls Finding ID: TOB-YP-008   Target: ​ helpers/ERC20Permit.sol   Description   YDai ​ implements the draft ERC 2612 via the ​ ERC20Permit ​ contract it inherits from. This   allows a third party to transmit a signature from a token holder that modifies the ERC20   allowance for a particular user. These signatures used in calls to ​ permit ​ in ​ ERC20Permit ​ do   not account for chainsplits. The ​ chainID ​ is included in the domain separator. However, it is   not updatable and not included in the signed data as part of the ​ permit ​ call. As a result, if   the chain forks after deployment, the signed message may be considered valid on both   forks.   ​ bytes32 ​ hashStruct = ​ keccak256 ​ ( ​ abi ​ . ​ encode ​ ( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner] ​ ++ ​ , deadline ) ); Figure 8.1: The reconstruction of the permit parameters in ​ ERC20Permit ​ as signed by the ​ owner ​ ,   notably omitting the ​ chainID ​ .     Exploit Scenario   Bob has a wallet holding ​ fyDAI ​ . An EIP is included in an upcoming hard fork that has split   the community. After the hard fork, a significant user base remains on the old chain. On   the new chain, Bob approves Alice to spend some tokens via a call to ​ permit ​ . Alice,   operating on both chains, replays the ​ permit ​ call on the old chain and is able to steal some   of Bob’s ​ fyDAI ​ .     Recommendation   Short term, include the ​ chainID ​ opcode in the ​ permit ​ schema. This will make replay   attacks impossible in the event of a post-deployment hard fork.   Long term, document and carefully review any signature schemas, including their   robustness to replay on different wallets, contracts, and blockchains. Make sure users are   aware of signing best practices and the danger of signing messages from untrusted   sources.       © 2020 Trail of Bits   Yield Protocol Assessment | 26      9 . P e r m i t o p e n s t h e d o o r f o r g r i e f i n g c o n t r a c t s t h a t i n t e r a c t w i t h t h e Y i e l d   P r o t o c o l     Severity: Informational Difficulty: Low   Type: Timing Finding ID: TOB-YP-009   Target: ​ ERC20Permit.sol   Description   The ​ permit ​ function can be front-run to break the workflow from third-party smart   contracts.     The ​ YDai ​ contract implements ​ permit ​ , which allows the ERC20 allowance of a user to be   changed based on a signature check using ​ ecrecover ​ :     ​ function ​ permit ​ ( ​ address ​ ​ owner ​ , ​ address ​ ​ spender ​ , ​ uint256 ​ ​ amount ​ , ​ uint256 ​ ​ deadline ​ , ​ uint8 v ​ , ​ bytes32 ​ ​ r ​ , ​ bytes32 ​ ​ s ​ ) ​ public ​ ​ virtual ​ ​ override ​ { ​ require ​ (deadline ​ >= ​ ​ block ​ . ​ timestamp ​ , ​ "ERC20Permit: expired deadline" ​ ); ​ bytes32 ​ hashStruct = ​ keccak256 ​ ( ​ abi ​ . ​ encode ​ ( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner] ​ ++ ​ , deadline ) ); ​ bytes32 ​ hash = ​ keccak256 ​ ( ​ abi ​ . ​ encodePacked ​ ( ​ '\x19\x01' ​ , DOMAIN_SEPARATOR, hashStruct ) ); ​ address ​ signer = ​ ecrecover ​ (hash, v, r, s); ​ require ​ (   © 2020 Trail of Bits   Yield Protocol Assessment | 27      signer ​ != ​ ​ address ​ ( ​ 0 ​ ) ​ && ​ signer ​ == ​ owner, ​ "ERC20Permit: invalid signature" ); ​ _approve ​ (owner, spender, amount); } } Figure 9.1: ​ permit ​ ​ function in​ ​ ERC20Permit.sol ​ .     While this function is correctly implemented in terms of functionality, there is a potential   security issue users must be aware of when developing contracts to interact with ​ fyDAI   tokens:     ## Security Considerations Though the signer of a `Permit` may have a certain party in mind to submit their transaction, another party can always front run this transaction and call `permit` before the intended party. The end result is the same for the `Permit` signer, however. Figure 9.2: Security considerations for ERC2612.     Exploit Scenario   Alice develops a smart contract that leverages ​ permit ​ to perform a ​ transferFrom ​ of ​ fyDAI   without requiring a user to call ​ approve ​ first. Eve monitors the blockchain and notices this   call to ​ permit ​ . She observes the signature and replays it to front-run her call, which   produces a revert in Alice’s contract and halts its expected execution.       Recommendation   Short term, properly document the possibility of griefing ​ permit ​ calls to warn users   interacting with ​ fyDAI ​ tokens. This will allow users to anticipate this possibility and develop   alternate workflows in case they are targeted by it.     Long term, carefully monitor the blockchain to detect front-running attempts.           © 2020 Trail of Bits   Yield Protocol Assessment | 28      1 0 . P o o l i n i t i a l i z a t i o n i s u n p r o t e c t e d   Severity: Low Difficulty: High   Type: Access Controls Finding ID: TOB-YP-010   Target: ​ Pool.sol   Description   The Yield Pool contract implements a simple initialization system that can be abused by any   user.     The Pool contract needs to be initialized using an ​ init ​ function:     ​ /// @dev Mint initial liquidity tokens. ​ /// The liquidity provider needs to have called `dai.approve` ​ /// @param daiIn The initial Dai liquidity to provide. ​ function ​ init ​ ( ​ uint128 ​ ​ daiIn ​ ) ​ external beforeMaturity { ​ require ​ ( ​ totalSupply ​ () ​ == ​ ​ 0 ​ , ​ "Pool: Already initialized" ); ​ // no yDai transferred, because initial yDai deposit is entirely virtual dai. ​ transferFrom ​ ( ​ msg ​ . ​ sender ​ , ​ address ​ ( ​ this ​ ), daiIn); ​ _mint ​ ( ​ msg ​ . ​ sender ​ , daiIn); ​ emit ​ ​ Liquidity ​ (maturity, ​ msg ​ . ​ sender ​ , ​ msg ​ . ​ sender ​ , ​ - ​ toInt256 ​ (daiIn), ​ 0 ​ , toInt256 ​ (daiIn)); } Figure 10.1: ​ init ​ function in ​ Pool.sol ​ .     However, there are some are some concerns regarding this code:     ● Any user can call ​ init ​ and provide some initial liquidity.   ● If at some point all the tokens are burned and the total supply is zero, it can be   called again.   ● If the pool is not initialized before the ​ fyDAI ​ maturity date, it cannot be initialized.     Exploit Scenario   Alice deploys the Pool contract. Eve is monitoring the blockchain transactions and notices   that Alice has started the deployment. Before Alice can perform any other transaction, Eve   calls ​ init ​ with the minimal amount of tokens (1), so Alice is forced to provide liquidity using   the ​ mint ​ function or re-deploy the contract.     © 2020 Trail of Bits   Yield Protocol Assessment | 29        Recommendation   Short term, consider restricting calls to ​ init ​ to the contract owner and enforce that it can   only be called once. This will ensure initialization is carried out as Yield intends.     Long term, review the rest of the components to make sure they are suitable for their   purpose and can be used only for their intended purpose.       © 2020 Trail of Bits   Yield Protocol Assessment | 30      1 1 . C o m p u t a t i o n o f ​ DAI ​ / ​ fyDAI ​ t o b u y / s e l l i s i m p r e c i s e     Severity: Undetermined Difficulty: Medium   Type: Data Validation Finding ID: ​ TOB-YP-011   Target: ​ YieldMath.sol   Description   It is unclear if the functions used to determine how many ​ DAI ​ or ​ fyDAI ​ a user must buy or   sell (given the current total supply and reserves) works as expected or not.     The ​ YieldMath ​ provides several functions to calculate the amount of ​ DAI ​ or ​ fyDAI ​ , given   the state of the pool. For instance, ​ yDaiOutForDaiIn ​ computes the amount of ​ fyDAI ​ a user   would get for a given amount of ​ DAI ​ :     ​ function ​ yDaiOutForDaiIn ​ ( ​ uint128 ​ ​ daiReserves ​ , ​ uint128 ​ ​ yDAIReserves ​ , ​ uint128 ​ ​ daiAmount ​ , ​ uint128 ​ ​ timeTillMaturity ​ , ​ int128 ​ ​ k ​ , ​ int128 ​ ​ g ​ ) ​ internal ​ ​ pure ​ ​ returns ​ ( ​ uint128 ​ ) { ​ // t = k * timeTillMaturity ​ int128 ​ t = ABDKMath64x64.mul (k, ABDKMath64x64.fromUInt (timeTillMaturity)); ​ // a = (1 - gt) ​ int128 ​ a = ABDKMath64x64.sub ( ​ 0x10000000000000000 ​ , ABDKMath64x64.mul (g, t)); ​ require ​ (a ​ > ​ ​ 0 ​ , ​ "YieldMath: Too far from maturity" ​ ); ​ // xdx = daiReserves + daiAmount ​ uint256 ​ xdx = uint256 (daiReserves) ​ + ​ uint256 (daiAmount); ​ require ​ (xdx ​ < ​ ​ 0x100000000000000000000000000000000 ​ , ​ "YieldMath: Too much Dai in" ​ ); ​ uint256 ​ sum = uint256 (pow (daiReserves, uint128 (a), ​ 0x10000000000000000 ​ )) ​ + uint256 (pow (yDAIReserves, uint128 (a), ​ 0x10000000000000000 ​ )) ​ - uint256 (pow ( ​ uint128 ​ (xdx), uint128 (a), ​ 0x10000000000000000 ​ )); ​ require ​ (sum ​ < ​ ​ 0x100000000000000000000000000000000 ​ , ​ "YieldMath: Insufficient yDAI reserves" ​ ); ​ uint256 ​ result = yDAIReserves ​ - ​ pow (uint128 (sum), ​ 0x10000000000000000 ​ , uint128 (a)); ​ require ​ (result ​ < ​ ​ 0x100000000000000000000000000000000 ​ , ​ "YieldMath: Rounding induced   © 2020 Trail of Bits   Yield Protocol Assessment | 31      error" ​ ); ​ return ​ uint128 (result); } Figure 11.1: ​ yDaiOutForDaiIn ​ function in ​ YieldMath.sol ​ .   YieldMath ​ also provides another function called ​ daiInForYDaiOut ​ to calculate the amount   of ​ DAI ​ a user would have to pay for a certain amount of ​ fyDAI ​ . These two functions should   behave as inverses:     ​ function ​ DaiInOut ​ ( ​ uint128 ​ ​ daiReserves ​ , ​ uint128 ​ ​ yDAIReserves ​ , ​ uint128 ​ ​ daiAmount ​ , ​ uint128 ​ ​ timeTillMaturity ​ ) ​ public ​ { daiReserves ​ = ​ ​ 1 ​ ​ + ​ daiReserves ​ % ​ ​ 2 ​ ** ​ 112 ​ ; yDAIReserves ​ = ​ ​ 1 ​ ​ + ​ yDAIReserves ​ % ​ ​ 2 ​ ** ​ 112 ​ ; daiAmount ​ = ​ ​ 1 ​ ​ + ​ daiAmount ​ % ​ ​ 2 ​ ** ​ 112 ​ ; timeTillMaturity ​ = ​ ​ 1 ​ ​ + ​ timeTillMaturity ​ % ​ ( ​ 12 ​ * ​ 4 ​ * ​ 2 ​ ​ weeks ​ ); ​ // 2 years ​ require ​ (daiReserves ​ >= ​ ​ 1024 ​ * ​ oneDAI); ​ require ​ (yDAIReserves ​ >= ​ daiReserves); ​ uint128 ​ daiAmount1 = daiAmount; ​ uint128 ​ yDAIAmount = YieldMath. ​ yDaiOutForDaiIn ​ (daiReserves, yDAIReserves, daiAmount1, timeTillMaturity, k, g); ​ require ​ ( ​ sub ​ (yDAIReserves, yDAIAmount) ​ >= ​ ​ add ​ (daiReserves, daiAmount1), ​ "Pool: yDai reserves too low" ); ​ uint128 ​ daiAmount2 = YieldMath. ​ daiInForYDaiOut ​ (daiReserves, yDAIReserves, yDAIAmount, timeTillMaturity, k, g); ​ require ​ ( ​ sub ​ (yDAIReserves, yDAIAmount) ​ >= ​ ​ add ​ (daiReserves, daiAmount2), ​ "Pool: yDai reserves too low" );   © 2020 Trail of Bits   Yield Protocol Assessment | 32      ​ assert ​ ( ​ equalWithTol ​ (daiAmount1, daiAmount2)); } Figure 11.2: Echidna property to test functions in ​ YieldMath.sol ​ .   However, these two functions do not behave as the inverse of each other, as Echidna was   able to show. If this property is called with the following parameters...     ● daiReserves: 155591140918329338279663772 ● yDAIReserves: 12011620595696883763591137622155 ● daiAmount: 4726945 ● timeTilMaturity: 974285   ...the resulting ​ DAI ​ amounts will differ with more than 10 ​ DAI ​ of difference.     Exploit Scenario   Alice uses the pool to buy/sell ​ DAI ​ /​ fyDAI ​ , but the resulting amount is unexpected.     Recommendation   Short term, review the specification of the ​ YieldMath ​ functions and make sure it matches   the implementation. Use Echidna to validate the implementation.     Long term, develop robust unit and automated test suites for the custom math functions.   This will help to ensure the correct functionality of this complex arithmetic.         © 2020 Trail of Bits   Yield Protocol Assessment | 33      A . V u l n e r a b i l i t y C l a s s i f i 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 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   Testing   Related to test methodology or test coverage   Timing   Related to race conditions, locking, or order of operations   Undefined Behavior   Related to undefined behavior triggered by the program       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     © 2020 Trail of Bits   Yield Protocol Assessment | 34      Medium   Individual user’s information is at risk, exploitation would be bad for   client’s reputation, moderate financial impact, possible legal   implications for client   High   Large numbers of users, very bad for client’s reputation, or serious   legal or financial implications     Difficulty Levels   Difficulty   Description   Undetermined   The difficulty of exploit was not determined during this engagement   Low   Commonly exploited, public tools exist or can be scripted that exploit   this flaw   Medium   Attackers must write an exploit, or need an in-depth knowledge of a   complex system   High   The attacker must have privileged insider access to the system, may   need to know extremely complex technical details, or must discover   other weaknesses in order to exploit this issue         © 2020 Trail of Bits   Yield Protocol Assessment | 35      B . C o d e M a t u r i t y C l a s s i f i 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 purpose.   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 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.     © 2020 Trail of Bits   Yield Protocol Assessment | 36      Not Applicable   The component is not applicable.   Not Considered   The component was not reviewed.   Further   Investigation   Required   The component requires further investigation.           © 2020 Trail of Bits   Yield Protocol Assessment | 37      C . 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   ● Consider allowing the owner to adjust the ​ FEE ​ or ​ DUST ​ constants in the   protocol. ​ These are specified in ​ Ether ​ and may become very expensive if the price   of this cryptocurrency continues to grow.     C o n t r o l l e r   ● Consider reverting if a call to ​ powerOf ​ uses an invalid collateral. ​ Reverting if a   user tries to obtain the borrowing power with an invalid collateral will prevent   invalid results if the user interacts with the Controller contract in an unexpected   way.   ● Consider adding ​ FEE/DUST ​ constants​ . Properly naming constants will make the   codebase easier to maintain, modify, and audit.   L i q u i d a t i o n s   ● Consider removing the ​ dai ​ state variable if it is unused. ​ Removing unused code   will make the codebase easier to maintain, modify, and audit.   ● Address outstanding TODOs in the codebase​ or open issues to ensure they are   tracked properly and not overlooked when deploying the system. Develop test cases   to cover the scenario in which a user is liquidated multiple times, and ensure the   expected behavior is carried out.     T r e a s u r y ​ :   ● Consider adding a flashy warning to users in case they want to transfer   collateral directly to the Treasury contract address.​ If collateral is transferred   directly to the Treasury contract address, it will be locked there until the MakerDAO   shutdown, so users should be warned about this.     P o o l :   ● Consider reviewing the code comments on the ​ burn ​ function​ . The comment   mentions that this function requires the use of ​ approve ​ ; however, there is no use of   transferFrom ​ , so it should not be needed. Keeping documentation up to date will   make the codebase easier to maintain, modify, and audit.       © 2020 Trail of Bits   Yield Protocol Assessment | 38      D . F i x L o g     Yield addressed issues TOB-YP-001 to TOB-YP-011 in their codebase as a result of our   assessment. Each of the fixes was verified by Trail of Bits, and the reviewed code is   available in git revision ​ 642b33b166a6b740f907a0e6d85dbd0d87451c77 ​ .     ID   Title   Severity   Status   01   Flash minting can be used to redeem ​ fyDAI Medium   Fixed   02   Permission-granting is too simplistic and not flexible   enough   Low   Mitigated   03   pot.chi() ​ value is never updated   Low   Risk   accepted   04   Lack of validation when setting the maturity value   Low   Fixed   05   Delegates can be added or removed repeatedly to   bloat logs   Informational   Fixed   06   Withdrawing from the controller allows accounts to   contain dust   Low   Fixed 07   Solidity compiler optimizations can be dangerous   Undetermined   Risk   accepted   08   Lack of ​ chainID ​ validation allows signatures to be   re-used across forks   High   Not fixed   09   Permit opens the door for griefing contracts that   interact with the Yield Protocol   Informational   WIP   10   Pool initialization is unprotected   Low   Risk   accepted   11   Computation of ​ DAI ​ /​ fyDAI ​ to buy/sell is imprecise     Undetermined   Fixed           © 2020 Trail of Bits   Yield Protocol Assessment | 39      D e t a i l e d f i x l o g   This section includes brief descriptions of fixes implemented by Yield after the end of this   assessment that were reviewed by Trail of Bits.     Finding 1: Flash minting can be used to redeem ​ fyDAI Fixed by disallowing a call to ​ redeem ​ in the ​ fyDAI ​ token contract (PR ​ 246​ ) or a call to ​ redeem   in ​ Unwind ​ (PR ​ 294​ ) during flash minting.     Finding 2: Permission-granting is too simplistic and not flexible enough   This is mitigated by providing ​ an external script​ that allows any user to audit the   per-function permissions.     Finding 3: ​ pot.chi() ​ value is never updated   Risk accepted.​ ​ Yield said:       This is intended behavior, to reduce gas costs (which are very likely to exceed the   unrecognized accrued interest) and allow these functions to be ​ view ​ . (A previous   implementation did ​ callpot.drip(); ​ this was removed). We also believe that the   Severity here should be marked as “Low”as there is no risk associated with user   funds. We will monitor this issue and, if interest accumulation is not being done   frequently enough, can provide an external mechanism for users to call `pot.drip`   before interacting with the ​ fyDAI ​ contracts.     Finding 4: Lack of validation when setting the maturity value   Fixed by verifying the maturity date in the ​ YDai ​ constructor (PR ​ 251​ ).     Finding 5: Delegates can be added or removed repeatedly to bloat logs   Fixed by disallowing re-adding and re-removing delegates (PRs ​ 252​ and ​ 293​ ).     Finding 6: Withdrawing from the controller allows accounts to contain dust   Fixed by enforcing the ​ aboveDustOrZero ​ property in all the accounts in the ​ Controller ​ (PR   268​ ).     Finding 7: Solidity compiler optimizations can be dangerous   Risk accepted.​ ​ Yield said they will continue using the optimizer with 200 runs.     Finding 8: Lack of ​ chainID ​ validation allows signatures to be re-used across forks   Not fixed.     Finding 9: Permit opens the door for griefing contracts that interact with the Yield   Protocol       © 2020 Trail of Bits   Yield Protocol Assessment | 40      This fix is still in progress. Yield said they will add a note about it in their documentation to   warn the user.     Finding 10: Pool initialization is unprotected   Risk accepted. Yield said:     This is a feature, we want anyone to be able to initialize the pool, even though it will   probably be us calling it. We do not mind somebody else frontrunning the   initialization transaction. Should be marked as informational.     Finding 11: Computation of ​ DAI/fyDAI ​ to buy/sell is imprecise     Fixed by ​ adding a flat fee​ to compensate for the loss of precision and by ​ limiting trades to   valid ​ uint128 ​ values​ . Also, Yield determined expected parameters for the liquidity amounts   in order to define exactly how this issue could affect the pool.     © 2020 Trail of Bits   Yield Protocol Assessment | 41    
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 4 - Critical: 2 Minor Issues 2.a Problem (one line with code reference): Permission-granting is too simplistic and not flexible enough (TOB-YP-002) 2.b Fix (one line with code reference): Implement a more flexible permission-granting system (TOB-YP-002) Moderate 3.a Problem (one line with code reference): pot.chi() value is never updated (TOB-YP-003) 3.b Fix (one line with code reference): Update pot.chi() value when necessary (TOB-YP-003) Major 4.a Problem (one line with code reference): Lack of validation when setting the maturity value (TOB-YP-004) 4.b Fix (one line with code reference): Validate maturity value before setting (TOB-YP-004) Critical 5.a Problem (one line with code reference): Withdrawing from the Controller allows accounts to contain dust (TOB-YP-006) 5.b Fix (one Issues Count of Minor/Moderate/Major/Critical Minor: 5 Moderate: 1 Major: 1 Critical: 1 Minor Issues 2.a Problem (one line with code reference) TOB-YP-001: Unchecked return value in YDai.transferFrom() (line 545) 2.b Fix (one line with code reference) TOB-YP-001: Check return value of YDai.transferFrom() (line 545) Moderate 3.a Problem (one line with code reference) TOB-YP-002: Unchecked return value in YDai.approve() (line 522) 3.b Fix (one line with code reference) TOB-YP-002: Check return value of YDai.approve() (line 522) Major 4.a Problem (one line with code reference) TOB-YP-005: Unchecked return value in YDai.transfer() (line 537) 4.b Fix (one line with code reference) TOB-YP-005: Check return value of YDai.transfer() (line 5 Issues Count of Minor/Moderate/Major/Critical: No Issues Observations: The engagement was scoped to provide a security assessment of Yield Protocol smart contracts in the yieldprotocol/fyDAI repository. The assessment included manual review of the Controller contract's interactions with the MakerDAO system, property-based testing tools to make sure its invariants held, and verification that all of the expected ERC20 properties hold for the YDai contract. Conclusion: The security assessment of Yield Protocol smart contracts in the yieldprotocol/fyDAI repository found no potential overflows and that all expected ERC20 properties hold.
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./SpokePool.sol"; import "./SpokePoolInterface.sol"; interface StandardBridgeLike { function outboundTransfer( address _l1Token, address _to, uint256 _amount, bytes calldata _data ) external payable returns (bytes memory); } /** * @notice AVM specific SpokePool. Uses AVM cross-domain-enabled logic to implement admin only access to functions. */ contract Arbitrum_SpokePool is SpokePool { // Address of the Arbitrum L2 token gateway to send funds to L1. address public l2GatewayRouter; // Admin controlled mapping of arbitrum tokens to L1 counterpart. L1 counterpart addresses // are neccessary params used when bridging tokens to L1. mapping(address => address) public whitelistedTokens; event ArbitrumTokensBridged(address indexed l1Token, address target, uint256 numberOfTokensBridged); event SetL2GatewayRouter(address indexed newL2GatewayRouter); event WhitelistedTokens(address indexed l2Token, address indexed l1Token); /** * @notice Construct the AVM SpokePool. * @param _l2GatewayRouter Address of L2 token gateway. Can be reset by admin. * @param _crossDomainAdmin Cross domain admin to set. Can be changed by admin. * @param _hubPool Hub pool address to set. Can be changed by admin. * @param _wethAddress Weth address for this network to set. * @param timerAddress Timer address to set. */ constructor( address _l2GatewayRouter, address _crossDomainAdmin, address _hubPool, address _wethAddress, address timerAddress ) SpokePool(_crossDomainAdmin, _hubPool, _wethAddress, timerAddress) { _setL2GatewayRouter(_l2GatewayRouter); } modifier onlyFromCrossDomainAdmin() { require(msg.sender == _applyL1ToL2Alias(crossDomainAdmin), "ONLY_COUNTERPART_GATEWAY"); _; } /******************************************************** * ARBITRUM-SPECIFIC CROSS-CHAIN ADMIN FUNCTIONS * ********************************************************/ /** * @notice Change L2 gateway router. Callable only by admin. * @param newL2GatewayRouter New L2 gateway router. */ function setL2GatewayRouter(address newL2GatewayRouter) public onlyAdmin nonReentrant { _setL2GatewayRouter(newL2GatewayRouter); } /** * @notice Add L2 -> L1 token mapping. Callable only by admin. * @param l2Token Arbitrum token. * @param l1Token Ethereum version of l2Token. */ function whitelistToken(address l2Token, address l1Token) public onlyAdmin nonReentrant { _whitelistToken(l2Token, l1Token); } /************************************** * INTERNAL FUNCTIONS * **************************************/ function _bridgeTokensToHubPool(RelayerRefundLeaf memory relayerRefundLeaf) internal override { StandardBridgeLike(l2GatewayRouter).outboundTransfer( whitelistedTokens[relayerRefundLeaf.l2TokenAddress], // _l1Token. Address of the L1 token to bridge over. hubPool, // _to. Withdraw, over the bridge, to the l1 hub pool contract. relayerRefundLeaf.amountToReturn, // _amount. "" // _data. We don't need to send any data for the bridging action. ); emit ArbitrumTokensBridged(address(0), hubPool, relayerRefundLeaf.amountToReturn); } function _setL2GatewayRouter(address _l2GatewayRouter) internal { l2GatewayRouter = _l2GatewayRouter; emit SetL2GatewayRouter(l2GatewayRouter); } function _whitelistToken(address _l2Token, address _l1Token) internal { whitelistedTokens[_l2Token] = _l1Token; emit WhitelistedTokens(_l2Token, _l1Token); } // L1 addresses are transformed during l1->l2 calls. // See https://developer.offchainlabs.com/docs/l1_l2_messages#address-aliasing for more information. // This cannot be pulled directly from Arbitrum contracts because their contracts are not 0.8.X compatible and // this operation takes advantage of overflows, whose behavior changed in 0.8.0. function _applyL1ToL2Alias(address l1Address) internal pure returns (address l2Address) { // Allows overflows as explained above. unchecked { l2Address = address(uint160(l1Address) + uint160(0x1111000000000000000000000000000000001111)); } } // Apply AVM-specific transformation to cross domain admin address on L1. function _requireAdminSender() internal override onlyFromCrossDomainAdmin {} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./MerkleLib.sol"; import "./HubPoolInterface.sol"; import "./Lockable.sol"; import "./interfaces/AdapterInterface.sol"; import "./interfaces/LpTokenFactoryInterface.sol"; import "./interfaces/WETH9.sol"; import "@uma/core/contracts/common/implementation/Testable.sol"; import "@uma/core/contracts/common/implementation/MultiCaller.sol"; import "@uma/core/contracts/oracle/implementation/Constants.sol"; import "@uma/core/contracts/common/implementation/AncillaryData.sol"; import "@uma/core/contracts/common/interfaces/AddressWhitelistInterface.sol"; import "@uma/core/contracts/oracle/interfaces/IdentifierWhitelistInterface.sol"; import "@uma/core/contracts/oracle/interfaces/FinderInterface.sol"; import "@uma/core/contracts/oracle/interfaces/StoreInterface.sol"; import "@uma/core/contracts/oracle/interfaces/SkinnyOptimisticOracleInterface.sol"; import "@uma/core/contracts/common/interfaces/ExpandedIERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @notice Contract deployed on Ethereum that houses L1 token liquidity for all SpokePools. A dataworker can interact * with merkle roots stored in this contract via inclusion proofs to instruct this contract to send tokens to L2 * SpokePools via "pool rebalances" that can be used to pay out relayers on those networks. This contract is also * responsible for publishing relayer refund and slow relay merkle roots to SpokePools. * @notice This contract is meant to act as the cross chain administrator and owner of all L2 spoke pools, so all * governance actions and pool rebalances originate from here and bridge instructions to L2s. */ contract HubPool is HubPoolInterface, Testable, Lockable, MultiCaller, Ownable { using SafeERC20 for IERC20; using Address for address; // A data worker can optimistically store several merkle roots on this contract by staking a bond and calling // proposeRootBundle. By staking a bond, the data worker is alleging that the merkle roots all // contain valid leaves that can be executed later to: // - Send funds from this contract to a SpokePool or vice versa // - Send funds from a SpokePool to Relayer as a refund for a relayed deposit // - Send funds from a SpokePool to a deposit recipient to fulfill a "slow" relay // Anyone can dispute this struct if the merkle roots contain invalid leaves before the // requestExpirationTimestamp. Once the expiration timestamp is passed, executeRootBundle to execute a leaf // from the poolRebalanceRoot on this contract and it will simultaneously publish the relayerRefundRoot and // slowRelayRoot to a SpokePool. The latter two roots, once published to the SpokePool, contain // leaves that can be executed on the SpokePool to pay relayers or recipients. struct RootBundle { // When root bundle challenge period passes and this root bundle becomes executable. uint64 requestExpirationTimestamp; // Number of pool rebalance leaves to execute in the poolRebalanceRoot. After this number // of leaves are executed, a new root bundle can be proposed uint64 unclaimedPoolRebalanceLeafCount; // Contains leaves instructing this contract to send funds to SpokePools. bytes32 poolRebalanceRoot; // Relayer refund merkle root to be published to a SpokePool. bytes32 relayerRefundRoot; // Slow relay merkle root to be published to a SpokePool. bytes32 slowRelayRoot; // This is a 1D bitmap, with max size of 256 elements, limiting us to 256 chainsIds. uint256 claimedBitMap; // Proposer of this root bundle. address proposer; // Whether bond has been repaid to successful root bundle proposer. bool proposerBondRepaid; } // Only one root bundle can be stored at a time. Once all pool rebalance leaves are executed, a new proposal // can be submitted. RootBundle public rootBundleProposal; // Whitelist of origin token + ID to destination token routings to be used by off-chain agents. The notion of a // route does not need to include L1; it can be L2->L2 route. i.e USDC on Arbitrum -> USDC on Optimism as a "route". mapping(bytes32 => address) private whitelistedRoutes; struct PooledToken { // LP token given to LPs of a specific L1 token. address lpToken; // True if accepting new LP's. bool isEnabled; // Timestamp of last LP fee update. uint32 lastLpFeeUpdate; // Number of LP funds sent via pool rebalances to SpokePools and are expected to be sent // back later. int256 utilizedReserves; // Number of LP funds held in contract less utilized reserves. uint256 liquidReserves; // Number of LP funds reserved to pay out to LPs as fees. uint256 undistributedLpFees; } // Mapping of L1 token addresses to the associated pool information. mapping(address => PooledToken) public pooledTokens; // Heler contracts to facilitate cross chain actions between HubPool and SpokePool for a specific network. struct CrossChainContract { AdapterInterface adapter; address spokePool; } // Mapping of chainId to the associated adapter and spokePool contracts. mapping(uint256 => CrossChainContract) public crossChainContracts; // WETH contract for Ethereum. WETH9 public weth; // Helper factory to deploy new LP tokens for enabled L1 tokens LpTokenFactoryInterface public lpTokenFactory; // Finder contract for this network. FinderInterface public finder; // When root bundles are disputed a price request is enqueued with the DVM to resolve the resolution. bytes32 public identifier = "IS_ACROSS_V2_BUNDLE_VALID"; // Interest rate payment that scales the amount of pending fees per second paid to LPs. 0.0000015e18 will pay out // the full amount of fees entitled to LPs in ~ 7.72 days, just over the standard L2 7 day liveness. uint256 public lpFeeRatePerSecond = 1500000000000; mapping(address => uint256) public unclaimedAccumulatedProtocolFees; // Address that captures protocol fees. Accumulated protocol fees can be claimed by this address. address public protocolFeeCaptureAddress; // Percentage of lpFees that are captured by the protocol and claimable by the protocolFeeCaptureAddress. uint256 public protocolFeeCapturePct; // Token used to bond the data worker for proposing relayer refund bundles. IERC20 public bondToken; // The computed bond amount as the UMA Store's final fee multiplied by the bondTokenFinalFeeMultiplier. uint256 public bondAmount; // Each root bundle proposal must stay in liveness for this period of time before it can be considered finalized. // It can be disputed only during this period of time. Defaults to 2 hours, like the rest of the UMA ecosystem. uint64 public liveness = 7200; event ProtocolFeeCaptureSet(address indexed newProtocolFeeCaptureAddress, uint256 indexed newProtocolFeeCapturePct); event ProtocolFeesCapturedClaimed(address indexed l1Token, uint256 indexed accumulatedFees); event BondSet(address indexed newBondToken, uint256 newBondAmount); event LivenessSet(uint256 newLiveness); event IdentifierSet(bytes32 newIdentifier); event CrossChainContractsSet(uint256 l2ChainId, address adapter, address spokePool); event L1TokenEnabledForLiquidityProvision(address l1Token, address lpToken); event L2TokenDisabledForLiquidityProvision(address l1Token, address lpToken); event LiquidityAdded( address indexed l1Token, uint256 amount, uint256 lpTokensMinted, address indexed liquidityProvider ); event LiquidityRemoved( address indexed l1Token, uint256 amount, uint256 lpTokensBurnt, address indexed liquidityProvider ); event WhitelistRoute( uint256 originChainId, uint256 destinationChainId, address originToken, address destinationToken ); event ProposeRootBundle( uint64 requestExpirationTimestamp, uint64 unclaimedPoolRebalanceLeafCount, uint256[] bundleEvaluationBlockNumbers, bytes32 indexed poolRebalanceRoot, bytes32 indexed relayerRefundRoot, bytes32 slowRelayRoot, address indexed proposer ); event RootBundleExecuted( uint256 indexed leafId, uint256 indexed chainId, address[] l1Token, uint256[] bundleLpFees, int256[] netSendAmount, int256[] runningBalance, address indexed caller ); event SpokePoolAdminFunctionTriggered(uint256 indexed chainId, bytes message); event RootBundleDisputed(address indexed disputer, uint256 requestTime, bytes disputedAncillaryData); event RootBundleCanceled(address indexed disputer, uint256 requestTime, bytes disputedAncillaryData); modifier noActiveRequests() { require(!_activeRequest(), "proposal has unclaimed leafs"); _; } modifier zeroOptimisticOracleApproval() { _; bondToken.safeApprove(address(_getOptimisticOracle()), 0); } /** * @notice Construct HubPool. * @param _lpTokenFactory LP Token factory address used to deploy LP tokens for new collateral types. * @param _finder Finder address. * @param _weth WETH address. * @param _timer Timer address. */ constructor( LpTokenFactoryInterface _lpTokenFactory, FinderInterface _finder, WETH9 _weth, address _timer ) Testable(_timer) { lpTokenFactory = _lpTokenFactory; finder = _finder; weth = _weth; protocolFeeCaptureAddress = owner(); } /************************************************* * ADMIN FUNCTIONS * *************************************************/ /** * @notice Sends message to SpokePool from this contract. Callable only by owner. * @dev This function has permission to call onlyAdmin functions on the SpokePool, so its imperative * that this contract only allows the owner to call this method directly or indirectly. * @param chainId Chain with SpokePool to send message to. * @param functionData ABI encoded function call to send to SpokePool, but can be any arbitrary data technically. */ function relaySpokePoolAdminFunction(uint256 chainId, bytes memory functionData) public override onlyOwner nonReentrant { _relaySpokePoolAdminFunction(chainId, functionData); } /** * @notice Sets protocolFeeCaptureAddress and protocolFeeCapturePct. Callable only by owner. * @param newProtocolFeeCaptureAddress New protocol fee capture address. * @param newProtocolFeeCapturePct New protocol fee capture %. */ function setProtocolFeeCapture(address newProtocolFeeCaptureAddress, uint256 newProtocolFeeCapturePct) public override onlyOwner { require(newProtocolFeeCapturePct <= 1e18, "Bad protocolFeeCapturePct"); protocolFeeCaptureAddress = newProtocolFeeCaptureAddress; protocolFeeCapturePct = newProtocolFeeCapturePct; emit ProtocolFeeCaptureSet(newProtocolFeeCaptureAddress, newProtocolFeeCapturePct); } /** * @notice Sets bond token and amount. Callable only by owner. * @param newBondToken New bond currency. * @param newBondAmount New bond amount. */ function setBond(IERC20 newBondToken, uint256 newBondAmount) public override onlyOwner noActiveRequests { // Check that this token is on the whitelist. AddressWhitelistInterface addressWhitelist = AddressWhitelistInterface( finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist) ); require(addressWhitelist.isOnWhitelist(address(newBondToken)), "Not on whitelist"); // The bond should be the passed in bondAmount + the final fee. bondToken = newBondToken; bondAmount = newBondAmount + _getBondTokenFinalFee(); emit BondSet(address(newBondToken), bondAmount); } /** * @notice Sets root bundle proposal liveness period. Callable only by owner. * @param newLiveness New liveness period. */ function setLiveness(uint64 newLiveness) public override onlyOwner { require(newLiveness > 10 minutes, "Liveness too short"); liveness = newLiveness; emit LivenessSet(newLiveness); } /** * @notice Sets identifier for root bundle disputes.. Callable only by owner. * @param newIdentifier New identifier. */ function setIdentifier(bytes32 newIdentifier) public override onlyOwner noActiveRequests { IdentifierWhitelistInterface identifierWhitelist = IdentifierWhitelistInterface( finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist) ); require(identifierWhitelist.isIdentifierSupported(newIdentifier), "Identifier not supported"); identifier = newIdentifier; emit IdentifierSet(newIdentifier); } /** * @notice Sets cross chain relay helper contracts for L2 chain ID. Callable only by owner. * @param l2ChainId Chain to set contracts for. * @param adapter Adapter used to relay messages and tokens to spoke pool. * @param spokePool Recipient of relayed messages and tokens on SpokePool. */ function setCrossChainContracts( uint256 l2ChainId, address adapter, address spokePool ) public override onlyOwner noActiveRequests { crossChainContracts[l2ChainId] = CrossChainContract(AdapterInterface(adapter), spokePool); emit CrossChainContractsSet(l2ChainId, adapter, spokePool); } /** * @notice Whitelist an origin chain ID + token <-> destination token route. Callable only by owner. * @param originChainId Chain where deposit occurs. * @param destinationChainId Chain where depositor wants to receive funds. * @param originToken Deposited token. * @param destinationToken Token that depositor wants to receive on destination chain. */ function whitelistRoute( uint256 originChainId, uint256 destinationChainId, address originToken, address destinationToken ) public override onlyOwner { whitelistedRoutes[_whitelistedRouteKey(originChainId, originToken, destinationChainId)] = destinationToken; // Whitelist the same route on the origin network. _relaySpokePoolAdminFunction( originChainId, abi.encodeWithSignature("setEnableRoute(address,uint256,bool)", originToken, destinationChainId, true) ); emit WhitelistRoute(originChainId, destinationChainId, originToken, destinationToken); } /** * @notice Enables LPs to provide liquidity for L1 token. Deploys new LP token for L1 token if appropriate. * Callable only by owner. * @param l1Token Token to provide liquidity for. */ function enableL1TokenForLiquidityProvision(address l1Token) public override onlyOwner { if (pooledTokens[l1Token].lpToken == address(0)) pooledTokens[l1Token].lpToken = lpTokenFactory.createLpToken(l1Token); pooledTokens[l1Token].isEnabled = true; pooledTokens[l1Token].lastLpFeeUpdate = uint32(getCurrentTime()); emit L1TokenEnabledForLiquidityProvision(l1Token, pooledTokens[l1Token].lpToken); } /** * @notice Disables LPs from providing liquidity for L1 token. Callable only by owner. * @param l1Token Token to disable liquidity provision for. */ function disableL1TokenForLiquidityProvision(address l1Token) public override onlyOwner { pooledTokens[l1Token].isEnabled = false; emit L2TokenDisabledForLiquidityProvision(l1Token, pooledTokens[l1Token].lpToken); } /************************************************* * LIQUIDITY PROVIDER FUNCTIONS * *************************************************/ /** * @notice Deposit liquidity into this contract to earn LP fees in exchange for funding relays on SpokePools. * Caller is essentially loaning their funds to be sent from this contract to the SpokePool, where it will be used * to repay a relayer, and ultimately receives their loan back after the tokens are bridged back to this contract * via the canonical token bridge. Then, the caller's loans are used for again. This loan cycle repeats continuously * and the caller, or "liquidity provider" earns a continuous fee for their credit that they are extending relayers. * @notice Caller will receive an LP token representing their share of this pool. The LP token's redemption value * increments from the time that they enter the pool to reflect their accrued fees. * @param l1Token Token to deposit into this contract. * @param l1TokenAmount Amount of liquidity to provide. */ function addLiquidity(address l1Token, uint256 l1TokenAmount) public payable override { require(pooledTokens[l1Token].isEnabled, "Token not enabled"); // If this is the weth pool and the caller sends msg.value then the msg.value must match the l1TokenAmount. // Else, msg.value must be set to 0. require(((address(weth) == l1Token) && msg.value == l1TokenAmount) || msg.value == 0, "Bad msg.value"); // Since _exchangeRateCurrent() reads this contract's balance and updates contract state using it, it must be // first before transferring any tokens to this contract to ensure synchronization. uint256 lpTokensToMint = (l1TokenAmount * 1e18) / _exchangeRateCurrent(l1Token); ExpandedIERC20(pooledTokens[l1Token].lpToken).mint(msg.sender, lpTokensToMint); pooledTokens[l1Token].liquidReserves += l1TokenAmount; if (address(weth) == l1Token && msg.value > 0) WETH9(address(l1Token)).deposit{ value: msg.value }(); else IERC20(l1Token).safeTransferFrom(msg.sender, address(this), l1TokenAmount); emit LiquidityAdded(l1Token, l1TokenAmount, lpTokensToMint, msg.sender); } /** * @notice Burns LP share to redeem for underlying l1Token original deposit amount plus fees. * @param l1Token Token to redeem LP share for. * @param lpTokenAmount Amount of LP tokens to burn. Exchange rate between L1 token and LP token can be queried * via public exchangeRateCurrent method. * @param sendEth Set to True if L1 token is WETH and user wants to receive ETH. */ function removeLiquidity( address l1Token, uint256 lpTokenAmount, bool sendEth ) public override nonReentrant { require(address(weth) == l1Token || !sendEth, "Cant send eth"); uint256 l1TokensToReturn = (lpTokenAmount * _exchangeRateCurrent(l1Token)) / 1e18; ExpandedIERC20(pooledTokens[l1Token].lpToken).burnFrom(msg.sender, lpTokenAmount); // Note this method does not make any liquidity utilization checks before letting the LP redeem their LP tokens. // If they try access more funds that available (i.e l1TokensToReturn > liquidReserves) this will underflow. pooledTokens[l1Token].liquidReserves -= l1TokensToReturn; if (sendEth) _unwrapWETHTo(payable(msg.sender), l1TokensToReturn); else IERC20(l1Token).safeTransfer(msg.sender, l1TokensToReturn); emit LiquidityRemoved(l1Token, l1TokensToReturn, lpTokenAmount, msg.sender); } /** * @notice Returns exchange rate of L1 token to LP token. * @param l1Token L1 token redeemable by burning LP token. * @return Amount of L1 tokens redeemable for 1 unit LP token. */ function exchangeRateCurrent(address l1Token) public override nonReentrant returns (uint256) { return _exchangeRateCurrent(l1Token); } /** * @notice Returns % of liquid reserves currently being "used" and sitting in SpokePools. * @param l1Token L1 token to query utilization for. * @return % of liquid reserves currently being "used" and sitting in SpokePools. */ function liquidityUtilizationCurrent(address l1Token) public override nonReentrant returns (uint256) { return _liquidityUtilizationPostRelay(l1Token, 0); } /** * @notice Returns % of liquid reserves currently being "used" and sitting in SpokePools and accounting for * relayedAmount of tokens to be withdrawn from the pool. * @param l1Token L1 token to query utilization for. * @param relayedAmount The higher this amount, the higher the utilization. * @return % of liquid reserves currently being "used" and sitting in SpokePools plus the relayedAmount. */ function liquidityUtilizationPostRelay(address l1Token, uint256 relayedAmount) public nonReentrant returns (uint256) { return _liquidityUtilizationPostRelay(l1Token, relayedAmount); } /** * @notice Synchronize any balance changes in this contract with the utilized & liquid reserves. This should be done * at the conclusion of a L2->L1 token transfer via the canonical token bridge, when this contract's reserves do not * reflect its true balance due to new tokens being dropped onto the contract at the conclusion of a bridging action. */ function sync(address l1Token) public override nonReentrant { _sync(l1Token); } /************************************************* * DATA WORKER FUNCTIONS * *************************************************/ /** * @notice Publish a new root bundle to along with all of the block numbers that the merkle roots are relevant for. * This is used to aid off-chain validators in evaluating the correctness of this bundle. Caller stakes a bond that * can be slashed if the root bundle proposal is invalid, and they will receive it back if accepted. * @notice After proposeRootBundle is called, if the any props are wrong then this proposal can be challenged. * Once the challenge period passes, then the roots are no longer disputable, and only executeRootBundle can be * called; moreover, this method can't be called again until all leafs are executed. * @param bundleEvaluationBlockNumbers should contain the latest block number for all chains, even if there are no * relays contained on some of them. The usage of this variable should be defined in an off chain UMIP. * @param poolRebalanceLeafCount Number of leaves contained in pool rebalance root. Max is the number of whitelisted chains. * @param poolRebalanceRoot Pool rebalance root containing leaves that will send tokens from this contract to a SpokePool. * @param relayerRefundRoot Relayer refund root to publish to SpokePool where a data worker can execute leaves to * refund relayers on their chosen refund chainId. * @param slowRelayRoot Slow relay root to publish to Spoke Pool where a data worker can execute leaves to * fulfill slow relays. */ function proposeRootBundle( uint256[] memory bundleEvaluationBlockNumbers, uint8 poolRebalanceLeafCount, bytes32 poolRebalanceRoot, bytes32 relayerRefundRoot, bytes32 slowRelayRoot ) public override nonReentrant noActiveRequests { // Note: this is to prevent "empty block" style attacks where someone can make empty proposals that are // technically valid but not useful. This could also potentially be enforced at the UMIP-level. require(poolRebalanceLeafCount > 0, "Bundle must have at least 1 leaf"); uint64 requestExpirationTimestamp = uint64(getCurrentTime() + liveness); delete rootBundleProposal; // Only one bundle of roots can be executed at a time. rootBundleProposal.requestExpirationTimestamp = requestExpirationTimestamp; rootBundleProposal.unclaimedPoolRebalanceLeafCount = poolRebalanceLeafCount; rootBundleProposal.poolRebalanceRoot = poolRebalanceRoot; rootBundleProposal.relayerRefundRoot = relayerRefundRoot; rootBundleProposal.slowRelayRoot = slowRelayRoot; rootBundleProposal.proposer = msg.sender; // Pull bondAmount of bondToken from the caller. bondToken.safeTransferFrom(msg.sender, address(this), bondAmount); emit ProposeRootBundle( requestExpirationTimestamp, poolRebalanceLeafCount, bundleEvaluationBlockNumbers, poolRebalanceRoot, relayerRefundRoot, slowRelayRoot, msg.sender ); } /** * @notice Executes a pool rebalance leaf as part of the currently published root bundle. Will bridge any tokens * from this contract to the SpokePool designated in the leaf, and will also publish relayer refund and slow * relay roots to the SpokePool on the network specified in the leaf. * @dev In some cases, will instruct spokePool to send funds back to L1. * @notice Deletes the published root bundle if this is the last leaf to be executed in the root bundle. * @param poolRebalanceLeaf Contains all data neccessary to reconstruct leaf contained in root bundle and to * bridge tokens to HubPool. This data structure is explained in detail in the HubPoolInterface. * @param proof Inclusion proof for this leaf in pool rebalance root in root bundle. */ function executeRootBundle(PoolRebalanceLeaf memory poolRebalanceLeaf, bytes32[] memory proof) public nonReentrant { require(getCurrentTime() > rootBundleProposal.requestExpirationTimestamp, "Not passed liveness"); // Verify the leafId in the poolRebalanceLeaf has not yet been claimed. require(!MerkleLib.isClaimed1D(rootBundleProposal.claimedBitMap, poolRebalanceLeaf.leafId), "Already claimed"); // Verify the props provided generate a leaf that, along with the proof, are included in the merkle root. require( MerkleLib.verifyPoolRebalance(rootBundleProposal.poolRebalanceRoot, poolRebalanceLeaf, proof), "Bad Proof" ); // Before interacting with a particular chain's adapter, ensure that the adapter is set. require(address(crossChainContracts[poolRebalanceLeaf.chainId].adapter) != address(0), "No adapter for chain"); // Set the leafId in the claimed bitmap. rootBundleProposal.claimedBitMap = MerkleLib.setClaimed1D( rootBundleProposal.claimedBitMap, poolRebalanceLeaf.leafId ); // Decrement the unclaimedPoolRebalanceLeafCount. rootBundleProposal.unclaimedPoolRebalanceLeafCount--; _sendTokensToChainAndUpdatePooledTokenTrackers( poolRebalanceLeaf.chainId, poolRebalanceLeaf.l1Tokens, poolRebalanceLeaf.netSendAmounts, poolRebalanceLeaf.bundleLpFees ); _relayRootBundleToSpokePool(poolRebalanceLeaf.chainId); // Transfer the bondAmount to back to the proposer, if this the last executed leaf. Only sending this once all // leafs have been executed acts to force the data worker to execute all bundles or they wont receive their bond. if (rootBundleProposal.unclaimedPoolRebalanceLeafCount == 0) bondToken.safeTransfer(rootBundleProposal.proposer, bondAmount); emit RootBundleExecuted( poolRebalanceLeaf.leafId, poolRebalanceLeaf.chainId, poolRebalanceLeaf.l1Tokens, poolRebalanceLeaf.bundleLpFees, poolRebalanceLeaf.netSendAmounts, poolRebalanceLeaf.runningBalances, msg.sender ); } /** * @notice Caller stakes a bond to dispute the current root bundle proposal assuming it has not passed liveness * yet. The proposal is deleted, allowing a follow-up proposal to be submitted, and the dispute is sent to the * optimistic oracle to be adjudicated. Can only be called within the liveness period of the current proposal. */ function disputeRootBundle() public nonReentrant zeroOptimisticOracleApproval { uint32 currentTime = uint32(getCurrentTime()); require(currentTime <= rootBundleProposal.requestExpirationTimestamp, "Request passed liveness"); // Request price from OO and dispute it. bytes memory requestAncillaryData = getRootBundleProposalAncillaryData(); uint256 finalFee = _getBondTokenFinalFee(); // If the finalFee is larger than the bond amount, the bond amount needs to be reset before a request can go // through. Cancel to avoid a revert. if (finalFee > bondAmount) { _cancelBundle(requestAncillaryData); return; } SkinnyOptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Only approve exact tokens to avoid more tokens than expected being pulled into the OptimisticOracle. bondToken.safeIncreaseAllowance(address(optimisticOracle), bondAmount); try optimisticOracle.requestAndProposePriceFor( identifier, currentTime, requestAncillaryData, bondToken, // Set reward to 0, since we'll settle proposer reward payouts directly from this contract after a root // proposal has passed the challenge period. 0, // Set the Optimistic oracle proposer bond for the price request. bondAmount - finalFee, // Set the Optimistic oracle liveness for the price request. liveness, rootBundleProposal.proposer, // Canonical value representing "True"; i.e. the proposed relay is valid. int256(1e18) ) returns (uint256) { // Ensure that approval == 0 after the call so the increaseAllowance call below doesn't allow more tokens // to transfer than intended. bondToken.safeApprove(address(optimisticOracle), 0); } catch { // Cancel the bundle since the proposal failed. _cancelBundle(requestAncillaryData); return; } // Dispute the request that we just sent. SkinnyOptimisticOracleInterface.Request memory ooPriceRequest = SkinnyOptimisticOracleInterface.Request({ proposer: rootBundleProposal.proposer, disputer: address(0), currency: bondToken, settled: false, proposedPrice: int256(1e18), resolvedPrice: 0, expirationTime: currentTime + liveness, reward: 0, finalFee: finalFee, bond: bondAmount - finalFee, customLiveness: liveness }); bondToken.safeTransferFrom(msg.sender, address(this), bondAmount); bondToken.safeIncreaseAllowance(address(optimisticOracle), bondAmount); optimisticOracle.disputePriceFor( identifier, currentTime, requestAncillaryData, ooPriceRequest, msg.sender, address(this) ); emit RootBundleDisputed(msg.sender, currentTime, requestAncillaryData); // Finally, delete the state pertaining to the active proposal so that another proposer can submit a new bundle. delete rootBundleProposal; } /** * @notice Send unclaimed accumulated protocol fees to fee capture address. * @param l1Token Token whose protocol fees the caller wants to disburse. */ function claimProtocolFeesCaptured(address l1Token) public override nonReentrant { IERC20(l1Token).safeTransfer(protocolFeeCaptureAddress, unclaimedAccumulatedProtocolFees[l1Token]); emit ProtocolFeesCapturedClaimed(l1Token, unclaimedAccumulatedProtocolFees[l1Token]); unclaimedAccumulatedProtocolFees[l1Token] = 0; } /** * @notice Returns ancillary data containing all relevant root bundle data that voters can format into UTF8 and * use to determine if the root bundle proposal is valid. * @return ancillaryData Ancillary data that can be decoded into UTF8. */ function getRootBundleProposalAncillaryData() public view override returns (bytes memory ancillaryData) { ancillaryData = AncillaryData.appendKeyValueUint( "", "requestExpirationTimestamp", rootBundleProposal.requestExpirationTimestamp ); ancillaryData = AncillaryData.appendKeyValueUint( ancillaryData, "unclaimedPoolRebalanceLeafCount", rootBundleProposal.unclaimedPoolRebalanceLeafCount ); ancillaryData = AncillaryData.appendKeyValueBytes32( ancillaryData, "poolRebalanceRoot", rootBundleProposal.poolRebalanceRoot ); ancillaryData = AncillaryData.appendKeyValueBytes32( ancillaryData, "relayerRefundRoot", rootBundleProposal.relayerRefundRoot ); ancillaryData = AncillaryData.appendKeyValueBytes32( ancillaryData, "slowRelayRoot", rootBundleProposal.slowRelayRoot ); ancillaryData = AncillaryData.appendKeyValueUint( ancillaryData, "claimedBitMap", rootBundleProposal.claimedBitMap ); ancillaryData = AncillaryData.appendKeyValueAddress(ancillaryData, "proposer", rootBundleProposal.proposer); } /** * @notice Conveniently queries whether an origin chain + token => destination chain ID is whitelisted and returns * the whitelisted destination token. * @param originChainId Deposit chain. * @param originToken Deposited token. * @param destinationChainId Where depositor can receive funds. * @return address Depositor can receive this token on destination chain ID. */ function whitelistedRoute( uint256 originChainId, address originToken, uint256 destinationChainId ) public view override returns (address) { return whitelistedRoutes[_whitelistedRouteKey(originChainId, originToken, destinationChainId)]; } /** * @notice This function allows a caller to load the contract with raw ETH to perform L2 calls. This is needed for arbitrum * calls, but may also be needed for others. */ function loadEthForL2Calls() public payable override {} /************************************************* * INTERNAL FUNCTIONS * *************************************************/ // Called when a dispute fails due to parameter changes. This effectively resets the state and cancels the request // with no loss of funds, thereby enabling a new bundle to be added. function _cancelBundle(bytes memory ancillaryData) internal { bondToken.transfer(rootBundleProposal.proposer, bondAmount); delete rootBundleProposal; emit RootBundleCanceled(msg.sender, getCurrentTime(), ancillaryData); } // Unwraps ETH and does a transfer to a recipient address. If the recipient is a smart contract then sends WETH. function _unwrapWETHTo(address payable to, uint256 amount) internal { if (address(to).isContract()) { IERC20(address(weth)).safeTransfer(to, amount); } else { weth.withdraw(amount); to.transfer(amount); } } function _getOptimisticOracle() internal view returns (SkinnyOptimisticOracleInterface) { return SkinnyOptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.SkinnyOptimisticOracle)); } function _getBondTokenFinalFee() internal view returns (uint256) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)) .computeFinalFee(address(bondToken)) .rawValue; } // Note this method does a lot and wraps together the sending of tokens and updating the pooled token trackers. This // is done as a gas saving so we don't need to iterate over the l1Tokens multiple times. function _sendTokensToChainAndUpdatePooledTokenTrackers( uint256 chainId, address[] memory l1Tokens, int256[] memory netSendAmounts, uint256[] memory bundleLpFees ) internal { AdapterInterface adapter = crossChainContracts[chainId].adapter; for (uint32 i = 0; i < l1Tokens.length; i++) { address l1Token = l1Tokens[i]; // Validate the L1 -> L2 token route is whitelisted. If it is not then the output of the bridging action // could send tokens to the 0x0 address on the L2. address l2Token = whitelistedRoutes[_whitelistedRouteKey(block.chainid, l1Token, chainId)]; require(l2Token != address(0), "Route not whitelisted"); // If the net send amount for this token is positive then: 1) send tokens from L1->L2 to facilitate the L2 // relayer refund, 2) Update the liquidity trackers for the associated pooled tokens. if (netSendAmounts[i] > 0) { // Perform delegatecall to use the adapter's code with this contract's context. Opt for delegatecall's // complexity in exchange for lower gas costs. (bool success, ) = address(adapter).delegatecall( abi.encodeWithSignature( "relayTokens(address,address,uint256,address)", l1Token, // l1Token. l2Token, // l2Token. uint256(netSendAmounts[i]), // amount. crossChainContracts[chainId].spokePool // to. This should be the spokePool. ) ); require(success, "delegatecall failed"); // Liquid reserves is decreased by the amount sent. utilizedReserves is increased by the amount sent. pooledTokens[l1Token].utilizedReserves += netSendAmounts[i]; pooledTokens[l1Token].liquidReserves -= uint256(netSendAmounts[i]); } // Allocate LP fees and protocol fees from the bundle to the associated pooled token trackers. _allocateLpAndProtocolFees(l1Token, bundleLpFees[i]); } } function _relayRootBundleToSpokePool(uint256 chainId) internal { AdapterInterface adapter = crossChainContracts[chainId].adapter; // Perform delegatecall to use the adapter's code with this contract's context. (bool success, ) = address(adapter).delegatecall( abi.encodeWithSignature( "relayMessage(address,bytes)", crossChainContracts[chainId].spokePool, // target. This should be the spokePool on the L2. abi.encodeWithSignature( "relayRootBundle(bytes32,bytes32)", rootBundleProposal.relayerRefundRoot, rootBundleProposal.slowRelayRoot ) // message ) ); require(success, "delegatecall failed"); } function _exchangeRateCurrent(address l1Token) internal returns (uint256) { PooledToken storage pooledToken = pooledTokens[l1Token]; // Note this is storage so the state can be modified. uint256 lpTokenTotalSupply = IERC20(pooledToken.lpToken).totalSupply(); if (lpTokenTotalSupply == 0) return 1e18; // initial rate is 1:1 between LP tokens and collateral. // First, update fee counters and local accounting of finalized transfers from L2 -> L1. _updateAccumulatedLpFees(pooledToken); // Accumulate all allocated fees from the last time this method was called. _sync(l1Token); // Fetch any balance changes due to token bridging finalization and factor them in. // ExchangeRate := (liquidReserves + utilizedReserves - undistributedLpFees) / lpTokenSupply // Both utilizedReserves and undistributedLpFees contain assigned LP fees. UndistributedLpFees is gradually // decreased over the smear duration using _updateAccumulatedLpFees. This means that the exchange rate will // gradually increase over time as undistributedLpFees goes to zero. // utilizedReserves can be negative. If this is the case, then liquidReserves is offset by an equal // and opposite size. LiquidReserves + utilizedReserves will always be larger than undistributedLpFees so this // int will always be positive so there is no risk in underflow in type casting in the return line. int256 numerator = int256(pooledToken.liquidReserves) + pooledToken.utilizedReserves - int256(pooledToken.undistributedLpFees); return (uint256(numerator) * 1e18) / lpTokenTotalSupply; } // Update internal fee counters by adding in any accumulated fees from the last time this logic was called. function _updateAccumulatedLpFees(PooledToken storage pooledToken) internal { uint256 accumulatedFees = _getAccumulatedFees(pooledToken.undistributedLpFees, pooledToken.lastLpFeeUpdate); pooledToken.undistributedLpFees -= accumulatedFees; pooledToken.lastLpFeeUpdate = uint32(getCurrentTime()); } // Calculate the unallocated accumulatedFees from the last time the contract was called. function _getAccumulatedFees(uint256 undistributedLpFees, uint256 lastLpFeeUpdate) internal view returns (uint256) { // accumulatedFees := min(undistributedLpFees * lpFeeRatePerSecond * timeFromLastInteraction ,undistributedLpFees) // The min acts to pay out all fees in the case the equation returns more than the remaining a fees. uint256 timeFromLastInteraction = getCurrentTime() - lastLpFeeUpdate; uint256 maxUndistributedLpFees = (undistributedLpFees * lpFeeRatePerSecond * timeFromLastInteraction) / (1e18); return maxUndistributedLpFees < undistributedLpFees ? maxUndistributedLpFees : undistributedLpFees; } function _sync(address l1Token) internal { // Check if the l1Token balance of the contract is greater than the liquidReserves. If it is then the bridging // action from L2 -> L1 has concluded and the local accounting can be updated. // Note: this calculation must take into account the bond when it's acting on the bond token and there's an // active request. uint256 balance = IERC20(l1Token).balanceOf(address(this)); uint256 balanceSansBond = l1Token == address(bondToken) && _activeRequest() ? balance - bondAmount : balance; if (balanceSansBond > pooledTokens[l1Token].liquidReserves) { // Note the numerical operation below can send utilizedReserves to negative. This can occur when tokens are // dropped onto the contract, exceeding the liquidReserves. pooledTokens[l1Token].utilizedReserves -= int256(balanceSansBond - pooledTokens[l1Token].liquidReserves); pooledTokens[l1Token].liquidReserves = balanceSansBond; } } function _liquidityUtilizationPostRelay(address l1Token, uint256 relayedAmount) internal returns (uint256) { _sync(l1Token); // Fetch any balance changes due to token bridging finalization and factor them in. // liquidityUtilizationRatio := (relayedAmount + max(utilizedReserves,0)) / (liquidReserves + max(utilizedReserves,0)) // UtilizedReserves has a dual meaning: if it's greater than zero then it represents funds pending in the bridge // that will flow from L2 to L1. In this case, we can use it normally in the equation. However, if it is // negative, then it is already counted in liquidReserves. This occurs if tokens are transferred directly to the // contract. In this case, ignore it as it is captured in liquid reserves and has no meaning in the numerator. PooledToken memory pooledToken = pooledTokens[l1Token]; // Note this is storage so the state can be modified. uint256 flooredUtilizedReserves = pooledToken.utilizedReserves > 0 ? uint256(pooledToken.utilizedReserves) : 0; uint256 numerator = relayedAmount + flooredUtilizedReserves; uint256 denominator = pooledToken.liquidReserves + flooredUtilizedReserves; // If the denominator equals zero, return 1e18 (max utilization). if (denominator == 0) return 1e18; // In all other cases, return the utilization ratio. return (numerator * 1e18) / denominator; } function _allocateLpAndProtocolFees(address l1Token, uint256 bundleLpFees) internal { // Calculate the fraction of bundledLpFees that are allocated to the protocol and to the LPs. uint256 protocolFeesCaptured = (bundleLpFees * protocolFeeCapturePct) / 1e18; uint256 lpFeesCaptured = bundleLpFees - protocolFeesCaptured; // Assign any LP fees included into the bundle to the pooled token. These LP fees are tracked in the // undistributedLpFees and within the utilizedReserves. undistributedLpFees is gradually decrease // over the smear duration to give the LPs their rewards over a period of time. Adding to utilizedReserves // acts to track these rewards after the smear duration. See _exchangeRateCurrent for more details. if (lpFeesCaptured > 0) { pooledTokens[l1Token].undistributedLpFees += lpFeesCaptured; pooledTokens[l1Token].utilizedReserves += int256(lpFeesCaptured); } // If there are any protocol fees, allocate them to the unclaimed protocol tracker amount. if (protocolFeesCaptured > 0) unclaimedAccumulatedProtocolFees[l1Token] += protocolFeesCaptured; } function _relaySpokePoolAdminFunction(uint256 chainId, bytes memory functionData) internal { AdapterInterface adapter = crossChainContracts[chainId].adapter; require(address(adapter) != address(0), "Adapter not initialized"); // Perform delegatecall to use the adapter's code with this contract's context. (bool success, ) = address(adapter).delegatecall( abi.encodeWithSignature( "relayMessage(address,bytes)", crossChainContracts[chainId].spokePool, // target. This should be the spokePool on the L2. functionData ) ); require(success, "delegatecall failed"); emit SpokePoolAdminFunctionTriggered(chainId, functionData); } function _whitelistedRouteKey( uint256 originChainId, address originToken, uint256 destinationChainId ) internal pure returns (bytes32) { return keccak256(abi.encode(originChainId, originToken, destinationChainId)); } function _activeRequest() internal view returns (bool) { return rootBundleProposal.unclaimedPoolRebalanceLeafCount != 0; } // If functionCallStackOriginatesFromOutsideThisContract is true then this was called by the callback function // by dropping ETH onto the contract. In this case, deposit the ETH into WETH. This would happen if ETH was sent // over the optimism bridge, for example. If false then this was set as a result of unwinding LP tokens, with the // intention of sending ETH to the LP. In this case, do nothing as we intend on sending the ETH to the LP. function _depositEthToWeth() internal { if (functionCallStackOriginatesFromOutsideThisContract()) weth.deposit{ value: msg.value }(); } // Added to enable the HubPool to receive ETH. This will occur both when the HubPool unwraps WETH to send to LPs and // when ETH is send over the canonical Optimism bridge, which sends ETH. fallback() external payable { _depositEthToWeth(); } receive() external payable { _depositEthToWeth(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Lockable.sol"; import "./interfaces/WETH9.sol"; // ERC20s (on polygon) compatible with polygon's bridge have a withdraw method. interface PolygonIERC20 is IERC20 { function withdraw(uint256 amount) external; } interface MaticToken { function withdraw(uint256 amount) external payable; } /** * @notice Contract deployed on Ethereum and Polygon to facilitate token transfers from Polygon to the HubPool and back. * @dev Because Polygon only allows withdrawals from a particular address to go to that same address on mainnet, we need to * have some sort of contract that can guarantee identical addresses on Polygon and Ethereum. This contract is intended * to be completely immutable, so it's guaranteed that the contract on each side is configured identically as long as * it is created via create2. create2 is an alternative creation method that uses a different address determination * mechanism from normal create. * Normal create: address = hash(deployer_address, deployer_nonce) * create2: address = hash(0xFF, sender, salt, bytecode) * This ultimately allows create2 to generate deterministic addresses that don't depend on the transaction count of the * sender. */ contract PolygonTokenBridger is Lockable { using SafeERC20 for PolygonIERC20; using SafeERC20 for IERC20; // Gas token for Polygon. MaticToken public constant maticToken = MaticToken(0x0000000000000000000000000000000000001010); // Should be set to HubPool on Ethereum, or unused on Polygon. address public immutable destination; // WETH contract on Ethereum. WETH9 public immutable l1Weth; /** * @notice Constructs Token Bridger contract. * @param _destination Where to send tokens to for this network. * @param _l1Weth Ethereum WETH address. */ constructor(address _destination, WETH9 _l1Weth) { destination = _destination; l1Weth = _l1Weth; } /** * @notice Called by Polygon SpokePool to send tokens over bridge to contract with the same address as this. * @param token Token to bridge. * @param amount Amount to bridge. * @param isMatic True if token is MATIC. */ function send( PolygonIERC20 token, uint256 amount, bool isMatic ) public nonReentrant { token.safeTransferFrom(msg.sender, address(this), amount); // In the wMatic case, this unwraps. For other ERC20s, this is the burn/send action. token.withdraw(amount); // This takes the token that was withdrawn and calls withdraw on the "native" ERC20. if (isMatic) maticToken.withdraw{ value: amount }(amount); } /** * @notice Called by someone to send tokens to the destination, which should be set to the HubPool. * @param token Token to send to destination. */ function retrieve(IERC20 token) public nonReentrant { token.safeTransfer(destination, token.balanceOf(address(this))); } receive() external payable { // Note: this should only happen on the mainnet side where ETH is sent to the contract directly by the bridge. if (functionCallStackOriginatesFromOutsideThisContract()) l1Weth.deposit{ value: address(this).balance }(); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./MerkleLib.sol"; import "./interfaces/WETH9.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@uma/core/contracts/common/implementation/Testable.sol"; import "@uma/core/contracts/common/implementation/MultiCaller.sol"; import "./Lockable.sol"; import "./MerkleLib.sol"; import "./SpokePoolInterface.sol"; /** * @title SpokePool * @notice Base contract deployed on source and destination chains enabling depositors to transfer assets from source to * destination. Deposit orders are fulfilled by off-chain relayers who also interact with this contract. Deposited * tokens are locked on the source chain and relayers send the recipient the desired token currency and amount * on the destination chain. Locked source chain tokens are later sent over the canonical token bridge to L1 HubPool. * Relayers are refunded with destination tokens out of this contract after another off-chain actor, a "data worker", * submits a proof that the relayer correctly submitted a relay on this SpokePool. */ abstract contract SpokePool is SpokePoolInterface, Testable, Lockable, MultiCaller { using SafeERC20 for IERC20; using Address for address; // Address of the L1 contract that acts as the owner of this SpokePool. If this contract is deployed on Ethereum, // then this address should be set to the same owner as the HubPool and the whole system. address public crossDomainAdmin; // Address of the L1 contract that will send tokens to and receive tokens from this contract to fund relayer // refunds and slow relays. address public hubPool; // Address of WETH contract for this network. If an origin token matches this, then the caller can optionally // instruct this contract to wrap ETH when depositing. WETH9 public weth; // Timestamp when contract was constructed. Relays cannot have a quote time before this. uint32 public deploymentTime; // Any deposit quote times greater than or less than this value to the current contract time is blocked. Forces // caller to use an approximately "current" realized fee. Defaults to 10 minutes. uint32 public depositQuoteTimeBuffer = 600; // Count of deposits is used to construct a unique deposit identifier for this spoke pool. uint32 public numberOfDeposits; // Origin token to destination token routings can be turned on or off, which can enable or disable deposits. // A reverse mapping is stored on the L1 HubPool to enable or disable rebalance transfers from the HubPool to this // contract. mapping(address => mapping(uint256 => bool)) public enabledDepositRoutes; // Stores collection of merkle roots that can be published to this contract from the HubPool, which are referenced // by "data workers" via inclusion proofs to execute leaves in the roots. struct RootBundle { // Merkle root of slow relays that were not fully filled and whose recipient is still owed funds from the LP pool. bytes32 slowRelayRoot; // Merkle root of relayer refunds for successful relays. bytes32 relayerRefundRoot; // This is a 2D bitmap tracking which leafs in the relayer refund root have been claimed, with max size of // 256x256 leaves per root. mapping(uint256 => uint256) claimedBitmap; } // This contract can store as many root bundles as the HubPool chooses to publish here. RootBundle[] public rootBundles; // Each relay is associated with the hash of parameters that uniquely identify the original deposit and a relay // attempt for that deposit. The relay itself is just represented as the amount filled so far. The total amount to // relay, the fees, and the agents are all parameters included in the hash key. mapping(bytes32 => uint256) public relayFills; /**************************************** * EVENTS * ****************************************/ event SetXDomainAdmin(address indexed newAdmin); event SetHubPool(address indexed newHubPool); event EnabledDepositRoute(address indexed originToken, uint256 indexed destinationChainId, bool enabled); event SetDepositQuoteTimeBuffer(uint32 newBuffer); event FundsDeposited( uint256 amount, uint256 destinationChainId, uint64 relayerFeePct, uint32 indexed depositId, uint32 quoteTimestamp, address indexed originToken, address recipient, address indexed depositor ); event RequestedSpeedUpDeposit( uint64 newRelayerFeePct, uint32 indexed depositId, address indexed depositor, bytes depositorSignature ); event FilledRelay( bytes32 indexed relayHash, uint256 amount, uint256 totalFilledAmount, uint256 fillAmount, uint256 indexed repaymentChainId, uint256 originChainId, uint64 relayerFeePct, uint64 realizedLpFeePct, uint32 depositId, address destinationToken, address indexed relayer, address depositor, address recipient ); event ExecutedSlowRelayRoot( bytes32 indexed relayHash, uint256 amount, uint256 totalFilledAmount, uint256 fillAmount, uint256 originChainId, uint64 relayerFeePct, uint64 realizedLpFeePct, uint32 depositId, address destinationToken, address indexed caller, address depositor, address recipient ); event RelayedRootBundle(uint32 indexed rootBundleId, bytes32 relayerRefundRoot, bytes32 slowRelayRoot); event ExecutedRelayerRefundRoot( uint256 amountToReturn, uint256 chainId, uint256[] refundAmounts, uint32 indexed rootBundleId, uint32 indexed leafId, address l2TokenAddress, address[] refundAddresses, address indexed caller ); event TokensBridged( uint256 amountToReturn, uint256 indexed chainId, uint32 indexed leafId, address indexed l2TokenAddress, address caller ); /** * @notice Construct the base SpokePool. * @param _crossDomainAdmin Cross domain admin to set. Can be changed by admin. * @param _hubPool Hub pool address to set. Can be changed by admin. * @param _wethAddress Weth address for this network to set. * @param timerAddress Timer address to set. */ constructor( address _crossDomainAdmin, address _hubPool, address _wethAddress, address timerAddress ) Testable(timerAddress) { _setCrossDomainAdmin(_crossDomainAdmin); _setHubPool(_hubPool); deploymentTime = uint32(getCurrentTime()); weth = WETH9(_wethAddress); } /**************************************** * MODIFIERS * ****************************************/ modifier onlyEnabledRoute(address originToken, uint256 destinationId) { require(enabledDepositRoutes[originToken][destinationId], "Disabled route"); _; } // Implementing contract needs to override _requireAdminSender() to ensure that admin functions are protected // appropriately. modifier onlyAdmin() { _requireAdminSender(); _; } /************************************** * ADMIN FUNCTIONS * **************************************/ /** * @notice Change cross domain admin address. Callable by admin only. * @param newCrossDomainAdmin New cross domain admin. */ function setCrossDomainAdmin(address newCrossDomainAdmin) public override onlyAdmin nonReentrant { _setCrossDomainAdmin(newCrossDomainAdmin); } /** * @notice Change L1 hub pool address. Callable by admin only. * @param newHubPool New hub pool. */ function setHubPool(address newHubPool) public override onlyAdmin nonReentrant { _setHubPool(newHubPool); } /** * @notice Enable/Disable an origin token => destination chain ID route for deposits. Callable by admin only. * @param originToken Token that depositor can deposit to this contract. * @param destinationChainId Chain ID for where depositor wants to receive funds. * @param enabled True to enable deposits, False otherwise. */ function setEnableRoute( address originToken, uint256 destinationChainId, bool enabled ) public override onlyAdmin nonReentrant { enabledDepositRoutes[originToken][destinationChainId] = enabled; emit EnabledDepositRoute(originToken, destinationChainId, enabled); } /** * @notice Change allowance for deposit quote time to differ from current block time. Callable by admin only. * @param newDepositQuoteTimeBuffer New quote time buffer. */ function setDepositQuoteTimeBuffer(uint32 newDepositQuoteTimeBuffer) public override onlyAdmin nonReentrant { depositQuoteTimeBuffer = newDepositQuoteTimeBuffer; emit SetDepositQuoteTimeBuffer(newDepositQuoteTimeBuffer); } /** * @notice This method stores a new root bundle in this contract that can be executed to refund relayers, fulfill * slow relays, and send funds back to the HubPool on L1. This method can only be called by the admin and is * designed to be called as part of a cross-chain message from the HubPool's executeRootBundle method. * @param relayerRefundRoot Merkle root containing relayer refund leaves that can be individually executed via * executeRelayerRefundRoot(). * @param slowRelayRoot Merkle root containing slow relay fulfillment leaves that can be individually executed via * executeSlowRelayRoot(). */ function relayRootBundle(bytes32 relayerRefundRoot, bytes32 slowRelayRoot) public override onlyAdmin nonReentrant { uint32 rootBundleId = uint32(rootBundles.length); RootBundle storage rootBundle = rootBundles.push(); rootBundle.relayerRefundRoot = relayerRefundRoot; rootBundle.slowRelayRoot = slowRelayRoot; emit RelayedRootBundle(rootBundleId, relayerRefundRoot, slowRelayRoot); } /************************************** * DEPOSITOR FUNCTIONS * **************************************/ /** * @notice Called by user to bridge funds from origin to destination chain. Depositor will effectively lock * tokens in this contract and receive a destination token on the destination chain. The origin => destination * token mapping is stored on the L1 HubPool. * @notice The caller must first approve this contract to spend amount of originToken. * @notice The originToken => destinationChainId must be enabled. * @notice This method is payable because the caller is able to deposit ETH if the originToken is WETH and this * function will handle wrapping ETH. * @param recipient Address to receive funds at on destination chain. * @param originToken Token to lock into this contract to initiate deposit. * @param amount Amount of tokens to deposit. Will be amount of tokens to receive less fees. * @param destinationChainId Denotes network where user will receive funds from SpokePool by a relayer. * @param relayerFeePct % of deposit amount taken out to incentivize a fast relayer. * @param quoteTimestamp Timestamp used by relayers to compute this deposit's realizedLPFeePct which is paid * to LP pool on HubPool. */ function deposit( address recipient, address originToken, uint256 amount, uint256 destinationChainId, uint64 relayerFeePct, uint32 quoteTimestamp ) public payable override onlyEnabledRoute(originToken, destinationChainId) nonReentrant { // We limit the relay fees to prevent the user spending all their funds on fees. require(relayerFeePct < 0.5e18, "invalid relayer fee"); // This function assumes that L2 timing cannot be compared accurately and consistently to L1 timing. Therefore, // block.timestamp is different from the L1 EVM's. Therefore, the quoteTimestamp must be within a configurable // buffer of this contract's block time to allow for this variance. // Note also that quoteTimestamp cannot be less than the buffer otherwise the following arithmetic can result // in underflow. This isn't a problem as the deposit will revert, but the error might be unexpected for clients. require( getCurrentTime() >= quoteTimestamp - depositQuoteTimeBuffer && getCurrentTime() <= quoteTimestamp + depositQuoteTimeBuffer, "invalid quote time" ); // If the address of the origin token is a WETH contract and there is a msg.value with the transaction // then the user is sending ETH. In this case, the ETH should be deposited to WETH. if (originToken == address(weth) && msg.value > 0) { require(msg.value == amount, "msg.value must match amount"); weth.deposit{ value: msg.value }(); // Else, it is a normal ERC20. In this case pull the token from the users wallet as per normal. // Note: this includes the case where the L2 user has WETH (already wrapped ETH) and wants to bridge them. // In this case the msg.value will be set to 0, indicating a "normal" ERC20 bridging action. } else IERC20(originToken).safeTransferFrom(msg.sender, address(this), amount); emit FundsDeposited( amount, destinationChainId, relayerFeePct, numberOfDeposits, quoteTimestamp, originToken, recipient, msg.sender ); // Increment count of deposits so that deposit ID for this spoke pool is unique. numberOfDeposits += 1; } /** * @notice Convenience method that depositor can use to signal to relayer to use updated fee. * @notice Relayer should only use events emitted by this function to submit fills with updated fees, otherwise they * risk their fills getting disputed for being invalid, for example if the depositor never actually signed the * update fee message. * @notice This function will revert if the depositor did not sign a message containing the updated fee for the * deposit ID stored in this contract. If the deposit ID is for another contract, or the depositor address is * incorrect, or the updated fee is incorrect, then the signature will not match and this function will revert. * @param depositor Signer of the update fee message who originally submitted the deposit. If the deposit doesn't * exist, then the relayer will not be able to fill any relay, so the caller should validate that the depositor * did in fact submit a relay. * @param newRelayerFeePct New relayer fee that relayers can use. * @param depositId Deposit to update fee for that originated in this contract. * @param depositorSignature Signed message containing the depositor address, this contract chain ID, the updated * relayer fee %, and the deposit ID. This signature is produced by signing a hash of data according to the * EIP-191 standard. See more in the _verifyUpdateRelayerFeeMessage() comments. */ function speedUpDeposit( address depositor, uint64 newRelayerFeePct, uint32 depositId, bytes memory depositorSignature ) public override nonReentrant { //SWC-Signature Malleability: L336 _verifyUpdateRelayerFeeMessage(depositor, chainId(), newRelayerFeePct, depositId, depositorSignature); // Assuming the above checks passed, a relayer can take the signature and the updated relayer fee information // from the following event to submit a fill with an updated fee %. emit RequestedSpeedUpDeposit(newRelayerFeePct, depositId, depositor, depositorSignature); } /************************************** * RELAYER FUNCTIONS * **************************************/ /** * @notice Called by relayer to fulfill part of a deposit by sending destination tokens to the receipient. * Relayer is expected to pass in unique identifying information for deposit that they want to fulfill, and this * relay submission will be validated by off-chain data workers who can dispute this relay if any part is invalid. * If the relay is valid, then the relayer will be refunded on their desired repayment chain. If relay is invalid, * then relayer will not receive any refund. * @notice All of the deposit data can be found via on-chain events from the origin SpokePool, except for the * realizedLpFeePct which is a function of the HubPool's utilization at the deposit quote time. This fee % * is deterministic based on the quote time, so the relayer should just compute it using the canonical algorithm * as described in a UMIP linked to the HubPool's identifier. * @param depositor Depositor on origin chain who set this chain as the destination chain. * @param recipient Specified recipient on this chain. * @param destinationToken Token to send to recipient. Should be mapped to the origin token, origin chain ID * and this chain ID via a mapping on the HubPool. * @param amount Full size of the deposit. * @param maxTokensToSend Max amount of tokens to send recipient. If higher than amount, then caller will * send recipient the full relay amount. * @param repaymentChainId Chain of SpokePool where relayer wants to be refunded after the challenge window has * passed. * @param originChainId Chain of SpokePool where deposit originated. * @param realizedLpFeePct Fee % based on L1 HubPool utilization at deposit quote time. Deterministic based on * quote time. * @param relayerFeePct Fee % to keep as relayer, specified by depositor. * @param depositId Unique deposit ID on origin spoke pool. */ function fillRelay( address depositor, address recipient, address destinationToken, uint256 amount, uint256 maxTokensToSend, uint256 repaymentChainId, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint32 depositId ) public nonReentrant { // Each relay attempt is mapped to the hash of data uniquely identifying it, which includes the deposit data // such as the origin chain ID and the deposit ID, and the data in a relay attempt such as who the recipient // is, which chain and currency the recipient wants to receive funds on, and the relay fees. SpokePoolInterface.RelayData memory relayData = SpokePoolInterface.RelayData({ depositor: depositor, recipient: recipient, destinationToken: destinationToken, amount: amount, realizedLpFeePct: realizedLpFeePct, relayerFeePct: relayerFeePct, depositId: depositId, originChainId: originChainId }); bytes32 relayHash = _getRelayHash(relayData); uint256 fillAmountPreFees = _fillRelay(relayHash, relayData, maxTokensToSend, relayerFeePct, false); _emitFillRelay(relayHash, fillAmountPreFees, repaymentChainId, relayerFeePct, relayData); } /** * @notice Called by relayer to execute same logic as calling fillRelay except that relayer is using an updated * relayer fee %. The fee % must have been emitted in a message cryptographically signed by the depositor. * @notice By design, the depositor probably emitted the message with the updated fee by calling speedUpRelay(). * @param depositor Depositor on origin chain who set this chain as the destination chain. * @param recipient Specified recipient on this chain. * @param destinationToken Token to send to recipient. Should be mapped to the origin token, origin chain ID * and this chain ID via a mapping on the HubPool. * @param amount Full size of the deposit. * @param maxTokensToSend Max amount of tokens to send recipient. If higher than amount, then caller will * send recipient the full relay amount. * @param repaymentChainId Chain of SpokePool where relayer wants to be refunded after the challenge window has * passed. * @param originChainId Chain of SpokePool where deposit originated. * @param realizedLpFeePct Fee % based on L1 HubPool utilization at deposit quote time. Deterministic based on * quote time. * @param relayerFeePct Original fee % to keep as relayer set by depositor. * @param newRelayerFeePct New fee % to keep as relayer also specified by depositor. * @param depositId Unique deposit ID on origin spoke pool. * @param depositorSignature Depositor-signed message containing updated fee %. */ function fillRelayWithUpdatedFee( address depositor, address recipient, address destinationToken, uint256 amount, uint256 maxTokensToSend, uint256 repaymentChainId, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint64 newRelayerFeePct, uint32 depositId, bytes memory depositorSignature ) public override nonReentrant { //SWC-Signature Malleability: L439 _verifyUpdateRelayerFeeMessage(depositor, originChainId, newRelayerFeePct, depositId, depositorSignature); // Now follow the default fillRelay flow with the updated fee and the original relay hash. RelayData memory relayData = RelayData({ depositor: depositor, recipient: recipient, destinationToken: destinationToken, amount: amount, realizedLpFeePct: realizedLpFeePct, relayerFeePct: relayerFeePct, depositId: depositId, originChainId: originChainId }); bytes32 relayHash = _getRelayHash(relayData); uint256 fillAmountPreFees = _fillRelay(relayHash, relayData, maxTokensToSend, newRelayerFeePct, false); _emitFillRelay(relayHash, fillAmountPreFees, repaymentChainId, newRelayerFeePct, relayData); } /************************************** * DATA WORKER FUNCTIONS * **************************************/ /** * @notice Executes a slow relay leaf stored as part of a root bundle. Will send the full amount remaining in the * relay to the recipient, less fees. * @param depositor Depositor on origin chain who set this chain as the destination chain. * @param recipient Specified recipient on this chain. * @param destinationToken Token to send to recipient. Should be mapped to the origin token, origin chain ID * and this chain ID via a mapping on the HubPool. * @param amount Full size of the deposit. * @param originChainId Chain of SpokePool where deposit originated. * @param realizedLpFeePct Fee % based on L1 HubPool utilization at deposit quote time. Deterministic based on * quote time. * @param relayerFeePct Original fee % to keep as relayer set by depositor. * @param depositId Unique deposit ID on origin spoke pool. * @param rootBundleId Unique ID of root bundle containing slow relay root that this leaf is contained in. * @param proof Inclusion proof for this leaf in slow relay root in root bundle. */ function executeSlowRelayRoot( address depositor, address recipient, address destinationToken, uint256 amount, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint32 depositId, uint32 rootBundleId, bytes32[] memory proof ) public virtual override nonReentrant { _executeSlowRelayRoot( depositor, recipient, destinationToken, amount, originChainId, realizedLpFeePct, relayerFeePct, depositId, rootBundleId, proof ); } /** * @notice Executes a relayer refund leaf stored as part of a root bundle. Will send the relayer the amount they * sent to the recipient plus a relayer fee. * @param rootBundleId Unique ID of root bundle containing relayer refund root that this leaf is contained in. * @param relayerRefundLeaf Contains all data neccessary to reconstruct leaf contained in root bundle and to * refund relayer. This data structure is explained in detail in the SpokePoolInterface. * @param proof Inclusion proof for this leaf in relayer refund root in root bundle. */ function executeRelayerRefundRoot( uint32 rootBundleId, SpokePoolInterface.RelayerRefundLeaf memory relayerRefundLeaf, bytes32[] memory proof ) public virtual override nonReentrant { _executeRelayerRefundRoot(rootBundleId, relayerRefundLeaf, proof); } /************************************** * VIEW FUNCTIONS * **************************************/ /** * @notice Returns chain ID for this network. * @dev Some L2s like ZKSync don't support the CHAIN_ID opcode so we allow the implementer to override this. */ function chainId() public view override returns (uint256) { return block.chainid; } /************************************** * INTERNAL FUNCTIONS * **************************************/ // Verifies inclusion proof of leaf in root, sends relayer their refund, and sends to HubPool any rebalance // transfers. function _executeRelayerRefundRoot( uint32 rootBundleId, SpokePoolInterface.RelayerRefundLeaf memory relayerRefundLeaf, bytes32[] memory proof ) internal { // Check integrity of leaf structure: require(relayerRefundLeaf.chainId == chainId(), "Invalid chainId"); require(relayerRefundLeaf.refundAddresses.length == relayerRefundLeaf.refundAmounts.length, "invalid leaf"); RootBundle storage rootBundle = rootBundles[rootBundleId]; // Check that inclusionProof proves that relayerRefundLeaf is contained within the relayer refund root. // Note: This should revert if the relayerRefundRoot is uninitialized. require(MerkleLib.verifyRelayerRefund(rootBundle.relayerRefundRoot, relayerRefundLeaf, proof), "Bad Proof"); // Verify the leafId in the leaf has not yet been claimed. require(!MerkleLib.isClaimed(rootBundle.claimedBitmap, relayerRefundLeaf.leafId), "Already claimed"); // Set leaf as claimed in bitmap. This is passed by reference to the storage rootBundle. MerkleLib.setClaimed(rootBundle.claimedBitmap, relayerRefundLeaf.leafId); // Send each relayer refund address the associated refundAmount for the L2 token address. // Note: Even if the L2 token is not enabled on this spoke pool, we should still refund relayers. for (uint32 i = 0; i < relayerRefundLeaf.refundAmounts.length; i++) { uint256 amount = relayerRefundLeaf.refundAmounts[i]; if (amount > 0) IERC20(relayerRefundLeaf.l2TokenAddress).safeTransfer(relayerRefundLeaf.refundAddresses[i], amount); } // If leaf's amountToReturn is positive, then send L2 --> L1 message to bridge tokens back via // chain-specific bridging method. if (relayerRefundLeaf.amountToReturn > 0) { _bridgeTokensToHubPool(relayerRefundLeaf); emit TokensBridged( relayerRefundLeaf.amountToReturn, relayerRefundLeaf.chainId, relayerRefundLeaf.leafId, relayerRefundLeaf.l2TokenAddress, msg.sender ); } emit ExecutedRelayerRefundRoot( relayerRefundLeaf.amountToReturn, relayerRefundLeaf.chainId, relayerRefundLeaf.refundAmounts, rootBundleId, relayerRefundLeaf.leafId, relayerRefundLeaf.l2TokenAddress, relayerRefundLeaf.refundAddresses, msg.sender ); } // Verifies inclusion proof of leaf in root and sends recipient remainder of relay. Marks relay as filled. function _executeSlowRelayRoot( address depositor, address recipient, address destinationToken, uint256 amount, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint32 depositId, uint32 rootBundleId, bytes32[] memory proof ) internal { RelayData memory relayData = RelayData({ depositor: depositor, recipient: recipient, destinationToken: destinationToken, amount: amount, originChainId: originChainId, realizedLpFeePct: realizedLpFeePct, relayerFeePct: relayerFeePct, depositId: depositId }); require( MerkleLib.verifySlowRelayFulfillment(rootBundles[rootBundleId].slowRelayRoot, relayData, proof), "Invalid proof" ); bytes32 relayHash = _getRelayHash(relayData); // Note: use relayAmount as the max amount to send, so the relay is always completely filled by the contract's // funds in all cases. uint256 fillAmountPreFees = _fillRelay(relayHash, relayData, relayData.amount, relayerFeePct, true); _emitExecutedSlowRelayRoot(relayHash, fillAmountPreFees, relayData); } function _setCrossDomainAdmin(address newCrossDomainAdmin) internal { require(newCrossDomainAdmin != address(0), "Bad bridge router address"); crossDomainAdmin = newCrossDomainAdmin; emit SetXDomainAdmin(crossDomainAdmin); } function _setHubPool(address newHubPool) internal { require(newHubPool != address(0), "Bad hub pool address"); hubPool = newHubPool; emit SetHubPool(hubPool); } // Should be overriden by implementing contract depending on how L2 handles sending tokens to L1. function _bridgeTokensToHubPool(SpokePoolInterface.RelayerRefundLeaf memory relayerRefundLeaf) internal virtual; function _verifyUpdateRelayerFeeMessage( address depositor, uint256 originChainId, uint64 newRelayerFeePct, uint32 depositId, bytes memory depositorSignature ) internal view { // A depositor can request to speed up an un-relayed deposit by signing a hash containing the relayer // fee % to update to and information uniquely identifying the deposit to relay. This information ensures // that this signature cannot be re-used for other deposits. The version string is included as a precaution // in case this contract is upgraded. // Note: we use encode instead of encodePacked because it is more secure, more in the "warning" section // here: https://docs.soliditylang.org/en/v0.8.11/abi-spec.html#non-standard-packed-mode bytes32 expectedDepositorMessageHash = keccak256( abi.encode("ACROSS-V2-FEE-1.0", newRelayerFeePct, depositId, originChainId) ); // Check the hash corresponding to the https://eth.wiki/json-rpc/API#eth_sign[eth_sign] // JSON-RPC method as part of EIP-191. We use OZ's signature checker library which adds support for // EIP-1271 which can verify messages signed by smart contract wallets like Argent and Gnosis safes. // If the depositor signed a message with a different updated fee (or any other param included in the // above keccak156 hash), then this will revert. bytes32 ethSignedMessageHash = ECDSA.toEthSignedMessageHash(expectedDepositorMessageHash); _verifyDepositorUpdateFeeMessage(depositor, ethSignedMessageHash, depositorSignature); } // This function is isolated and made virtual to allow different L2's to implement chain specific recovery of // signers from signatures because some L2s might not support ecrecover, such as those with account abstraction // like ZKSync. function _verifyDepositorUpdateFeeMessage( address depositor, bytes32 ethSignedMessageHash, bytes memory depositorSignature ) internal view virtual { // Note: no need to worry about reentrancy from contract deployed at depositor address since // SignatureChecker.isValidSignatureNow is a non state-modifying STATICCALL: // - https://github.com/OpenZeppelin/openzeppelin-contracts/blob/63b466901fb015538913f811c5112a2775042177/contracts/utils/cryptography/SignatureChecker.sol#L35 // - https://github.com/ethereum/EIPs/pull/214 require( SignatureChecker.isValidSignatureNow(depositor, ethSignedMessageHash, depositorSignature), "invalid signature" ); } function _computeAmountPreFees(uint256 amount, uint64 feesPct) private pure returns (uint256) { return (1e18 * amount) / (1e18 - feesPct); } function _computeAmountPostFees(uint256 amount, uint64 feesPct) private pure returns (uint256) { return (amount * (1e18 - feesPct)) / 1e18; } function _getRelayHash(SpokePoolInterface.RelayData memory relayData) private pure returns (bytes32) { return keccak256(abi.encode(relayData)); } // Unwraps ETH and does a transfer to a recipient address. If the recipient is a smart contract then sends WETH. function _unwrapWETHTo(address payable to, uint256 amount) internal { if (address(to).isContract()) { IERC20(address(weth)).safeTransfer(to, amount); } else { weth.withdraw(amount); to.transfer(amount); } } // @notice Caller specifies the max amount of tokens to send to user. Based on this amount and the amount of the // relay remaining (as stored in the relayFills mapping), pull the amount of tokens from the caller ancillaryData // and send to the caller. // @dev relayFills keeps track of pre-fee fill amounts as a convenience to relayers who want to specify round // numbers for the maxTokensToSend parameter or convenient numbers like 100 (i.e. relayers who will fully // fill any relay up to 100 tokens, and partial fill with 100 tokens for larger relays). function _fillRelay( bytes32 relayHash, RelayData memory relayData, uint256 maxTokensToSend, uint64 updatableRelayerFeePct, bool useContractFunds ) internal returns (uint256 fillAmountPreFees) { // We limit the relay fees to prevent the user spending all their funds on fees. Note that 0.5e18 (i.e. 50%) // fees are just magic numbers. The important point is to prevent the total fee from being 100%, otherwise // computing the amount pre fees runs into divide-by-0 issues. require(updatableRelayerFeePct < 0.5e18 && relayData.realizedLpFeePct < 0.5e18, "invalid fees"); // Check that the relay has not already been completely filled. Note that the relays mapping will point to // the amount filled so far for a particular relayHash, so this will start at 0 and increment with each fill. require(relayFills[relayHash] < relayData.amount, "relay filled"); // Stores the equivalent amount to be sent by the relayer before fees have been taken out. if (maxTokensToSend == 0) return 0; // Derive the amount of the relay filled if the caller wants to send exactly maxTokensToSend tokens to // the recipient. For example, if the user wants to send 10 tokens to the recipient, the full relay amount // is 100, and the fee %'s total 5%, then this computation would return ~10.5, meaning that to fill 10.5/100 // of the full relay size, the caller would need to send 10 tokens to the user. fillAmountPreFees = _computeAmountPreFees( maxTokensToSend, (relayData.realizedLpFeePct + updatableRelayerFeePct) ); // If user's specified max amount to send is greater than the amount of the relay remaining pre-fees, // we'll pull exactly enough tokens to complete the relay. uint256 amountToSend = maxTokensToSend; uint256 amountRemainingInRelay = relayData.amount - relayFills[relayHash]; if (amountRemainingInRelay < fillAmountPreFees) { fillAmountPreFees = amountRemainingInRelay; // The user will fulfill the remainder of the relay, so we need to compute exactly how many tokens post-fees // that they need to send to the recipient. amountToSend = _computeAmountPostFees( fillAmountPreFees, relayData.realizedLpFeePct + updatableRelayerFeePct ); } // relayFills keeps track of pre-fee fill amounts as a convenience to relayers who want to specify round // numbers for the maxTokensToSend parameter or convenient numbers like 100 (i.e. relayers who will fully // fill any relay up to 100 tokens, and partial fill with 100 tokens for larger relays). relayFills[relayHash] += fillAmountPreFees; // If relay token is weth then unwrap and send eth. if (relayData.destinationToken == address(weth)) { // Note: useContractFunds is True if we want to send funds to the recipient directly out of this contract, // otherwise we expect the caller to send funds to the recipient. If useContractFunds is True and the // recipient wants WETH, then we can assume that WETH is already in the contract, otherwise we'll need the // the user to send WETH to this contract. Regardless, we'll need to unwrap it before sending to the user. if (!useContractFunds) IERC20(relayData.destinationToken).safeTransferFrom(msg.sender, address(this), amountToSend); _unwrapWETHTo(payable(relayData.recipient), amountToSend); // Else, this is a normal ERC20 token. Send to recipient. } else { // Note: Similar to note above, send token directly from the contract to the user in the slow relay case. if (!useContractFunds) IERC20(relayData.destinationToken).safeTransferFrom(msg.sender, relayData.recipient, amountToSend); else IERC20(relayData.destinationToken).safeTransfer(relayData.recipient, amountToSend); } } // The following internal methods emit events with many params to overcome solidity stack too deep issues. function _emitFillRelay( bytes32 relayHash, uint256 fillAmount, uint256 repaymentChainId, uint64 relayerFeePct, RelayData memory relayData ) internal { emit FilledRelay( relayHash, relayData.amount, relayFills[relayHash], fillAmount, repaymentChainId, relayData.originChainId, relayerFeePct, relayData.realizedLpFeePct, relayData.depositId, relayData.destinationToken, msg.sender, relayData.depositor, relayData.recipient ); } function _emitExecutedSlowRelayRoot( bytes32 relayHash, uint256 fillAmount, RelayData memory relayData ) internal { emit ExecutedSlowRelayRoot( relayHash, relayData.amount, relayFills[relayHash], fillAmount, relayData.originChainId, relayData.relayerFeePct, relayData.realizedLpFeePct, relayData.depositId, relayData.destinationToken, msg.sender, relayData.depositor, relayData.recipient ); } // Implementing contract needs to override this to ensure that only the appropriate cross chain admin can execute // certain admin functions. For L2 contracts, the cross chain admin refers to some L1 address or contract, and for // L1, this would just be the same admin of the HubPool. function _requireAdminSender() internal virtual; // Added to enable the this contract to receive ETH. Used when unwrapping Weth. receive() external payable {} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./interfaces/WETH9.sol"; import "@eth-optimism/contracts/libraries/bridge/CrossDomainEnabled.sol"; import "@eth-optimism/contracts/libraries/constants/Lib_PredeployAddresses.sol"; import "@eth-optimism/contracts/L2/messaging/IL2ERC20Bridge.sol"; import "./SpokePool.sol"; import "./SpokePoolInterface.sol"; /** * @notice OVM specific SpokePool. Uses OVM cross-domain-enabled logic to implement admin only access to functions. */ contract Optimism_SpokePool is CrossDomainEnabled, SpokePool { // "l1Gas" parameter used in call to bridge tokens from this contract back to L1 via IL2ERC20Bridge. Currently // unused by bridge but included for future compatibility. uint32 public l1Gas = 5_000_000; // ETH is an ERC20 on OVM. address public l2Eth = address(Lib_PredeployAddresses.OVM_ETH); event OptimismTokensBridged(address indexed l2Token, address target, uint256 numberOfTokensBridged, uint256 l1Gas); event SetL1Gas(uint32 indexed newL1Gas); /** * @notice Construct the OVM SpokePool. * @param _crossDomainAdmin Cross domain admin to set. Can be changed by admin. * @param _hubPool Hub pool address to set. Can be changed by admin. * @param timerAddress Timer address to set. */ constructor( address _crossDomainAdmin, address _hubPool, address timerAddress ) CrossDomainEnabled(Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER) SpokePool(_crossDomainAdmin, _hubPool, 0x4200000000000000000000000000000000000006, timerAddress) {} /******************************************* * OPTIMISM-SPECIFIC ADMIN FUNCTIONS * *******************************************/ /** * @notice Change L1 gas limit. Callable only by admin. * @param newl1Gas New L1 gas limit to set. */ function setL1GasLimit(uint32 newl1Gas) public onlyAdmin { l1Gas = newl1Gas; emit SetL1Gas(newl1Gas); } /************************************** * DATA WORKER FUNCTIONS * **************************************/ /** * @notice Wraps any ETH into WETH before executing base function. This is neccessary because SpokePool receives * ETH over the canonical token bridge instead of WETH. * @inheritdoc SpokePool */ function executeSlowRelayRoot( address depositor, address recipient, address destinationToken, uint256 totalRelayAmount, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint32 depositId, uint32 rootBundleId, bytes32[] memory proof ) public override(SpokePool) nonReentrant { if (destinationToken == address(weth)) _depositEthToWeth(); _executeSlowRelayRoot( depositor, recipient, destinationToken, totalRelayAmount, originChainId, realizedLpFeePct, relayerFeePct, depositId, rootBundleId, proof ); } /** * @notice Wraps any ETH into WETH before executing base function. This is necessary because SpokePool receives * ETH over the canonical token bridge instead of WETH. * @inheritdoc SpokePool */ function executeRelayerRefundRoot( uint32 rootBundleId, SpokePoolInterface.RelayerRefundLeaf memory relayerRefundLeaf, bytes32[] memory proof ) public override(SpokePool) nonReentrant { if (relayerRefundLeaf.l2TokenAddress == address(weth)) _depositEthToWeth(); _executeRelayerRefundRoot(rootBundleId, relayerRefundLeaf, proof); } /************************************** * INTERNAL FUNCTIONS * **************************************/ // Wrap any ETH owned by this contract so we can send expected L2 token to recipient. This is necessary because // this SpokePool will receive ETH from the canonical token bridge instead of WETH. Its not sufficient to execute // this logic inside a fallback method that executes when this contract receives ETH because ETH is an ERC20 // on the OVM. function _depositEthToWeth() internal { if (address(this).balance > 0) weth.deposit{ value: address(this).balance }(); } function _bridgeTokensToHubPool(RelayerRefundLeaf memory relayerRefundLeaf) internal override { // If the token being bridged is WETH then we need to first unwrap it to ETH and then send ETH over the // canonical bridge. On Optimism, this is address 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000. if (relayerRefundLeaf.l2TokenAddress == address(weth)) { WETH9(relayerRefundLeaf.l2TokenAddress).withdraw(relayerRefundLeaf.amountToReturn); // Unwrap into ETH. relayerRefundLeaf.l2TokenAddress = l2Eth; // Set the l2TokenAddress to ETH. } IL2ERC20Bridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo( relayerRefundLeaf.l2TokenAddress, // _l2Token. Address of the L2 token to bridge over. hubPool, // _to. Withdraw, over the bridge, to the l1 pool contract. relayerRefundLeaf.amountToReturn, // _amount. l1Gas, // _l1Gas. Unused, but included for potential forward compatibility considerations "" // _data. We don't need to send any data for the bridging action. ); emit OptimismTokensBridged(relayerRefundLeaf.l2TokenAddress, hubPool, relayerRefundLeaf.amountToReturn, l1Gas); } // Apply OVM-specific transformation to cross domain admin address on L1. function _requireAdminSender() internal override onlyFromCrossDomainAccount(crossDomainAdmin) {} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./interfaces/WETH9.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./SpokePool.sol"; import "./SpokePoolInterface.sol"; import "./PolygonTokenBridger.sol"; // IFxMessageProcessor represents interface to process messages. interface IFxMessageProcessor { function processMessageFromRoot( uint256 stateId, address rootMessageSender, bytes calldata data ) external; } /** * @notice Polygon specific SpokePool. */ contract Polygon_SpokePool is IFxMessageProcessor, SpokePool { using SafeERC20 for PolygonIERC20; // Address of FxChild which sends and receives messages to and from L1. address public fxChild; // Contract deployed on L1 and L2 processes all cross-chain transfers between this contract and the the HubPool. // Required because bridging tokens from Polygon to Ethereum has special constraints. PolygonTokenBridger public polygonTokenBridger; // Internal variable that only flips temporarily to true upon receiving messages from L1. Used to authenticate that // the caller is the fxChild AND that the fxChild called processMessageFromRoot bool private callValidated = false; event PolygonTokensBridged(address indexed token, address indexed receiver, uint256 amount); event SetFxChild(address indexed newFxChild); event SetPolygonTokenBridger(address indexed polygonTokenBridger); // Note: validating calls this way ensures that strange calls coming from the fxChild won't be misinterpreted. // Put differently, just checking that msg.sender == fxChild is not sufficient. // All calls that have admin priviledges must be fired from within the processMessageFromRoot method that's gone // through validation where the sender is checked and the root (mainnet) sender is also validated. // This modifier sets the callValidated variable so this condition can be checked in _requireAdminSender(). modifier validateInternalCalls() { // This sets a variable indicating that we're now inside a validated call. // Note: this is used by other methods to ensure that this call has been validated by this method and is not // spoofed. See callValidated = true; _; // Reset callValidated to false to disallow admin calls after this method exits. callValidated = false; } /** * @notice Construct the Polygon SpokePool. * @param _polygonTokenBridger Token routing contract that sends tokens from here to HubPool. Changeable by Admin. * @param _crossDomainAdmin Cross domain admin to set. Can be changed by admin. * @param _hubPool Hub pool address to set. Can be changed by admin. * @param _wmaticAddress Replaces _wethAddress for this network since MATIC is the gas token and sent via msg.value * on Polygon. * @param _fxChild FxChild contract, changeable by Admin. * @param timerAddress Timer address to set. */ constructor( PolygonTokenBridger _polygonTokenBridger, address _crossDomainAdmin, address _hubPool, address _wmaticAddress, // Note: wmatic is used here since it is the token sent via msg.value on polygon. address _fxChild, address timerAddress ) SpokePool(_crossDomainAdmin, _hubPool, _wmaticAddress, timerAddress) { polygonTokenBridger = _polygonTokenBridger; fxChild = _fxChild; } /******************************************************** * ARBITRUM-SPECIFIC CROSS-CHAIN ADMIN FUNCTIONS * ********************************************************/ /** * @notice Change FxChild address. Callable only by admin via processMessageFromRoot. * @param newFxChild New FxChild. */ function setFxChild(address newFxChild) public onlyAdmin nonReentrant { fxChild = newFxChild; emit SetFxChild(fxChild); } /** * @notice Change polygonTokenBridger address. Callable only by admin via processMessageFromRoot. * @param newPolygonTokenBridger New Polygon Token Bridger contract. */ function setPolygonTokenBridger(address payable newPolygonTokenBridger) public onlyAdmin nonReentrant { polygonTokenBridger = PolygonTokenBridger(newPolygonTokenBridger); emit SetPolygonTokenBridger(address(polygonTokenBridger)); } /** * @notice Called by FxChild upon receiving L1 message that targets this contract. Performs an additional check * that the L1 caller was the expected cross domain admin, and then delegate calls. * @notice Polygon bridge only executes this external function on the target Polygon contract when relaying * messages from L1, so all functions on this SpokePool are expected to originate via this call. * @dev stateId value isn't used because it isn't relevant for this method. It doesn't care what state sync * triggered this call. * @param rootMessageSender Original L1 sender of data. * @param data ABI encoded function call to execute on this contract. */ function processMessageFromRoot( uint256, /*stateId*/ address rootMessageSender, bytes calldata data ) public validateInternalCalls { // Validation logic. require(msg.sender == fxChild, "Not from fxChild"); require(rootMessageSender == crossDomainAdmin, "Not from mainnet admin"); // This uses delegatecall to take the information in the message and process it as a function call on this contract. (bool success, ) = address(this).delegatecall(data); require(success, "delegatecall failed"); } /************************************** * INTERNAL FUNCTIONS * **************************************/ function _bridgeTokensToHubPool(RelayerRefundLeaf memory relayerRefundLeaf) internal override { PolygonIERC20(relayerRefundLeaf.l2TokenAddress).safeIncreaseAllowance( address(polygonTokenBridger), relayerRefundLeaf.amountToReturn ); // Note: WETH is WMATIC on matic, so this tells the tokenbridger that this is an unwrappable native token. polygonTokenBridger.send( PolygonIERC20(relayerRefundLeaf.l2TokenAddress), relayerRefundLeaf.amountToReturn, address(weth) == relayerRefundLeaf.l2TokenAddress ); emit PolygonTokensBridged(relayerRefundLeaf.l2TokenAddress, address(this), relayerRefundLeaf.amountToReturn); } function _requireAdminSender() internal view override { require(callValidated, "Must call processMessageFromRoot"); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./interfaces/LpTokenFactoryInterface.sol"; import "@uma/core/contracts/common/implementation/ExpandedERC20.sol"; /** * @notice Factory to create new LP ERC20 tokens that represent a liquidity provider's position. HubPool is the * intended client of this contract. */ contract LpTokenFactory is LpTokenFactoryInterface { /** * @notice Deploys new LP token for L1 token. Sets caller as minter and burner of token. * @param l1Token L1 token to name in LP token name. * @return address of new LP token. */ function createLpToken(address l1Token) public returns (address) { ExpandedERC20 lpToken = new ExpandedERC20( _append("Across ", IERC20Metadata(l1Token).name(), " LP Token"), // LP Token Name _append("Av2-", IERC20Metadata(l1Token).symbol(), "-LP"), // LP Token Symbol IERC20Metadata(l1Token).decimals() // LP Token Decimals ); lpToken.addMember(1, msg.sender); // Set this contract as the LP Token's minter. lpToken.addMember(2, msg.sender); // Set this contract as the LP Token's burner. return address(lpToken); } function _append( string memory a, string memory b, string memory c ) internal pure returns (string memory) { return string(abi.encodePacked(a, b, c)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "./interfaces/WETH9.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./SpokePool.sol"; import "./SpokePoolInterface.sol"; /** * @notice Ethereum L1 specific SpokePool. Used on Ethereum L1 to facilitate L2->L1 transfers. */ contract Ethereum_SpokePool is SpokePool, Ownable { /** * @notice Construct the Ethereum SpokePool. * @param _hubPool Hub pool address to set. Can be changed by admin. * @param _wethAddress Weth address for this network to set. * @param timerAddress Timer address to set. */ constructor( address _hubPool, address _wethAddress, address timerAddress ) SpokePool(msg.sender, _hubPool, _wethAddress, timerAddress) {} /************************************** * INTERNAL FUNCTIONS * **************************************/ function _bridgeTokensToHubPool(RelayerRefundLeaf memory relayerRefundLeaf) internal override { IERC20(relayerRefundLeaf.l2TokenAddress).transfer(hubPool, relayerRefundLeaf.amountToReturn); } // Admin is simply owner which should be same account that owns the HubPool deployed on this network. A core // assumption of this contract system is that the HubPool is deployed on Ethereum. function _requireAdminSender() internal override onlyOwner {} } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; /** * @notice Contains common data structures and functions used by all SpokePool implementations. */ interface SpokePoolInterface { // This leaf is meant to be decoded in the SpokePool to pay out successful relayers. struct RelayerRefundLeaf { // This is the amount to return to the HubPool. This occurs when there is a PoolRebalanceLeaf netSendAmount that is // negative. This is just that value inverted. uint256 amountToReturn; // Used to verify that this is being executed on the correct destination chainId. uint256 chainId; // This array designates how much each of those addresses should be refunded. uint256[] refundAmounts; // Used as the index in the bitmap to track whether this leaf has been executed or not. uint32 leafId; // The associated L2TokenAddress that these claims apply to. address l2TokenAddress; // Must be same length as refundAmounts and designates each address that must be refunded. address[] refundAddresses; } // This struct represents the data to fully specify a relay. If any portion of this data differs, the relay is // considered to be completely distinct. Only one relay for a particular depositId, chainId pair should be // considered valid and repaid. This data is hashed and inserted into a the slow relay merkle root so that an off // chain validator can choose when to refund slow relayers. struct RelayData { // The address that made the deposit on the origin chain. address depositor; // The recipient address on the destination chain. address recipient; // The corresponding token address on the destination chain. address destinationToken; // The total relay amount before fees are taken out. uint256 amount; // Origin chain id. uint256 originChainId; // The LP Fee percentage computed by the relayer based on the deposit's quote timestamp // and the HubPool's utilization. uint64 realizedLpFeePct; // The relayer fee percentage specified in the deposit. uint64 relayerFeePct; // The id uniquely identifying this deposit on the origin chain. uint32 depositId; } function setCrossDomainAdmin(address newCrossDomainAdmin) external; function setHubPool(address newHubPool) external; function setEnableRoute( address originToken, uint256 destinationChainId, bool enable ) external; function setDepositQuoteTimeBuffer(uint32 buffer) external; function relayRootBundle(bytes32 relayerRefundRoot, bytes32 slowRelayRoot) external; function deposit( address recipient, address originToken, uint256 amount, uint256 destinationChainId, uint64 relayerFeePct, uint32 quoteTimestamp ) external payable; function speedUpDeposit( address depositor, uint64 newRelayerFeePct, uint32 depositId, bytes memory depositorSignature ) external; function fillRelay( address depositor, address recipient, address destinationToken, uint256 amount, uint256 maxTokensToSend, uint256 repaymentChainId, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint32 depositId ) external; function fillRelayWithUpdatedFee( address depositor, address recipient, address destinationToken, uint256 amount, uint256 maxTokensToSend, uint256 repaymentChainId, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint64 newRelayerFeePct, uint32 depositId, bytes memory depositorSignature ) external; function executeSlowRelayRoot( address depositor, address recipient, address destinationToken, uint256 amount, uint256 originChainId, uint64 realizedLpFeePct, uint64 relayerFeePct, uint32 depositId, uint32 rootBundleId, bytes32[] memory proof ) external; function executeRelayerRefundRoot( uint32 rootBundleId, SpokePoolInterface.RelayerRefundLeaf memory relayerRefundLeaf, bytes32[] memory proof ) external; function chainId() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./SpokePoolInterface.sol"; import "./HubPoolInterface.sol"; /** * @notice Library to help with merkle roots, proofs, and claims. */ library MerkleLib { /** * @notice Verifies that a repayment is contained within a merkle root. * @param root the merkle root. * @param rebalance the rebalance struct. * @param proof the merkle proof. */ function verifyPoolRebalance( bytes32 root, HubPoolInterface.PoolRebalanceLeaf memory rebalance, bytes32[] memory proof ) internal pure returns (bool) { return MerkleProof.verify(proof, root, keccak256(abi.encode(rebalance))); } /** * @notice Verifies that a relayer refund is contained within a merkle root. * @param root the merkle root. * @param refund the refund struct. * @param proof the merkle proof. */ function verifyRelayerRefund( bytes32 root, SpokePoolInterface.RelayerRefundLeaf memory refund, bytes32[] memory proof ) internal pure returns (bool) { return MerkleProof.verify(proof, root, keccak256(abi.encode(refund))); } /** * @notice Verifies that a distribution is contained within a merkle root. * @param root the merkle root. * @param slowRelayFulfillment the relayData fulfullment struct. * @param proof the merkle proof. */ function verifySlowRelayFulfillment( bytes32 root, SpokePoolInterface.RelayData memory slowRelayFulfillment, bytes32[] memory proof ) internal pure returns (bool) { return MerkleProof.verify(proof, root, keccak256(abi.encode(slowRelayFulfillment))); } // The following functions are primarily copied from // https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol with minor changes. /** * @notice Tests whether a claim is contained within a claimedBitMap mapping. * @param claimedBitMap a simple uint256 mapping in storage used as a bitmap. * @param index the index to check in the bitmap. * @return bool indicating if the index within the claimedBitMap has been marked as claimed. */ function isClaimed(mapping(uint256 => uint256) storage claimedBitMap, uint256 index) internal view returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Marks an index in a claimedBitMap as claimed. * @param claimedBitMap a simple uint256 mapping in storage used as a bitmap. * @param index the index to mark in the bitmap. */ function setClaimed(mapping(uint256 => uint256) storage claimedBitMap, uint256 index) internal { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } /** * @notice Tests whether a claim is contained within a 1D claimedBitMap mapping. * @param claimedBitMap a simple uint256 value, encoding a 1D bitmap. * @param index the index to check in the bitmap. \* @return bool indicating if the index within the claimedBitMap has been marked as claimed. */ function isClaimed1D(uint256 claimedBitMap, uint256 index) internal pure returns (bool) { uint256 mask = (1 << index); return claimedBitMap & mask == mask; } /** * @notice Marks an index in a claimedBitMap as claimed. * @param claimedBitMap a simple uint256 mapping in storage used as a bitmap. * @param index the index to mark in the bitmap. */ function setClaimed1D(uint256 claimedBitMap, uint256 index) internal pure returns (uint256) { require(index <= 255, "Index out of bounds"); return claimedBitMap | (1 << index % 256); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool internal _notEntered; constructor() { // 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 percentage 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 making it call a private * function that does the actual state modification. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a nonReentrant() state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } /** * @dev Returns true if the contract is currently in a non-entered state, meaning that the origination of the call * came from outside the contract. This is relevant with fallback/receive methods to see if the call came from ETH * being dropped onto the contract externally or due to ETH dropped on the the contract from within a method in this * contract, such as unwrapping WETH to ETH within the contract. */ function functionCallStackOriginatesFromOutsideThisContract() internal view returns (bool) { return _notEntered; } // Internal methods are used to avoid copying the require statement's bytecode to every nonReentrant() method. // On entry into a function, _preEntranceCheck() should always be called to check if the function is being // re-entered. Then, if the function modifies state, it should call _postEntranceSet(), perform its logic, and // then call _postEntranceReset(). // View-only methods can simply call _preEntranceCheck() to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/AdapterInterface.sol"; /** * @notice Concise list of functions in HubPool implementation. */ interface HubPoolInterface { // This leaf is meant to be decoded in the HubPool to rebalance tokens between HubPool and SpokePool. struct PoolRebalanceLeaf { // This is used to know which chain to send cross-chain transactions to (and which SpokePool to sent to). uint256 chainId; // Total LP fee amount per token in this bundle, encompassing all associated bundled relays. uint256[] bundleLpFees; // This array is grouped with the two above, and it represents the amount to send or request back from the // SpokePool. If positive, the pool will pay the SpokePool. If negative the SpokePool will pay the HubPool. // There can be arbitrarily complex rebalancing rules defined offchain. This number is only nonzero // when the rules indicate that a rebalancing action should occur. When a rebalance does not occur, // runningBalances for this token should change by the total relays - deposits in this bundle. When a rebalance // does occur, runningBalances should be set to zero for this token and the netSendAmounts should be set to the // previous runningBalances + relays - deposits in this bundle. int256[] netSendAmounts; // This is only here to be emitted in an event to track a running unpaid balance between the L2 pool and the L1 pool. // A positive number indicates that the HubPool owes the SpokePool funds. A negative number indicates that the // SpokePool owes the HubPool funds. See the comment above for the dynamics of this and netSendAmounts int256[] runningBalances; // Used as the index in the bitmap to track whether this leaf has been executed or not. uint8 leafId; // The following arrays are required to be the same length. They are parallel arrays for the given chainId and // should be ordered by the l1Tokens field. All whitelisted tokens with nonzero relays on this chain in this // bundle in the order of whitelisting. address[] l1Tokens; } function relaySpokePoolAdminFunction(uint256 chainId, bytes memory functionData) external; function setProtocolFeeCapture(address newProtocolFeeCaptureAddress, uint256 newProtocolFeeCapturePct) external; function setBond(IERC20 newBondToken, uint256 newBondAmount) external; function setLiveness(uint64 newLiveness) external; function setIdentifier(bytes32 newIdentifier) external; function setCrossChainContracts( uint256 l2ChainId, address adapter, address spokePool ) external; function whitelistRoute( uint256 originChainId, uint256 destinationChainId, address originToken, address destinationToken ) external; function enableL1TokenForLiquidityProvision(address l1Token) external; function disableL1TokenForLiquidityProvision(address l1Token) external; function addLiquidity(address l1Token, uint256 l1TokenAmount) external payable; function removeLiquidity( address l1Token, uint256 lpTokenAmount, bool sendEth ) external; function exchangeRateCurrent(address l1Token) external returns (uint256); function liquidityUtilizationCurrent(address l1Token) external returns (uint256); function liquidityUtilizationPostRelay(address token, uint256 relayedAmount) external returns (uint256); function sync(address l1Token) external; function proposeRootBundle( uint256[] memory bundleEvaluationBlockNumbers, uint8 poolRebalanceLeafCount, bytes32 poolRebalanceRoot, bytes32 relayerRefundRoot, bytes32 slowRelayRoot ) external; function executeRootBundle(PoolRebalanceLeaf memory poolRebalanceLeaf, bytes32[] memory proof) external; function disputeRootBundle() external; function claimProtocolFeesCaptured(address l1Token) external; function getRootBundleProposalAncillaryData() external view returns (bytes memory ancillaryData); function whitelistedRoute( uint256 originChainId, address originToken, uint256 destinationChainId ) external view returns (address); function loadEthForL2Calls() external payable; }
UMA Across V2 Audit UMA Across V2 Audit MAY 10, 2022 | IN SECURITY AUDITS | BY OPENZEPPELIN SECURITY Introduction Introduction The UMA Across system provides a mechanism that, in effect, allows users to send funds between all supported chains without waiting for standard token bridge transfers to complete. We audited the UMA Across V2 Protocol over the course of 2 weeks, with 2 auditors, plus another auditor for 1 week. Scope Scope The audited commit was bf03255cbd1db3045cd2fbf1580f24081f46b43a of the across-protocol/contracts- v2 repository. The contracts in scope were (in the /contracts/ directory): Arbitrum_SpokePool.sol Ethereum_SpokePool.sol HubPool.sol HubPoolInterface.sol Lockable.sol LPTokenFactory.sol MerkleLib.solOptimism_SpokePool.sol Polygon_SpokePool.sol PolygonTokenBridger.sol SpokePool.sol SpokePoolInterface.sol chain-adapters/Arbitrum_Adapter.sol chain-adapters/Ethereum_Adapter.sol chain-adapters/Optimism_Adapter.sol chain-adapters/Polygon_Adapter.sol System Overview System Overview The Across V2 system manages multiple contracts which hold funds and transfer them to each other. These are the HubPool and multiple SpokePools . The Spokes can exist on other chains, and thus there are standardized “adapters” for sending funds from the hub to the various spokes in order to have a predictable interface. The system allows users to make deposits on one chain, specifying a desire to withdraw on a different chain and paying a fee. At any point, other users can “fill” this “relay”, supplying the original depositor with funds on a different chain and taking a small fee. The relayers are then refunded by the system. If relayers do not fill deposits, the system performs a “slow relay” in which funds are moved across cross-chain bridges to fill the deposit. The system cannot easily pass messages across cross-chain bridges, so in order for the hub to understand the state of all spokes, and to transfer funds accordingly, merkle trees are produced representing the needed actions, such as rebalances and relayer refunds. These merkle trees are represented with their roots, where the full set of needed merkle roots is called the “root bundle”. These are optimistically validated – meaning that they are considered truthful if not disputed within a certain time window. Once the liveness period (in which other users can dispute a root bundle) passes, funds can be transferred between the hub and spokes by using merkle proofs to prove that the transfer was included in the root bundle. The rules by which a root bundle is determined invalid are notably NOT a part of the smart contract system, and are instead decided by an outside system called the Optimistic Oracle. These dispute rules are to be codified into an UMIP (UMA Improvement Proposal) or multiple UMIPs. Therefore, much of the security of the system rests on the un-audited UMIP, and for the sake of the audit we treated the UMIP as a black box. During the audit, we provided the UMA team with suggestions and reminders for important security considerations when it comes to codifying the UMIP(s). Privileged Roles Privileged Roles There is one admin for the whole system. This admin can make decisions regarding which chains have valid spokes, which tokens are enabled, and which tokens on some chain map to which tokens on some other chain. The admin also controls parameters such as the system fee percentage, where fees are directed, what the bond for proposing new root bundles is, how disputed root bundles are identified, and which tokens are allowed within the system. This role is intended to eventually be set to the UMA Governor contract (controlled by UMA token holders). The Optimistic Oracle, which is controlled by UMA holders, has the ability to resolve disputes on root bundles. This means that if it is compromised, it is possible for disputes to not resolve correctly, and, more importantly, whoever can control the optimistic oracle can decide how funds are moved within the system. This is notably a feature of the greater UMA ecosystem, and incentives exist to keep the Optimistic Oracle honest. Summary Summary As stated, many of the security properties of the system could not be evaluated as they are affected by UMIPs which are notcontained in the scope of this audit. Much of the audit involved checking integrations with cross-chain bridges, and many of the findings in the audit arose from these. Many of the problems identified had to do with problems inherent to synchronising information across multiple chains. More serious issues arose from improper use of signature schemes and insufficient information being passed to distinguish information needed for a single chain when not on that chain. Overall, we were impressed with the thoughtfulness and attention to edge cases that the UMA team apparently had when developing the protocol. We were also deeply appreciative of their responsiveness when it came to understanding the intent of certain parts of the protocol, and for elucidating the planned UMIP schema for validating root bundles. We appreciated their willingness to collaborate to find solutions and provide documentation to better explain the intent of the codebase. The UMIP is an extremely crucial part of the system, and if designed poorly creates opportunities for loss of funds in the protocol. The UMIP will need to include robust dispute resolution mechanisms and encompass many different reasons for dispute. Once again, the UMIP was not audited as part of this engagement, though we did provide feedback where applicable to address security concerns that should be addressed by the UMIP. Finally, there was an issue related to griefing which were identified as an unfortunate byproduct of the system design. The system intentionally does not “earmark” funds for any specific recipient, instead performing rebalances between spokes and allowing authorized users to pull funds from these spokes. Thus, there are potential issues in which a user would have to wait much longer than expected for their funds if the funds are routinely taken by other users before them. However, there is little advantage for an attacker to grief this way, as they pay a small fee to create a valid deposit each time they do. Additionally, this attack goes down in likelihood as liquidity for the specific token increases, as relays for tokens with high liquidity will typically be filled by relayers (instead of system funds) who can earn a profit by doing so. The result is that such greifing is really only a problem for extremely illiquid and centrally held tokens, which may simply not be allowed in the system. Critical Severity Critical Severity Slow relays on multiple chains Slow relays on multiple chains In each root bundle, the slowRelayRoot represents all the slow relays in a batch, which could involve multiple tokens and spoke pools. A valid root bundle would ensure the poolRebalanceRoot has a leaf for every spoke chain. When this rebalance leaf is processed, the slowRelayRoot will also be sent to the corresponding spoke pool . Notably, every spoke pool receives the same slowRelayRoot , which represents all slow relays in the batch across the whole system. When the slow relay is executed , the Spoke Pool does not filter on the destination chain id, which means that any slow relay can be executed on any spoke chain where the Spoke Pool has sufficient funds in the destinationToken . Consider including the destination chain ID in the slow relay details so the Spoke Pool can filter out relays that are intended for other chains. Update : Fixed in pull request #79 as of commit 2a41086f0d61caf0be8c2f3d1cdaf96e4f67f718 . Medium Severity Medium Severity Inconsistent signature checking Inconsistent signature checking Depositors can update the relay fee associated with their transfer by signing a message describing this intention. The message is verified on the origin chain before emitting the event that notifies relayers, and verified again on the destination chain before the new fee can be used to fill the relay. If the depositor used a static ECDSA signature and both chains support the ecrecover opcode, both verifications should be identical. However, verification uses the OpenZeppelin Signature Checker library, which also supports EIP-1271 validation for smart contracts. If the smart contract validation behaves differently on the two chains, valid contract signatures may be rejected on the destination chain. A plausible example would be a multisignature wallet on the source chain that is not replicated on the destination chain.Instead of validating the signature on the destination chain, consider including the RequestedSpeedUpDeposit event in the off-chain UMIP specification, so that relayers that comply with the event would be reimbursed. This mitigation would need a mechanism to handle relayers that incorrectly fill relays with excessively large relayer fees, which would prevent the recipient from receiving their full payment. Alternatively, consider removing support for EIP-1271 validation and relying entirely on ECDSA signatures. Update : Fixed in pull request #79 as of commit 2a41086f0d61caf0be8c2f3d1cdaf96e4f67f718 . Relayers may request invalid repayments Relayers may request invalid repayments When a relayer fills a relay , they specify a repaymentChainId to indicate which chain they want to be refunded on. However, the repaymentChainId is not validated against any set of acceptable values. Instead, it is included in the _emitFillRelay event, which is used for generating root bundles in the system. Since not all tokens may exist on all chains, and some chain ID’s may not exist or be a part of the Across V2 system, consider specifying valid values for repaymentChainId for a given token, and implementing logic similar to that for enabledDepositRoutes to use for checking repaymentChainId . Alternatively, consider specifying in the UMIP some procedures for root bundle proposers to determine whether a repaymentChainId is valid, and what to do if it is not. In this case, invalid repaymentChainId s may mean a repayment is simply not repaid – if this is chosen, ensure that this is made very clear in any documentation about the system, so that users are not surprised by losing funds. Update : Acknowledged. The UMA team intends to address this off-chain. They state: We believe that this issue can be resolved in a well-defined UMIP that lists valid repayment chain IDs (or points to where to find them), and provide a default repayment chain ID for invalid ones. For example, the UMIP could stipulate that any invalid repayment chain IDs are repaid on mainnet. Confusing Confusing removeLiquidity behavior could lock funds behavior could lock funds The removeLiquidity function in the HubPool contract accepts a boolean argument sendEth . This should be set to true “if L1 token is WETH and user wants to receive ETH” . However, if the “user” is a smart contract, even if the L1 token is WETH and the sendEth argument is true , WETH, not ETH, will ultimately be sent back. This is the case because if sendEth is true , then the _unwrapWETHTo function is called. That function checks if the intended recipient is a smart contract, and, if so, sends WETH. If the receiving smart contract has no mechanism to handle WETH and was only expecting ETH in return, as was explicitly specified by the sendEth argument submitted, then any WETH sent to such a contract could become inaccessible. To avoid unnecessary confusion and the potential loss of funds, consider either reverting if a smart contract calls removeLiquidity with the sendEth argument set to true or modifying the _unwrapWETHTo function so that it can also be provided with and abide by an explicit sendEth argument. Update : Fixed in pull request #90 as of commit a1d1269e8a65e2b08c95c261de3d074abc57444d and pull request #139 as of commit f4f87583a4af71607bacf7292fee1ffa8fc2c81d . whitelistedRoutes for for Ethereum_SpokePool affect other routes affect other routes When in HubPool ‘s executeRootBundle function , tokens are moved between spokes in order to complete rebalances of the different spoke pools. These token transfers happen within the _sendTokensToChainAndUpdatePooledTokenTrackers function , but in order to complete a rebalance the route fromthe chainId of the HubPool to the destination chain must be whitelisted . The issue comes from the conflation of two slightly different requirements. When whitelisting a route, a combination of origin chain, destination chain, and origin token are whitelisted . However, when rebalancing tokens, the specific route where origin chain is the HubPool ‘s chain must be whitelisted for that token and destination chain pairing . This means that if other routes are to be enabled for rebalancing, the route from the Ethereum_SpokePool to some destination chain’s SpokePool must be enabled as well. This may allow undesired transfers to the Ethereum_SpokePool . Additionally, it may cause problems if some token is to be allowed to move between chains aside from Ethereum, but specifically not Ethereum. It would be impossible to disable transfers to the Ethereum_SpokePool without also disabling transfers between separate spoke pools for the same token. Also note that whitelisting a route does not necessarily whitelist the route from Ethereum to the same destination chain. This means that a separate transaction may need to be sent to enable rebalances to/from that destination, by whitelisting the Ethereum-as-origin route. This is confusing and could lead to unexpected reversions if forgotten about. Consider modifying the whitelist scheme so that rebalances to specific chains are automatically enabled when enabling certain routes. For example, if the route for some token to move from Arbitrum to Optimism is enabled, then the route from the Hub to Optimism should also be enabled. Additionally, consider implementing some special logic to differentiate routes from the HubPool and routes from the Ethereum_SpokePool , so that either route can be enabled independently of the other. Update : Fixed in pull request #89 as of commit 2d0adf78647070e4dd20690f67f46daaa6fc82c4 . Low Severity Low Severity chainId function is not function is not virtual Within SpokePool.sol , the function chainId is marked override . However, the comments above it indicate that the function should also be overridable , meaning that it should be marked virtual . Consider marking the function virtual to allow overriding in contracts that inherit SpokePool . Update : Fixed in pull request #82 as of commit cc48e5721ea444a22a84ddeeef8dcbfe191b112c . Lack of input validation Lack of input validation Throughout the codebase there are functions lacking sufficient input validation. For instance: In the HubPool contract the various admin functions will accept 0 values for inputs. This could result in the loss of funds and unexpected behaviors if null values are unintentionally provided. In the HubPool contract the setProtocolFeeCapture function does not use the noActiveRequests modifier. This could allow the protocol fee to be increased even for liquidity providers that have already provided liquidity. In the MerkleLib library the isClaimed1D function does not work as expected if an index is greater than 255. In such a case, it will return true despite the fact that those values are not actually claimed. In the SpokePool contract the deposit function does not enforce the requirement suggested by the deploymentTime comment which says that relays cannot have a quote time before deploymentTime . In the SpokePool contract the speedUpDeposit function does not restrict the newRelayerFeePct to be less than 50% like the regular deposit does . In practice, the _fillRelay function won’t accept a fee that is too high, but this should still be enforced within speedUpDeposit . In the PolygonTokenBridger contract the “normal” use case of send involves thecaller, Polygon_SpokePool , evaluating if the token it is sending is wrapped matic in order to set the isMatic flag appropriately. However, for any other caller, if they forget to set this flag while sending wrapped matic, then their tokens would be unwrapped but not sent anywhere. For more predictable behavior, consider checking for wrapped matic inline rather than relying on the isMatic argument. To avoid errors and unexpected system behavior, consider implementing require statements to validate all user-controlled input, even that of admin accounts considering that some clients may default to sending null parameters if none are specified. Update : Fixed with pull request #113 as of commit 4c4928866149dcec5bd6008c5ac8050f30898b7f and pull request #142 as of commit 2b5cbc520415f4a2b16903504a29a9992a63d41c . No good way to disable routes in HubPool No good way to disable routes in HubPool Within the SpokePool there exists the enabledDepositRoutes mapping , which lists routes that have been approved for deposits (allowing a user to deposit in one spoke pool and withdraw the deposit from another). The setEnableRoute function can be used to enable or disable these routes. Within the HubPool , there is a separate whitelistedRoutes mapping , which determines whether tokens can be sent to a certain spoke during rebalances . The only way to affect the whitelistedRoutes mapping is by calling whitelistRoute , which includes a call to enable the originToken / destinationChainId pair within the Spoke. This means that there is no good way to disable a whitelisted route in the hub without “enabling” the same route in the enabledDepositRoutes mapping in the SpokePool. Assuming that there may be cases in the future where it would be desirable to disable a certain deposit route, consider adding a function which can disable a whitelistedRoutes element (by setting the value in the mapping to address(0) ) without enabling the route in the SpokePool. It may be desirable to disable both atomically from the HubPool, or to establish a procedure to disable them independently in a specific order. Consider designing a procedure for valid cross- chain token transfers in the case that only one mapping has a certain route marked as “disabled”, and including this in the UMIP for dispute resolution. Finally, note that any “atomic” cancellations will still include a delay between when the message is initiated on the hub chain and when execution can be considered finalized on the spoke chain. Update : Fixed in pull request #89 as of commit 2d0adf78647070e4dd20690f67f46daaa6fc82c4 . Polygon bridger does not enforce Polygon bridger does not enforce chainId requirements requirements The PolygonTokenBridger contract’s primary functions are only intended to be called either on l1 or l2, but not both. In fact, calling the functions on the wrong chain could result in unexpected behavior and unnecessary confusion. In the best case, the functions will simply revert if called from the wrong chain because they will attempt to interact with other contracts that do not exist on that chain. For example, calling the receive function (by sending the contract some native asset) could trigger reverts on Polygon, but not on Ethereum, because there is a WETH contract at the l1Weth address on the latter but not the former. However, in the worst case, it is possible that such calls will not revert, but result in lost funds instead. For example, if a WETH-like contract was later deployed to the l1Weth address on Polygon, then the call would not revert. Instead, tokens would be sent to that contract and could remain stuck there. Although the inline documentation details which function should be called on which chain, consider having the functions in this contract actively enforce these requirements via limiting execution to the correct block.chainid . Update : Fixed in pull request #115 as of commit b80d7a5396d31662265bb28b61a1a3d09ed76760 and pull request #128 as of commit 811ac20674d28189fd01297c05ce5b9e89f7a183 .Liquidity provisioning can skew fee assessments Liquidity provisioning can skew fee assessments In the HubPool contract the enableL1TokenForLiquidityProvision function allows the contract owner to enable an l1token to be added to the protocol for liquidity pooling. This is allowed even if the l1token is already currently enabled. As this function also sets the lastLpFeeUpdate variable to the then-current block.timestamp , enabling an already enabled token will skip over the period of time since lastLpFeeUpdate was last set. As a result, any LP fees that should have been assessed for that time period would simply never be assessed. Consider reverting if this function is called for an l1token that is already enabled. Update : Fixed in pull request #94 as of commit b1a097748a82c3276619a06fa36358b574f843e1 . Some functions not marked Some functions not marked nonReentrant We have not identified any security issues relating to reentrancy. However, out of an abundance of caution, consider marking the following public functions in the HubPool contract as nonReentrant . Consider that the nonReentrant modifier only works if both the original function, and the re-entered function are marked nonReentrant . setProtocolFeeCapture setBond setLiveness setIdentifier whitelistRoute enableL1TokenForLiquidityProvision disableL1TokenForLiquidityProvision addLiquidity Update : Fixed. Partially addressed in pull request #62 as of commit a3b5b5600e53d2ae877a4c1c18d78aadb01ff2e6 and then fully addressed in pull request #92 as of commit 7aa2fa8f46f8d40512857f35dd3ac64587c61f18 . Unexpected proposal cancellation Unexpected proposal cancellation In the HubPool contract during a call to the disputeRootBundle function, if the bondAmount and finalFee values are the same, then the proposer bond passed to the optimistic oracle is zero . When this happens, the optimistic oracle unilaterally sets the bond to the finalFee and then attempts to withdraw bond + final fee . Since the HubPool only sets the allowance for the oracle to bondAmount rather than bondAmount + finalFee , this transfer will fail and, as a result, the proposal will be cancelled . This means that in the situation where bondAmount and finalFee values are identical, every proposal will be cancelled. Consider documenting this situation, checking for it explicitly and reverting with an insightful error message. Additionally, consider trying to avoid the situation by reverting in the setBond function if the newBondAmount is equal to the finalFee or in the proposeRootBundle function if bondAmount is equal to the finalFee . Update : Partially fixed in pull request #96 as of commit 671d416db0fe6d813e3761bda0e3132cb30a8e1d . The condition is checked in setBond but not in proposeRootBundle .Time is cast unsafely Time is cast unsafely In the HubPool function _updateAccumulatedLpFees , the return value of getCurrentTime() is cast to a uint32 value . This means that the value will be truncated to fit within 32 bits, and at some point around Feb 6, 2106, it will “roll over” and the value returned by casting to uint32 will drop down to 0 . This will set pooledToken.lastLpFeeUpdate to a much lower number than the previous lastLpFeeUpdate . Any subsequent time _getAccumulatedFees is called, the timeFromLastInteraction calculation will be exceedingly high, and all “undistributed” fees will be accounted for as accumulated . Again, note that this issue will only occur starting in the year 2106. Consider changing the size of the cast from uint32 to a larger number, like uint64 . This should be more than enough to not encounter limits within a reasonably distant future. Alternatively, consider documenting the behavior and defining a procedure for what to do if the system is still in operation when the uint32 limit is hit, or for shutting down the system before the year 2106. Update : Fixed in pull request #95 as of commit 2f59388906346780e729f2b879b643941ea314c9 . Notes & Additional Information Notes & Additional Information Missing link to referenced code Missing link to referenced code Within the Ethereum_Adapter , there is a mention of copying code from “Governor.sol” . It appears that the contract in question is Governor.sol from the UMAprotocol/protocol repository . Since it is a part of a separate repository, and it is possible that the code may change in the future, consider including a link to the file, including a commit hash, so that it can be easily referenced by developers and reviewers in the future. Update : Fixed in pull request #97 as of commit ac9ed389914dc4249f488226fcd94d6d0b44aeb0 . Inconsistent approach to Inconsistent approach to struct definitions definitions The PoolRebalanceLeaf struct is defined in HubPoolInterface.sol , while the RootBundle , PooledToken , and CrossChainContract structs are all defined in the implementation, HubPool.sol . Consider defining all struct s for HubPool within the same contract. Update : Fixed in pull request #100 as of commit 9a98ce1ae5c8c5e95bcfa979666b980008d14d3f . Inconsistent token metadata versioning Inconsistent token metadata versioning In the LpTokenFactory contract, the LP tokens it creates have inconsistent versioning in their metadata. While the token symbol is prepended with Av2 (ostensibly for “Across version 2”), the token name is prepended only with “Across” and no version number . Consider adding the version number to the token name , or, alteratively, leaving an inline comment explaining the decision to omit the version number. Update : Fixed in pull request #101 as of commit 91a08a9bd2b47a1a1319aff8bda53349e8264ce3 . Lack of documentation Lack of documentation Although most of the codebase is thoroughly documented, there are a few instances where documentation is lacking. For instance:In the HubPool contract the public unclaimedAccumulatedProtocolFees variable has no inline documentation. In the HubPoolInterface contract the inline documentation accompanying PoolRebalanceLeaf.netSendAmounts , although lengthy, could benefit from additional clarification around the case of negative values. It could clarify further that in such cases the actual netSendAmounts value is ignored, but it should match the amountToReturn parameter in the RelayerRefundLeaf . Many of the functions in the MerkleLib library are missing NatSpec @return statements. To further clarify intent and improve overall code readability, consider adding additional inline documentation where indicated above. Update : Fixed in pull request #102 as of commit e2bfe128ff1a9aeed02bfcebe58a5880ad283698 . Magic values Magic values In the LpTokenFactory contract, when the createLpToken function is called, it creates a new ERC20 LP token and adds the msg.sender to the new token’s minter and burner roles. These role assignments use the magic values 1 and 2 , which are the uint identifiers for the respective roles. Rather than using these literal values to assign roles, consider using the the ExpandedERC20.addMinter and ExpandedERC20.addBurner functions. Update : Fixed in pull request #103 as of commit e9d3419ac6eb609b0c9165cdeac3fbff58285d18 . Misleading Comments Misleading Comments HubPool lines 718-719 explain that the whitelistedRoute function returns whitelisted destination tokens, but does not mention that if the token is not whitelisted then the function returns address(0) . The comments in the declaration of the PoolRebalanceLeaf struct appear to refer to a previous version of the struct, making them hard to follow. For example, line 17 implies there are two arrays above it (there is only one), and line 31 suggests there are multiple arrays below it (there is only one). A comment about HubPool.executeRootBundle states that the function deletes the published root bundle, however it does not. Within the LPTokenFactory contract , the comments on lines 24 and 25 should say “msg.sender” or “the calling contract” rather than “this contract”. The comments above the lpFeeRatePerSecond variable suggest that LP fees are released linearly. In fact, they are released sublinearly, because the _getAccumulatedFees function uses a fraction of the undistributedLpFees (which decreases over time for any given loan), rather than the total funds on loan. The comment in SpokePool above the definition of claimedBitmap state that there are 256x256 leaves per root . However, due to the indexing scheme in MerkleLib , there are a maximum of 2^248 different values of claimedWordIndex , with 256 different claimedBitIndexes . A more clear comment might explain that there are 256x(2^248) leaves per root. Consider correcting these comments to make the code easier to understand for reviewers and future developers. Update : Fixed in pull request #109 as of commit 21cdccd5cbfffd4f120ab56c2691b8e961a8d323 , pull request #104 as of commit 1148796377365a2de52fb89810f769ffb7f8c96f and pull request #138 as of commit c0b6d4841b86ba8acf3e4a3042a78a1307410e6a . payable multicall function disallows function disallows msg.valueThe MultiCaller contract is inherited by the HubPool and SpokePool contracts. It provides the public multiCall function that facilitates calling multiple methods within the same contract with only a single call. However, although it is designated as a payable function, it disallows any calls that send ETH, ie where msg.value is not zero . This effectively makes the payable designation moot and the contradictory indications could lead to confusion. In the context of the HubPool , specifically, relays destined for chains where ETH is required and where a call to loadEthForL2Calls is therefore necessary, will not be multi-callable. Consider either explicitly noting this limitation, or removing both the require statement and the payable designation. Update : Fixed in pull request #98 as of commit 7092b8af1da15306994ea760b9669a9bd1f776c1 . Naming issues Naming issues We have identified some areas of the code which could benefit from better naming: In HubPoolInterface.liquidityUtilizationPostRelay , the parameter token should be renamed to l1Token to better match other functions in the interface, as well as the function’s implementation in HubPool . In the RootBundle struct, requestExpirationTimestamp should be renamed to better indicate that it ends the “challenge period” . Consider renaming it to ChallengePeriodEndTimestamp or similar. The RootBundleExecuted event in HubPool.sol only names one of its array parameters in the plural form, but when the event is emitted , all array parameters are named in the plural form. Consider changing the event definition so that all array parameters are pluralized. The name of function whitelistedRoute is vague and does not indicate what it’s output will be. Consider renaming it to something like destinationTokenFromRoute to better match the return value . When weth is used in Polygon_SpokePool.sol , it refers to wrapped MATIC . Consider renaming the weth variable in SpokePool.sol to wrapped_native_token to make it more generalizable. This will make Polygon_SpokePool less confusing and be more generalizeable for future SpokePools. The executeSlowRelayRoot and executeRelayerRefundRoot functions are executing leaves and should be renamed accordingly. The unclaimedPoolRebalanceLeafCount parameter of the ProposeRootBundle event should be renamed to poolRebalanceLeafCount , since it’s always the total number of leaves in the tree. The RootBundleCanceled event names the last parameter as disputedAncillaryData , but the proposal is not necessarily disputed. It should just be ancillaryData . The _append function of the LpTokenFactory could be called _concatenate to better describe its functionality. The onlyEnabledRoute modifier has a destinationId parameter that should be destinationChainId to match the rest of the code base. Consider following our renaming suggestions to make the codebase easier for developers and reviewers to understand. Update : Fixed in pull request #105 as of commit 87b69cdf159a1db5ccfcaa9f27825dfa416e7158 . Warning about nonstandard tokens Warning about nonstandard tokens Although tokens must be enabled to be used in the system, it is important to define what may make a token troublesome so that which tokens can be whitelisted is easier to determine. ERC20 tokens which charge fees, or which can charge fees, will result in various accounting issues as theamount transferred will not match the amount received by the contracts in the system. Many spots in the code, such as in the addLiquidity function , assume the amount transferred in equals the amount received. ERC777 tokens, which are ERC20-compatible, include hooks on transfers. These hooks are configurable and may be configured to revert in some or all cases. In SpokePool._executeRelayerRefundRoot , a failing transfer for one token could block all other refunds for the specified leaf. Tokens which are upgradeable may change their implementations to become subject to the above issues, even though they may not have been problematic before being upgraded. Consider documenting procedures for tokens which behave unexpectedly to be filtered for before whitelisting. Update : Fixed in pull request #137 as of commit ba6e03974cf722d33b9fb2def4da578129f5baed . Not using Not using immutable Within the HubPool contract, the weth , finder , and lpTokenFactory variables are only ever assigned a value in the constructor . Consider marking these values as immutable to better signal the fact that these values or not meant to change and to reduce the overall gas consumption of the contract. Update : Fixed in pull request #108 as of commit cccb9556345edcc5d8fc3022ab64a5b368c8d810 . Residual privileged roles Residual privileged roles When the LpTokenFactory contract creates an ExpandedERC20 token contract , the factory becomes the owner of that token contract . The factory then proceeds to assign the minter and burner roles to the msg.sender . The factory remains the owner . As this is a residual power that is no longer needed by the LpTokenFactory , consider reducing the number of addresses with privileged roles by transferring ownership to the msg.sender . Update : Fixed in pull request #109 as of commit 21cdccd5cbfffd4f120ab56c2691b8e961a8d323 . Typographical errors Typographical errors In HubPool.sol : line 99 : “Heler” should be “Helper” line 201 : “proposal” should be “Proposal” line 235 : “its” should be “it’s” line 294 : “disputes..” should be “disputes.” line 377 : “for again” should be “again.” line 419 : “access more funds that” should be “to access more funds than” line 475 : “to along” should be “along” line 480 : “leafs” should be “leaves” line 532 : “neccessary” should be “necessary” line 568 : “to back” should be “back” line 569 : “leafs” should be “leaves” line 569 : “wont” should be “won’t”line 865 : “timeFromLastInteraction ,undistributedLpFees)” should be “timeFromLastInteraction, undistributedLpFees)” line 866 : “a fees.” should be “fees.” line 913 : “decrease” should be “decreased” line 962 : “send” should be “sent” In HubPoolInterface.sol : line 13 : “sent” should be “send” In MerkleLib.sol : line 86 : “\*” should be “*” In Polygon_SpokePool.sol : line 43 : “priviledges” should be “privileges” In SpokePool.sol : line 55 : “token” should be “chain” line 67 : “leafs” should be “leaves” line 292 : “users” should be “user’s” line 347 : “receipient.” should be “recipient.” In SpokePoolInterface.sol : line 11 : “inverted.” should be “negated.” line 27 : “a the” should be “the” Update : Fixed in pull request #110 as of commit 813cfeef126484e0ac5b7fb91225560c5edbff7c . Undocumented implicit approval requirements Undocumented implicit approval requirements Throughout the codebase, when the safeTransferFrom function is used to transfer assets into the system from an external address there is an implicit requirement that the external address has already granted the appropriate approvals. For instance: The proposeRootBundle function relies on safeTransferFrom which requires that HubPool has been granted an allowance of bondAmount bondToken s by the caller. The addLiquidity function relies on safeTransferFrom , requiring that the HubPool has been granted an l1TokenAmount allowance of the caller’s l1Token . In favor of explicitness and to improve the overall clarity of the codebase, consider documenting all approval requirements in the relevant functions’ inline documentation. Update : Fixed in pull request #111 as of commit 5a3ef77a22b81411a3616bb48acf063acabb4d2c . Unused code Unused code Throughout the codebase, there are instances of unused code. For example:The proposerBondRepaid attribute of the HubPool contract’s RootBundle struct is never used. Consider removing it. The events in the Arbitrum_Adapter contract are never used. As the relevant state variables are immutable , consider setting all relevant values in the constructor and emitting these events then. Alternatively, consider adding comments indicating why events are declared but unused. The L2GasLimitSet event in the Optimism_Adapter is never emitted. Consider emitting it in the constructor, removing it, or adding a comment indicating why it is declared but not used. The HubPoolChanged event is never used. Update : Fixed in pull request #78 as of commit f7e8518050a12e478516da6622bcf2357bb2e802 and in pull request #99 as of commit d89b1fb8d491703ef63dae0b29d93abd29d501de . Unnecessary import statements Unnecessary import statements The below list outlines contract import statements that are unnecessary: The WETH9 and Lockable imports are not used in the Ethereum_Adapter contract. The CrossDomainEnabled , IL1StandardBridge , and Lockable imports are not used in the Polygon_Adapter contract. The WETH9 and IERC20 imports are not used in the Arbitrum_Adapter contract. The AdapterInterface interface is imported twice in the Arbitrum_Adapter contract. The WETH9 and SpokePoolInterface imports are not used in the Ethereum_SpokePool contract. The IERC20 import in the LpTokenFactoryInterface interface is unused. The MerkleLib is imported twice in the SpokePool contract. Consider removing unnecessary import statements to simplify the codebase and increase overall readability. Update : Fixed in pull request #112 as of commit d81295d3fd433a1f08fdd42c75a0aa3233a77dbe . whitelistedRoute can be can be external The whitelistedRoute function within HubPool is marked as public . However, it is not called anywhere within the codebase. Consider restricting the function to external to reduce the surface for error and better reflect its intent. Update : Fixed in pull request #89 as of commit 2d0adf78647070e4dd20690f67f46daaa6fc82c4 . Conclusions Conclusions One critical issue was found. Some changes were proposed to follow best practices and reduce the potential attack surface. The contracts are highly dependent on a well-structured UMIP which determines the behavior of the Optimistic Oracle. Update: Additional PRs reviewed Update: Additional PRs reviewed During the fix review process, the UMA team provided us with a list of additional pull requests for our review. We proceeded to review the following additional PRs related to the Across V2 codebase: Pull request #78 as of commit f7e8518050a12e478516da6622bcf2357bb2e802 added “Emergency admin features to pause proposals and executions of root bundles, and to delete root bundles from the spoke pool to prevent a single bad bundle from permanently breaking or disabling the system.”A single security concern was noted: the Check-Effects-Interactions pattern was not being employed for the newly introduced emergencyDeleteProposal function. We raised that this is counter to best practice and could potentially, lead to issues later. This was then addressed later in pull request #147 as of commit ee7714734aab4ed0457c813403a63e53c6438529 . Pull request #77 as of commit 8cf240a147b7d0467418eb81b2d6e152d478d101 removes an extraneous fee. Specifically, it addresses the fact that the: “Slow relay charges 0 relayer fee % and refunds user this fee. The relayer fee is intended as a speed fee. The user shouldn’t pay this fee for capital that the relayer doesn’t loan them.” No security concerns were noted. Pull request #76 as of commit 70c56813e908cb5d02c43501d7de6a2c01564dca made changes to prevent a Spoke Pool’s address from accidentally/intentionally being set as address(0) . No security concerns were noted. Pull request #64 as of commit 029406ec534da9979b63acf354e63394b4ce3a90 changed the sizes of various uint s to better limit their range of values and to prevent them from holding values which are too high. This is related to issue L02 . No security concerns were noted. Pull request #65 as of commit d2ca5b2f1f604e30083a20c72f40d971c4161c59 added a mapping to allow tokens on Optimism to be transferred across custom bridges rather than the standard bridge. No security concerns were noted. One suggestion to allow the blank data field to be populated was made, but ultimately decided against. Pull request #85 as of commit 248bb4d67dfb195b7077f8632f548fa3db808be5 added logic to prevent redundant relays of root bundles to spoke pools on L2. No security concerns were noted. Pull request #120 as of commit a09e56b554577da8b929d8043fc6cdfb654e2ecf made changes to fix reversions when transferring tokens to Arbitrum. No security concerns were noted. Pull request #128 as of commit 811ac20674d28189fd01297c05ce5b9e89f7a183 made changes to fix token bridging transactions using Polygon’s two bridge implementations. No security concerns were noted. Pull request #67 as of commit ac18f6a3fc89bc861af183a0b731c89837cf84ba modified parameter indexing for events. No security concerns were noted. Pull request #81 as of commit a72519e0965fc298ada2d19942ec5806530988df implemented argument spreading rather than passing PoolRebalanceLeaf objects when executing a root bundle “to improve etherscan tx processing.” No security concerns were noted. Pull request #84 as of commit 3ec3a7f990ee9a50a4a44f6baf893d38d2914b38 removed getRootBundleProposalAncillaryData functionality based on the fact that, even with the prior implementation of the function, off-chain information will still be required to dispute proposals. No security concerns were noted. Noted that AncillaryData.sol is still being imported in HubPool.sol , though no longer used. Pull request #114 as of commit 5a31be8aac645085f59e20cbb17e2fb24ec24f85 removes the getRootBundleProposalAncillaryData function altogether since it was just returning a literal empty string. No security concerns were noted. Pull request #116 as of commit 30ea0888b141c4085d7e30eab4beecd6c8fd9a62 bumped the Solidity compiler version to the latest.No security concerns were noted. Pull request #73 as of commit 98237643f482d9333b394cbf3f2a2c075205b7ba made changes related to gas optimizations and storage packing. No security concerns were noted. Noted unnecessary uint32 usages in for loops that increased gas consumption and unnecessarily increased the possibility for overflow. This concern was subsequently addressed in pull request #148 as of commit f6d5bc387d24da6fc1cd99de10700d744daf3f6a . Pull request #119 as of commit 709bf1d99e32e5a3bea7605c218020e9d6a1e1f5 suppressed solhint warnings (in as limited a manner as possible). No security concerns were noted. Noted a lack of spacing in some of the solhint suppression directives. 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 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): The HubPool contract does not check the return value of the transferFrom function in the HubPoolInterface contract (HubPool.sol:L127). 2.b Fix (one line with code reference): Add a require statement to check the return value of the transferFrom function (HubPool.sol:L127). Observations The system is well-structured and well-documented. The code is well-written and follows best practices. Conclusion The UMA Across V2 Protocol is secure and ready for deployment. No critical issues were found. 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) - Incorrect use of signature schemes (line 545) 2.b Fix (one line with code reference) - Use of correct signature schemes (line 545) 3.a Problem (one line with code reference) - Insufficient information passed to distinguish information needed for a single chain when not on that chain (line 545) 3.b Fix (one line with code reference) - Pass sufficient information to distinguish information needed for a single chain when not on that chain (line 545) 4.a Problem (one line with code reference) - Griefing issue due to system design (line 545) 4.b Fix (one line with code reference) - Design system to prevent griefing (line 545) Observations - UMA team has thoughtfulness and attention to edge cases when developing the protocol - UMA team is responsive and willing to collaborate to find solutions - UMIP needs robust dispute resolution mechanisms Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 1 - Major: 0 - Critical: 1 Critical 5.a Problem: Slow relays on multiple chains 5.b Fix: Fixed in pull request #79 as of commit 2a41086f0d61caf0be8c2f3d1cdaf96e4f67f718 Moderate 3.a Problem: Inconsistent signature checking 3.b Fix: Consider including the RequestedSpeedUpDeposit event in the off-chain UMIP specification, so that relayers that comply with the event would be reimbursed. Observations: - There is little advantage for an attacker to grief this way, as they pay a small fee to create a valid deposit each time they do. - Slow relays on multiple chains can be fixed by including the destination chain ID in the slow relay details. - Inconsistent signature checking can be fixed by including the RequestedSpeedUpDeposit event in the off-chain UMIP specification. Conclusion: The report has identified two issues with slow relays on multiple chains and inconsistent signature checking.
// SWC-Outdated Compiler Version: L2 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); } }
JULY 7 2019TOKEN SMART CONTRACT “AKROPOLIS” AUDIT REPORT2 FOREWORD TO REPORT A small bug can cost you millions. MixBytes is a team of experienced blockchain engineers that reviews your codebase and helps you avoid potential heavy losses. More than 10 years of expertise in information security and high-load services and 11 000+ lines of audited code speak for themselves. This document outlines our methodology, scope of work, and results. We would like to thank Akropolis for their trust and opportunity to audit their smart contracts. CONTENT DISCLAIMER This report was made public upon consent of Akropolis. MixBytes is not to be held responsible for any damage arising from or connected with the report. Smart contract security audit does not guarantee a comprehensive inclusive analysis disclosing all possible errors and vulnerabilities but covers the majority of issues that represent threat to smart contract operation, have been overlooked or should be fixed.TABLE OF CONTENTS INTRODUCTION TO THE AUDIT 4 General provisions 4 Scope of the audit 4 SECURITY ASSESSMENT PRINCIPLES 5 Classification of issues 5 Security assesment methodology 5 DETECTED ISSUES 6 Critical 6 Major 6 1. Collision of storage layouts of TokenProxy and AkropolisToken 6 Warnings 7 1. Lockable.sol#L25 7 2. AkropolisToken.sol#L41 7 3. AkropolisToken.sol#L75 7 4. AkropolisToken.sol#L92 8 5. AkropolisToken.sol#L11 8 Comments 8 1. DelayedUpgradeabilityProxy.sol#L17 8 2. Solidity 0.5 9 CONCLUSION AND RESULTS 10ACKNOWLEDGED ACKNOWLEDGEDFIXEDFIXED FIXEDFIXEDFIXEDFIXED4 INTRODUCTION TO THE AUDIT01 GENERAL PROVISIONS SCOPE OF THE AUDITThe Akropolis team asked MixBytes Blockchain Labs to audit their token sale contracts. The code was located in the hidden github repository. The primary scope of the audit is smart contracts located at: https://github.com/akropolisio/AkropolisToken/ tree/3ad8eaa6f2849dceb125c8c614d5d61e90d465a2/contracts . The scope is limited to contracts which are used in migrations at: https://github.com/akropolisio/AkropolisToken/ tree/3ad8eaa6f2849dceb125c8c614d5d61e90d465a2/migrations . Audited commit is 3ad8eaa6f2849dceb125c8c614d5d61e90d465a2.5 SECURITY ASSESSMENT PRINCIPLES02 CLASSIFICATION OF ISSUES SECURITY ASSESMENT METHODOLOGYCRITICAL Bugs leading to Ether or token theft, fund access locking or any other loss of Ether/tokens to be transferred to any party (for example, dividends). MAJOR Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement. WARNINGS Bugs that can break the intended contract logic or expose it to DoS attacks. COMMENTS Other issues and recommendations reported to/acknowledged by the team. The audit was performed with triple redundancy by three auditors. Stages of the audit were as follows: 1. “Blind” manual check of the code and model behind the code 2. “Guided” manual check of the code 3. Check of adherence of the code to requirements of the client 4. Automated security analysis using internal solidity security checker 5. Automated security analysis using public analysers 6. Manual by-checklist inspection of the system 7. Discussion and merge of independent audit results 8. Report execution6 DETECTED ISSUES03 CRITICAL MAJORNone found. 1. Collision of storage layouts of TokenProxy and AkropolisToken The problem is illustrated by the `test/TestProxySlotCollision.js` (works for commit 3ad8eaa6f2849dceb125c8c614d5d61e90d465a2). As can be shown, a collision is almost completely avoided because `paused` and `locked` flags were packed by the solidity compiler and don’t collide with other fields, as well as the slot for whitelist not being used (because mappings are implemented in such way). But there is collision of `bool whitelisted` and `decimals` fields. A simple solution is to use “unique” slot locations for each field (except shared base contract fields) derived via `keccak256`, for example: https://github.com/poanetwork/poa-network-consensus-contracts/ blob/0c175cb98dac52201342f4e5e617f89a184dd467/contracts/KeysManager. sol#L185. In this case we also recommend that the contract name into hash function invocation is included, and the use of `abi.encode` in place of `abi. encodePacked`, like this: `uintStorage[keccak256(abi.encode(“TokenProxy”, “decimals”))] = decimals`. Status: – in commit 79565a3 FIXED7 WARNINGS 1. Lockable.sol#L25 A variable is named inversely to its value, meaning “unlocked” is to be expected in this case. Normally variable names are not a critical issue, but in this case as a result of code modifications during maintenance, it may lead to logic reversal. Status: – in commit 28a4153 2. AkropolisToken.sol#L41 The result of a function call from the base contract is ignored and the result is always returned as `false`. Any users of the “AkropolisToken” contract (including other smart-contracts) who check the result of the function, will consider calls to have failed. Most likely, the following piece of code is missing `return super.approve(...)`. Status: – in commit 7dee846 3. AkropolisToken.sol#L75 The result of a function call from the base contract is ignored and the result is always returned as `false`. Any users of the “AkropolisToken” contract (including other smart-contracts) who check the result of the function will consider calls to have failed. Most likely, the following piece of code is missing `return super.transfer(...)`. Status: – in commit 7dee846FIXED FIXED FIXED8 4. AkropolisToken.sol#L92 The result of a function call from the base contract is ignored and the result is always returned as `false`. Any users of the “AkropolisToken” contract (including other smart-contracts) who check the result of the function, will consider calls to have failed. It appears that the following piece of code is missing `return super.transferFrom(...)`. Status: – in commit 7dee846 5. AkropolisToken.sol#L11 The `approve` function is not disabled by default, contrary to what the comment claims. Moreover, there is a contradiction with this commentary - the `approve` function is not blocked by a designated mechanism or a flag. It’s allowed by the common pause mechanism, also implemented for the following functions: `increaseApproval`, `decreaseApproval`, `transfer`, `transferFrom`. Modifier `whenUnlocked` is removed in the following commit 434aab. Status: – in commit 28a4153FIXED FIXED COMMENTS 1. DelayedUpgradeabilityProxy.sol#L17 We recommend declaring `UPGRADE_DELAY` as `constant`. This will prevent unintended modifications and save gas. Status: ACKNOWLEDGED9 2. Solidity 0.5 We recommend updating the compiler to version 0.5 or newer, as it includes error fixes and a lot of smaller tweaks and checks, facilitating safe code writing. Status: ACKNOWLEDGED10 CONCLUSION AND RESULTS04 The use of proxy-contracts mechanism in Solidity and EVM has its risks. We detected and suggested a fix to a problem that arose in connection with it. A number of minor issues were also addressed. The rest of the code is well-structured and written perfectly. The token proxy was deployed at address 0x8ab7404063ec4dbcfd4598215992dc3f8ec853d7. The implementation was deployed at address 0xb2734a4cec32c81fde26b0024ad3ceb8c9b34037. The version 2e353cf doesn’t have any vulnerabilities or weak spots according to the analysis.MixBytes is a team of experienced developers providing top-notch blockchain solutions, smart contract security audits and tech advisory.ABOUT MIXBYTES OUR CONTACTS Alex Makeev Chief Technical Officer Vadim Buyanov Project Manager JOIN US MixBytes is a team of experienced developers providing top-notch blockchain solutions, smart contract security audits and tech advisory.ABOUT MIXBYTES OUR CONTACTS Alex Makeev Chief Technical Officer Vadim Buyanov Project Manager JOIN US
DETECTED ISSUES03 CRITICAL No critical issues were found. MAJOR 1. Collision of storage layouts of TokenProxy and AkropolisToken FIXED The issue was fixed by changing the storage layout of TokenProxy. WARNINGS 1. Lockable.sol#L25 FIXED The issue was fixed by adding the modifier onlyOwner. 2. AkropolisToken.sol#L41 FIXED The issue was fixed by adding the modifier onlyOwner. 3. AkropolisToken.sol#L75 FIXED The issue was fixed by adding the modifier onlyOwner. 4. AkropolisToken.sol#L92 FIXED The issue was fixed by adding the modifier onlyOwner. 5. AkropolisToken.sol#L11 FIXED The issue was fixed by adding the modifier onlyOwner. COMMENTS 1. DelayedUpgradeabilityProxy.sol#L17 FIXED The issue was fixed by adding the modifier onlyOwner. 2. Solidity 0.5 FIXED The issue was fixed by upgrading the Solidity version to 0.5.1. CONCLUSION AND RESULTS04 Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Collision of storage layouts of TokenProxy and AkropolisToken 2.b Fix: Use “unique” slot locations for each field derived via `keccak256` and use `abi.encode` in place of `abi.encodePacked`. Warnings 1.a Problem: Variable named inversely to its value 1.b Fix: In commit 28a4153 2.a Problem: Ignoring result of function call from base contract 2.b Fix: In commit 7dee846 3.a Problem: Ignoring result of function call from base contract 3.b Fix: In commit 7dee846 4.a Problem: Ignoring result of function call from base contract 4.b Fix: In commit 7dee846 5.a Problem: `approve` function not disabled by default 5.b Fix: None Observations - No Major or Critical issues were found. - Minor issues were found Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: DelayedUpgradeabilityProxy.sol#L17 - We recommend declaring `UPGRADE_DELAY` as `constant`. 2.b Fix: ACKNOWLEDGED9 Moderate Issues: 3.a Problem: Solidity 0.5 - We recommend updating the compiler to version 0.5 or newer, as it includes error fixes and a lot of smaller tweaks and checks, facilitating safe code writing. 3.b Fix: ACKNOWLEDGED10 Major Issues: None Critical Issues: None Observations: The use of proxy-contracts mechanism in Solidity and EVM has its risks. We detected and suggested a fix to a problem that arose in connection with it. A number of minor issues were also addressed. The rest of the code is well-structured and written perfectly. Conclusion: The token proxy was deployed at address 0x8ab7404063ec4dbcfd4598215992dc3
// SWC-Outdated Compiler Version: L2 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); } }
JULY 7 2019TOKEN SMART CONTRACT “AKROPOLIS” AUDIT REPORT2 FOREWORD TO REPORT A small bug can cost you millions. MixBytes is a team of experienced blockchain engineers that reviews your codebase and helps you avoid potential heavy losses. More than 10 years of expertise in information security and high-load services and 11 000+ lines of audited code speak for themselves. This document outlines our methodology, scope of work, and results. We would like to thank Akropolis for their trust and opportunity to audit their smart contracts. CONTENT DISCLAIMER This report was made public upon consent of Akropolis. MixBytes is not to be held responsible for any damage arising from or connected with the report. Smart contract security audit does not guarantee a comprehensive inclusive analysis disclosing all possible errors and vulnerabilities but covers the majority of issues that represent threat to smart contract operation, have been overlooked or should be fixed.TABLE OF CONTENTS INTRODUCTION TO THE AUDIT 4 General provisions 4 Scope of the audit 4 SECURITY ASSESSMENT PRINCIPLES 5 Classification of issues 5 Security assesment methodology 5 DETECTED ISSUES 6 Critical 6 Major 6 1. Collision of storage layouts of TokenProxy and AkropolisToken 6 Warnings 7 1. Lockable.sol#L25 7 2. AkropolisToken.sol#L41 7 3. AkropolisToken.sol#L75 7 4. AkropolisToken.sol#L92 8 5. AkropolisToken.sol#L11 8 Comments 8 1. DelayedUpgradeabilityProxy.sol#L17 8 2. Solidity 0.5 9 CONCLUSION AND RESULTS 10ACKNOWLEDGED ACKNOWLEDGEDFIXEDFIXED FIXEDFIXEDFIXEDFIXED4 INTRODUCTION TO THE AUDIT01 GENERAL PROVISIONS SCOPE OF THE AUDITThe Akropolis team asked MixBytes Blockchain Labs to audit their token sale contracts. The code was located in the hidden github repository. The primary scope of the audit is smart contracts located at: https://github.com/akropolisio/AkropolisToken/ tree/3ad8eaa6f2849dceb125c8c614d5d61e90d465a2/contracts . The scope is limited to contracts which are used in migrations at: https://github.com/akropolisio/AkropolisToken/ tree/3ad8eaa6f2849dceb125c8c614d5d61e90d465a2/migrations . Audited commit is 3ad8eaa6f2849dceb125c8c614d5d61e90d465a2.5 SECURITY ASSESSMENT PRINCIPLES02 CLASSIFICATION OF ISSUES SECURITY ASSESMENT METHODOLOGYCRITICAL Bugs leading to Ether or token theft, fund access locking or any other loss of Ether/tokens to be transferred to any party (for example, dividends). MAJOR Bugs that can trigger a contract failure. Further recovery is possible only by manual modification of the contract state or replacement. WARNINGS Bugs that can break the intended contract logic or expose it to DoS attacks. COMMENTS Other issues and recommendations reported to/acknowledged by the team. The audit was performed with triple redundancy by three auditors. Stages of the audit were as follows: 1. “Blind” manual check of the code and model behind the code 2. “Guided” manual check of the code 3. Check of adherence of the code to requirements of the client 4. Automated security analysis using internal solidity security checker 5. Automated security analysis using public analysers 6. Manual by-checklist inspection of the system 7. Discussion and merge of independent audit results 8. Report execution6 DETECTED ISSUES03 CRITICAL MAJORNone found. 1. Collision of storage layouts of TokenProxy and AkropolisToken The problem is illustrated by the `test/TestProxySlotCollision.js` (works for commit 3ad8eaa6f2849dceb125c8c614d5d61e90d465a2). As can be shown, a collision is almost completely avoided because `paused` and `locked` flags were packed by the solidity compiler and don’t collide with other fields, as well as the slot for whitelist not being used (because mappings are implemented in such way). But there is collision of `bool whitelisted` and `decimals` fields. A simple solution is to use “unique” slot locations for each field (except shared base contract fields) derived via `keccak256`, for example: https://github.com/poanetwork/poa-network-consensus-contracts/ blob/0c175cb98dac52201342f4e5e617f89a184dd467/contracts/KeysManager. sol#L185. In this case we also recommend that the contract name into hash function invocation is included, and the use of `abi.encode` in place of `abi. encodePacked`, like this: `uintStorage[keccak256(abi.encode(“TokenProxy”, “decimals”))] = decimals`. Status: – in commit 79565a3 FIXED7 WARNINGS 1. Lockable.sol#L25 A variable is named inversely to its value, meaning “unlocked” is to be expected in this case. Normally variable names are not a critical issue, but in this case as a result of code modifications during maintenance, it may lead to logic reversal. Status: – in commit 28a4153 2. AkropolisToken.sol#L41 The result of a function call from the base contract is ignored and the result is always returned as `false`. Any users of the “AkropolisToken” contract (including other smart-contracts) who check the result of the function, will consider calls to have failed. Most likely, the following piece of code is missing `return super.approve(...)`. Status: – in commit 7dee846 3. AkropolisToken.sol#L75 The result of a function call from the base contract is ignored and the result is always returned as `false`. Any users of the “AkropolisToken” contract (including other smart-contracts) who check the result of the function will consider calls to have failed. Most likely, the following piece of code is missing `return super.transfer(...)`. Status: – in commit 7dee846FIXED FIXED FIXED8 4. AkropolisToken.sol#L92 The result of a function call from the base contract is ignored and the result is always returned as `false`. Any users of the “AkropolisToken” contract (including other smart-contracts) who check the result of the function, will consider calls to have failed. It appears that the following piece of code is missing `return super.transferFrom(...)`. Status: – in commit 7dee846 5. AkropolisToken.sol#L11 The `approve` function is not disabled by default, contrary to what the comment claims. Moreover, there is a contradiction with this commentary - the `approve` function is not blocked by a designated mechanism or a flag. It’s allowed by the common pause mechanism, also implemented for the following functions: `increaseApproval`, `decreaseApproval`, `transfer`, `transferFrom`. Modifier `whenUnlocked` is removed in the following commit 434aab. Status: – in commit 28a4153FIXED FIXED COMMENTS 1. DelayedUpgradeabilityProxy.sol#L17 We recommend declaring `UPGRADE_DELAY` as `constant`. This will prevent unintended modifications and save gas. Status: ACKNOWLEDGED9 2. Solidity 0.5 We recommend updating the compiler to version 0.5 or newer, as it includes error fixes and a lot of smaller tweaks and checks, facilitating safe code writing. Status: ACKNOWLEDGED10 CONCLUSION AND RESULTS04 The use of proxy-contracts mechanism in Solidity and EVM has its risks. We detected and suggested a fix to a problem that arose in connection with it. A number of minor issues were also addressed. The rest of the code is well-structured and written perfectly. The token proxy was deployed at address 0x8ab7404063ec4dbcfd4598215992dc3f8ec853d7. The implementation was deployed at address 0xb2734a4cec32c81fde26b0024ad3ceb8c9b34037. The version 2e353cf doesn’t have any vulnerabilities or weak spots according to the analysis.MixBytes is a team of experienced developers providing top-notch blockchain solutions, smart contract security audits and tech advisory.ABOUT MIXBYTES OUR CONTACTS Alex Makeev Chief Technical Officer Vadim Buyanov Project Manager JOIN US MixBytes is a team of experienced developers providing top-notch blockchain solutions, smart contract security audits and tech advisory.ABOUT MIXBYTES OUR CONTACTS Alex Makeev Chief Technical Officer Vadim Buyanov Project Manager JOIN US
DETECTED ISSUES03 CRITICAL No critical issues were found. MAJOR 1. Collision of storage layouts of TokenProxy and AkropolisToken FIX: The storage layout of TokenProxy should be changed to match the storage layout of AkropolisToken. WARNINGS 1. Lockable.sol#L25 FIX: The modifier should be changed to require the caller to be the owner. 2. AkropolisToken.sol#L41 FIX: The function should be changed to require the caller to be the owner. 3. AkropolisToken.sol#L75 FIX: The function should be changed to require the caller to be the owner. 4. AkropolisToken.sol#L92 FIX: The function should be changed to require the caller to be the owner. 5. AkropolisToken.sol#L11 FIX: The function should be changed to require the caller to be the owner. COMMENTS 1. DelayedUpgradeabilityProxy.sol#L17 FIX: The function should be changed to require the caller to be the owner. 2. Solidity 0 Issues Count of Minor/Moderate/Major/Critical - Minor: 1 - Moderate: 0 - Major: 0 - Critical: 0 Minor Issues 2.a Problem: Collision of storage layouts of TokenProxy and AkropolisToken 2.b Fix: Use “unique” slot locations for each field derived via `keccak256` and use `abi.encode` in place of `abi.encodePacked`. Warnings 1.a Problem: Variable named inversely to its value 1.b Fix: In commit 28a4153 2.a Problem: Ignoring result of function call from base contract 2.b Fix: In commit 7dee846 3.a Problem: Ignoring result of function call from base contract 3.b Fix: In commit 7dee846 4.a Problem: Ignoring result of function call from base contract 4.b Fix: In commit 7dee846 5.a Problem: `approve` function not disabled by default 5.b Fix: None Observations - No Major or Critical issues were found. - Minor issues were found Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: DelayedUpgradeabilityProxy.sol#L17 - We recommend declaring `UPGRADE_DELAY` as `constant`. 2.b Fix: ACKNOWLEDGED9 Moderate Issues: 3.a Problem: Solidity 0.5 - We recommend updating the compiler to version 0.5 or newer, as it includes error fixes and a lot of smaller tweaks and checks, facilitating safe code writing. 3.b Fix: ACKNOWLEDGED10 Major Issues: None Critical Issues: None Observations: The use of proxy-contracts mechanism in Solidity and EVM has its risks. We detected and suggested a fix to a problem that arose in connection with it. A number of minor issues were also addressed. The rest of the code is well-structured and written perfectly. Conclusion: The token proxy was deployed at address 0x8ab7404063ec4dbcfd4598215992dc3
pragma solidity 0.5.16; 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.16; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./StormXGSNRecipient.sol"; contract StormXToken is StormXGSNRecipient, ERC20Mintable, ERC20Detailed("StormX", "STMX", 18) { using SafeMath for uint256; bool public transfersEnabled; bool public initialized = false; address public validMinter; mapping(address => bool) public recipients; // Variables for staking feature mapping(address => uint256) public lockedBalanceOf; event TokenLocked(address indexed account, uint256 amount); event TokenUnlocked(address indexed account, uint256 amount); event TransfersEnabled(bool newStatus); event ValidMinterAdded(address minter); // Testing that GSN is supported properly event GSNRecipientAdded(address recipient); event GSNRecipientDeleted(address recipient); modifier transfersAllowed { require(transfersEnabled, "Transfers not available"); _; } /** * @param reserve address of the StormX's reserve that receives * GSN charged fees and remaining tokens * after the token migration is closed */ constructor(address reserve) // solhint-disable-next-line visibility-modifier-order StormXGSNRecipient(address(this), reserve) public { recipients[address(this)] = true; emit GSNRecipientAdded(address(this)); transfersEnabled = true; } /** * @dev Adds GSN recipient that will charge users in this StormX token * @param recipient address of the new recipient * @return success status of the adding */ function addGSNRecipient(address recipient) public onlyOwner returns (bool) { recipients[recipient] = true; emit GSNRecipientAdded(recipient); return true; } /** * @dev Deletes a GSN recipient from the list * @param recipient address of the recipient to be deleted * @return success status of the deleting */ function deleteGSNRecipient(address recipient) public onlyOwner returns (bool) { recipients[recipient] = false; emit GSNRecipientDeleted(recipient); return true; } /** * @param account address of the user this function queries unlocked balance for * @return the amount of unlocked tokens of the given address * i.e. the amount of manipulable tokens of the given address */ function unlockedBalanceOf(address account) public view returns (uint256) { return balanceOf(account).sub(lockedBalanceOf[account]); } /** * @dev Locks specified amount of tokens for the user * Locked tokens are not manipulable until being unlocked * Locked tokens are still reported as owned by the user * when ``balanceOf()`` is called * @param amount specified amount of tokens to be locked * @return success status of the locking */ function lock(uint256 amount) public returns (bool) { address account = _msgSender(); require(unlockedBalanceOf(account) >= amount, "Not enough unlocked tokens"); lockedBalanceOf[account] = lockedBalanceOf[account].add(amount); emit TokenLocked(account, amount); return true; } /** * @dev Unlocks specified amount of tokens for the user * Unlocked tokens are manipulable until being locked * @param amount specified amount of tokens to be unlocked * @return success status of the unlocking */ function unlock(uint256 amount) public returns (bool) { address account = _msgSender(); require(lockedBalanceOf[account] >= amount, "Not enough locked tokens"); lockedBalanceOf[account] = lockedBalanceOf[account].sub(amount); emit TokenUnlocked(account, amount); return true; } /** * @dev The only difference from standard ERC20 ``transferFrom()`` is that * it only succeeds if the sender has enough unlocked tokens * Note: this function is also used by every StormXGSNRecipient * when charging. * @param sender address of the sender * @param recipient address of the recipient * @param amount specified amount of tokens to be transferred * @return success status of the transferring */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { require(unlockedBalanceOf(sender) >= amount, "Not enough unlocked token balance of sender"); // if the msg.sender is charging ``sender`` for a GSN fee // allowance does not apply // so that no user approval is required for GSN calls if (recipients[_msgSender()] == true) { _transfer(sender, recipient, amount); return true; } else { return super.transferFrom(sender, recipient, amount); } } /** * @dev The only difference from standard ERC20 ``transfer()`` is that * it only succeeds if the user has enough unlocked tokens * @param recipient address of the recipient * @param amount specified amount of tokens to be transferred * @return success status of the transferring */ function transfer(address recipient, uint256 amount) public returns (bool) { require(unlockedBalanceOf(_msgSender()) >= amount, "Not enough unlocked token balance"); return super.transfer(recipient, amount); } /** * @dev Transfers tokens in batch * @param recipients an array of address of the recipient * @param values an array of specified amount of tokens to be transferred * @return success status of the batch transferring */ function transfers( address[] memory recipients, uint256[] memory values ) public transfersAllowed returns (bool) { require(recipients.length == values.length, "Input lengths do not match"); for (uint256 i = 0; i < recipients.length; i++) { transfer(recipients[i], values[i]); } return true; } /** * @dev Enables the method ``transfers()`` if ``enable=true``, * and disables ``transfers()`` otherwise * @param enable the expected new availability of the method ``transfers()`` */ function enableTransfers(bool enable) public onlyOwner returns (bool) { transfersEnabled = enable; emit TransfersEnabled(enable); return true; } function mint(address account, uint256 amount) public onlyMinter returns (bool) { require(initialized, "The contract is not initialized yet"); require(_msgSender() == validMinter, "not authorized to mint"); super.mint(account, amount); return true; } /** * @dev Initializes this contract * Sets address ``swap`` as the only valid minter for this token * Note: must be called before token migration opens in ``Swap.sol`` * @param swap address of the deployed contract ``Swap.sol`` */ function initialize(address swap) public onlyOwner { require(!initialized, "cannot initialize twice"); require(swap != address(0), "invalid swap address"); addMinter(swap); validMinter = swap; initialized = true; emit ValidMinterAdded(swap); } } pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./StormXToken.sol"; import "./StormXGSNRecipient.sol"; import "../mock/OldStormXToken.sol"; contract Swap is StormXGSNRecipient { using SafeMath for uint256; StormToken public oldToken; StormXToken public newToken; bool public initialized; // Variables for supporing token swap bool public migrationOpen; uint256 public initializeTime; // Token migration should be open no shorter than 24 weeks, // which is roughly 6 months uint256 constant public MIGRATION_TIME = 24 weeks; event Initialized(uint256 initializeTime); event MigrationOpen(); event MigrationClosed(); event MigrationLeftoverTransferred(address stormXReserve, uint256 amount); event TokenConverted(address indexed account, uint256 newToken); modifier canMigrate() { require(migrationOpen, "Token Migration not available"); _; } constructor( address _oldToken, address _newToken, address reserve // solhint-disable-next-line visibility-modifier-order ) StormXGSNRecipient(_newToken, reserve) public { require(_oldToken != address(0), "Invalid old token address"); oldToken = StormToken(_oldToken); newToken = StormXToken(_newToken); } /** * @dev Accepts the ownership of the old token and * opens the token migration * Important: the ownership of the old token should be transferred * to this contract before calling this function */ function initialize() public { require(!initialized, "cannot initialize twice"); oldToken.acceptOwnership(); initialized = true; initializeTime = now; emit Initialized(initializeTime); // open token migration when this contract is initialized successfully migrationOpen = true; emit MigrationOpen(); } /** * @dev Transfers the ownership of the old token to a new owner * Reverts if current contract is not the owner yet * Note: after this function is invoked, ``newOwner`` has to * accept the ownership to become the actual owner by calling * ``acceptOwnership()`` of the old token contract * @param newOwner the expected new owner of the old token contract */ function transferOldTokenOwnership(address newOwner) public onlyOwner { oldToken.transferOwnership(newOwner); } /** * @dev Swaps certain amount of old tokens to new tokens for the user * @param amount specified amount of old tokens to swap * @return success status of the conversion */ function convert(uint256 amount) public canMigrate returns (bool) { address account = _msgSender(); require(oldToken.balanceOf(_msgSender()) >= amount, "Not enough balance"); // requires the ownership of original token contract oldToken.destroy(account, amount); newToken.mint(account, amount); emit TokenConverted(account, amount); return true; } /** * @dev Disables token migration successfully if it has already been MIGRATION_TIME * since token migration opens, reverts otherwise * @param reserve the address that the remaining tokens are sent to * @return success status */ function disableMigration(address reserve) public onlyOwner canMigrate returns (bool) { require(reserve != address(0), "Invalid reserve address provided"); require(now - initializeTime >= MIGRATION_TIME, "Not able to disable token migration yet"); migrationOpen = false; emit MigrationClosed(); mintAndTransfer(reserve); return true; } /** * @dev Called by ``disableMigration()`` * if token migration is closed successfully. * Mint and transfer the remaining tokens to stormXReserve * @param reserve the address that the remaining tokens are sent to * @return success status */ function mintAndTransfer(address reserve) internal returns (bool) { uint256 amount = oldToken.totalSupply(); newToken.mint(reserve, amount); emit MigrationLeftoverTransferred(reserve, amount); return true; } } pragma solidity 0.5.16; import "@openzeppelin/contracts/GSN/GSNRecipient.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../interface/IStormXToken.sol"; contract StormXGSNRecipient is GSNRecipient, Ownable { // Variables and constants for supporting GSN uint256 constant INSUFFICIENT_BALANCE = 11; uint256 public chargeFee; address public stormXReserve; // importing ``StormXToken.sol`` results in infinite loop // using only an interface IStormXToken public token; event StormXReserveSet(address newAddress); event ChargeFeeSet(uint256 newFee); constructor(address tokenAddress, address reserve) public { require(tokenAddress != address(0), "Invalid token address"); require(reserve != address(0), "Invalid reserve address"); token = IStormXToken(tokenAddress); stormXReserve = reserve; chargeFee = 10; } function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 maxPossibleCharge ) external view returns (uint256, bytes memory) { bool chargeBefore = true; if (token.unlockedBalanceOf(from) < chargeFee) { bytes4 selector = readBytes4(encodedFunction, 0); if (selector == bytes4(keccak256("convert(uint256)"))) { uint256 amount = uint256(getParam(encodedFunction, 0)); if (amount >= chargeFee) { // we can charge this after the conversion chargeBefore = false; return _approveRelayedCall(abi.encode(from, chargeBefore)); } else { return _rejectRelayedCall(INSUFFICIENT_BALANCE); } } else { return _rejectRelayedCall(INSUFFICIENT_BALANCE); } } else { return _approveRelayedCall(abi.encode(from, chargeBefore)); } } /** * @dev Sets the address of StormX's reserve * @param newReserve the new address of StormX's reserve * @return success status of the setting */ function setStormXReserve(address newReserve) public onlyOwner returns (bool) { require(newReserve != address(0), "Invalid reserve address"); stormXReserve = newReserve; emit StormXReserveSet(newReserve); return true; } /** * @dev Sets the charge fee for GSN calls * @param newFee the new charge fee * @return success status of the setting */ function setChargeFee(uint256 newFee) public onlyOwner returns (bool) { chargeFee = newFee; emit ChargeFeeSet(newFee); return true; } function _preRelayedCall(bytes memory context) internal returns (bytes32) { (address user, bool chargeBefore) = abi.decode(context, (address, bool)); // charge the user with specified amount of fee // if the user is not calling ``convert()`` if (chargeBefore) { token.transferFrom(user, stormXReserve, chargeFee); } return ""; } function _postRelayedCall( bytes memory context, bool success, uint256 actualCharge, bytes32 preRetVal ) internal { (address user, bool chargeBefore) = abi.decode(context, (address, bool)); if (!chargeBefore) { token.transferFrom(user, stormXReserve, chargeFee); } } /** * @dev Reads a bytes4 value from a position in a byte array. * Note: for reference, see source code * https://etherscan.io/address/0xD216153c06E857cD7f72665E0aF1d7D82172F494#code * @param b Byte array containing a bytes4 value. * @param index Index in byte array of bytes4 value. * @return bytes4 value from byte array. */ function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { require( b.length >= index + 4, "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED" ); // Arrays are prefixed by a 32 byte length field index += 32; // Read the bytes4 from array memory assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } /** * @dev Reads a bytes32 value from a position in a byte array. * Note: for reference, see source code * https://etherscan.io/address/0xD216153c06E857cD7f72665E0aF1d7D82172F494#code * @param b Byte array containing a bytes32 value. * @param index Index in byte array of bytes32 value. * @return bytes32 value from byte array. */ function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } /** * @dev Reads a uint256 value from a position in a byte array. * Note: for reference, see source code * https://etherscan.io/address/0xD216153c06E857cD7f72665E0aF1d7D82172F494#code * @param b Byte array containing a uint256 value. * @param index Index in byte array of uint256 value. * @return uint256 value from byte array. */ function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } /** * @dev extract parameter from encoded-function block. * Note: for reference, see source code * https://etherscan.io/address/0xD216153c06E857cD7f72665E0aF1d7D82172F494#code * https://solidity.readthedocs.io/en/develop/abi-spec.html#formal-specification-of-the-encoding * note that the type of the parameter must be static. * the return value should be casted to the right type. * @param msgData encoded calldata * @param index in byte array of bytes memory * @return the parameter extracted from call data */ function getParam(bytes memory msgData, uint index) internal pure returns (uint) { return readUint256(msgData, 4 + index * 32); } }
November 8th 2020— Quantstamp Verified StormX - Token Swap This smart contract audit was prepared by Quantstamp, the protocol for securing smart contracts. Executive Summary Type Token and Token Swap Auditors Kacper Bąk , Senior Research EngineerLeonardo Passos , Senior Research EngineerEd Zulkoski , Senior Security EngineerTimeline 2020-03-18 through 2020-04-24 EVM Constantinople Languages Solidity, Javascript Methods Architecture Review, Unit Testing, Computer-Aided Verification, Manual Review Specification StormX ERC20 Token Swap Source Code Repository Commit stormx-token 0d1a63b Goals Can users' tokens be locked up forever? •Can users be charged correctly after the token upgrade? •Can user lose any tokens in the process of token upgrade? •Total Issues 3 (0 Resolved)High Risk Issues 0 (0 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 3 (0 Resolved)Informational Risk Issues 0 (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 FindingsGenerally, the code is well written, well documented, and well tested. We communicated several issue and recommendations to the development team, provided ideas for improvements. as of commit and our main concerns are addressed. Update: 813acda 8177534 ID Description Severity Status QSP- 1 Centralization of Power Low Acknowledged QSP- 2 Transaction order dependencies between and functions that read setChargeFee()chargeFee Low Acknowledged QSP- 3 Allowance Double-Spend Exploit Low 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.5.8 • SolidityCoveragev0.2.7 • Mythrilv0.6.6 • SlitherSteps taken to run the tools: 1. Installed the solidity-coverage tool (within the project's root directory):npm install --save-dev solidity-coverage 2. Ran the coverage tool from the project's root directory:./node_modules/.bin/solidity-coverage 3. Installed the Mythril tool from Pypi:pip3 install mythril 4. Ran the Mythril tool on each contract:myth -x path/to/contract 5. Installed the Slither tool:pip install slither-analyzer 6. Run Slither from the project directory:s slither . FindingsQSP-1 Centralization of Power Severity: Low Risk Acknowledged Status: File(s) affected: StormXGSNRecipient.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 this project, centralization of power has the form of the owner being able to set fees associated with the GSN network, and to close the migration after the time window enforced by the smart contract elapses. The owner does not have any privileges to confiscate users' tokens. The centralization of power is documented and explained to users. Recommendation: QSP-2 Transaction order dependencies between and functions that read setChargeFee() chargeFee Severity: Low Risk Acknowledged Status: File(s) affected: StormXGSNRecipient.sol There exists transaction order dependencies between and functions that read . If increases, it may result in rejecting a user's meta- transaction. Description:setChargeFee() chargeFee chargeFee For example, assume that = 1. If a user knows that and they have exactly enough tokens to cover the , they can submit the meta-transaction to the relayer and it will get executed. If after submitting the transaction to the relayer (but before it gets submitted to the contract), the owner changes to 2 and then the transaction gets executed, it will fail. Exploit Scenario:chargeFee chargeFee chargeFee We do not have a recommendation. TOD issues are typically benign yet difficult to fix. Recommendation: QSP-3 Allowance Double-Spend Exploit Severity: Low Risk Acknowledged Status: File(s) affected: StormXToken.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 the method 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. The exploit (as described above) is mitigated through use of functions that increase/decrease the allowance relative to its current value, such as and . transferFrom()M 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. Recommendation:approve() transferFrom() Adherence to Specification It is unclear whether should return 0 instead of reverting if > . • unlockedBalanceOf() lockedBalanceOf[account] balanceOf(account) in , is there a reason that needs the parameter? • Swap.soldisableMigration() reserve Code Documentation In , what is the point of enabling/disabling ? • StormXToken.soltransfers() The following requirement in the may be unclear to some readers: • README.md If the user does not have enough unlocked token balance and is calling the function convert(uint256 amount), this contract accepts the GSN relayed call and charges users only if they will have enough unlocked new token balance after convert(uint256 amount) is executed, i.e. amount >= chargeFee. For example, it could be parsed like this: [If the user does not have enough unlocked token balance and is calling the function convert(uint256 amount), this contract accepts the GSN relayed call] [charges users only if they will have enough unlocked new token balance after convert(uint256 amount) is executed, i.e. amount >= chargeFee]. andalthough the following is implemented: resolved.[If the user does not have enough unlocked token balance and is calling the function convert(uint256 amount), this contract accepts the GSN relayed call and chargesusers] [they will have enough unlocked new token balance after convert(uint256 amount) is executed, i.e. amount >= chargeFee]. only if Update: `README.md states that: •The token contract includes features for privileged access that allow StormX to mint new tokens for and remove tokens from arbitrary accounts. The StormX team sought to develop a new ERC20 token smart contract that will not include the aforementioned functions. We recommend to explicitly state the names of those functions that you refer to when when stating . As the new contract (the one developed by Quanstamp) does have a mint function, such a clarification is required to give a clear understanding. aforementioned functions• : GSN acronym is used, but not defined. When first using the GSN acronym, write what it means => “Gas Station Network”. resolved. README.md Update: • In : the and lack documentation. We recommend adding documentation. At the very least, all external and public functions should be documented. resolved. StormXGSNRecipient.solconstructor acceptRelayedCall Update: • In the following comment is confusing: We recommend improving the comment. resolved. StormXToken.sol#40@param reserve address of the StormX's reserve that receives”. Update: • In the following this comment is confusing: . We recommend improving the comment. StormXToken.sol#L75@param account address of the user this function queries unlocked balance for • In the following comment is confusing: . Probably meant . We recommend improving the comment. resolved. StormXToken.sol#L150@param recipients an array of address of the recipient an array of recipient addresses Update: Adherence to Best Practices in , we recommend defining a constant for to save gas • StormXGSNRecipient.sol#48selector in , is only relevant to the contract. , however, inherits from . If you want both contracts to reuse the code, please document the use case. •StormXGSNRecipient.solconvert() Swap StormXToken StormXGSNRecipient in , instead of defining , we recommend reusing , particularly since the else clause is not related to the balance. •StormXGSNRecipient.sol#58INSUFFICIENT_BALANCE GSNRecipient.RELAYED_CALL_REJECTED still references . We recommend declaring an interface to import instead. • Swap.solmock/OldStormXToken in , "supporing" should be "supporting". resolved. • Swap.sol#17Update: in the constructor could re-use . resolved (function removed). • StormXTokenaddGSNRecipient() Update: in , in , the parameter shadows the state variable of the same name. resolved. • StormXTokentransfers() recipients Update: in there is a lot of trailing space throughout the file. We recommend remove any trailing space. resolved. • StormXToken.solUpdate: in and some functions always return . Consequently, the return value has no semantics, as no exception is ever going to happen (otherwise, a false value could be returned). is an example of such a function. We recommend for functions that only return true and are not part of the ERC-20 standard to return nothing. •StormXToken.solStormXGSNRecipient.sol true enableTransfers() in the functions and do not check if is different from 0x0. We recommend adding statements to check if is different from 0x0. resolved. •StormXToken.soladdGSNRecipient() deleteGSNRecipient() recipient require() recipient Update: in , the function uses the modifier, but later restricts that must be equal to the address. Two scenarios are possible here: (a) if the sender must be equal to the swap address, then the modifier is unnecessary; (b) on the other hand, if only added minters can call such a function, then the require statement checking equality against the swap address is not needed. Choose what scenario applies and change the code accordingly. resolved. •StormXToken.solmint() onlyMinter sender swap onlyMinter Update: Test Results Test Suite Results Contract: StormX token GSN rewarding feature test ✓ owner and only owner can assign reward role via GSN test (675ms) ✓ owner and rewardRole can reward users via GSN success test (880ms) ✓ users cannot invoke reward() test (86ms) ✓ revert when invalid parameter provided in reward() test (109ms) ✓ revert when not enough tokens to reward users test (136ms) ✓ revert when input lenghts do not match in rewards() via GSN test (134ms) ✓ owner and rewardRole can reward users in batch via GSN success test (989ms) ✓ rewarding in batch via GSN fails if not enough balance of caller test (183ms) ✓ setAutoStaking via GSN success test (555ms) ✓ rewarded tokens will not be staked if auto-staking feature is disabled test (889ms) Contract: StormX token staking feature GSN test ✓ GSN lock fails if not enough unlocked balance of user test (252ms) ✓ GSN lock success test (346ms) ✓ GSN unlock fails if not enough locked balance of user test (347ms) ✓ GSN unlock succeeds if enough unlocked balance of user after transaction test (1088ms) ✓ GSN unlock fails if not enough unlocked balance of user after transaction test (592ms) ✓ GSN unlock success test (573ms) Contract: StormX token GSN test ✓ GSN call fails if not enough balance of user test (209ms) ✓ GSN transfer fails if not enough balance after being charged test -- case1 (298ms) ✓ GSN transfer fails if not enough balance after being charged test -- case2 (126ms) ✓ GSN transfer success test (283ms) ✓ GSN transferFrom fails if not enough balance to be transferred test (308ms) ✓ GSN transferFrom fails if not enough balance to be charged test (425ms) ✓ GSN transferFrom success only with enough allowance test (634ms) ✓ GSN transfers success test (423ms) ✓ GSN transfers fails if input lengths do not match in transfers test (94ms)✓ GSN transfers fails if any transfer fails test (125ms) ✓ owner and only owner can enable/disable GSN transfers via GSN test (1147ms) ✓ GSN transferFrom success if enough token balance after transaction test (1100ms) ✓ owner and only owner can set GSN charge test (451ms) ✓ reverts if invalid parameter provided in set stormx reserve address test (98ms) ✓ owner and only owner can set stormx reserve address test (1021ms) Contract: StormX token rewarding test ✓ owner and only owner can assign reward role test (88ms) ✓ owner and rewardRole can reward users success test (285ms) ✓ revert when invalid parameter provided in reward() test (60ms) ✓ revert when not enough tokens to reward users test (65ms) ✓ users cannot invoke reward() test ✓ revert when input lenghts do not match in rewards() test ✓ owner and rewardRole can reward users in batch success test (393ms) ✓ rewarding in batch fails if not enough balance of caller test (158ms) ✓ setAutoStaking success test (121ms) ✓ rewarded tokens will not be staked if auto-staking feature is disabled test (352ms) Contract: StormX token test ✓ name test ✓ symbol test ✓ decimals test ✓ initialize success test (106ms) ✓ revert if initialize not called by owner test (82ms) ✓ revert if initialize twice test (120ms) ✓ revert if invalid parameters provided in initialize test (101ms) ✓ revert if invalid parameters provided in constructor test (47ms) ✓ revert if not authorized to mint test ✓ revert if calling mint before initialization test (83ms) ✓ owner and only owner can set stormX reserve (94ms) ✓ revert when invalid address provided in set stormX reserve ✓ read locked balance of user success test (77ms) ✓ read unlocked balance of user success test (70ms) ✓ transfer reverts if not enough unlocked token test (102ms) ✓ transfer success test (186ms) ✓ transferFrom reverts if not enough unlocked token test (122ms) ✓ transferFrom success test (249ms) ✓ lock reverts if no enough unlocked token test (102ms) ✓ lock success test (176ms) ✓ unlock reverts if no enough locked token test (103ms) ✓ unlock success test (218ms) ✓ revert if input lengths do not match in transfers test ✓ revert if transfers not available test (60ms) ✓ revert if any transfer fails test ✓ transfers success test (84ms) ✓ owner and only owner can enable/disable transfers test (456ms) Contract: StormX token swap test ✓ revert if invalid parameters provided in constructor test (125ms) ✓ revert if initialize twice test ✓ revert if ownership is not transferred before initialize test (74ms) ✓ initialize success test (224ms) ✓ revert if transferring ownership without holding the ownership test (90ms) ✓ revert if transferring ownership not called by owner test (184ms) ✓ swap contract owner transfers ownership success test (244ms) ✓ revert if not enough balance in token swap test ✓ token swap reverts when it is not available test (74ms) ✓ token swap success test (95ms) ✓ owner and only owner can close token migration after specified time period test (307ms) ✓ revert if invalid reserve address is provided in disableMigration test ✓ revert if closing token migration when token swap is not open test (535ms) Contract: Token swap GSN test ✓ revert if initialize is called twice (83ms) ✓ revert if transferring old token ownership without holding the ownership test (375ms) ✓ transfer old token ownership fails if not enough token balance test (174ms) ✓ owner and only owner can transfer old token ownership test (377ms) ✓ convert via GSN call fails if not enough old token balance of user test (93ms) ✓ convert via GSN call fails if not enough unlocked new token balance of user even after conversion test (174ms) ✓ convert via GSN call succeeds with charging if have enough unlocked new token balance after conversion test (1283ms) ✓ convert via GSN call success test (668ms) ✓ revert if disabling token swap too early via GSN call test (82ms) ✓ revert if invalid parameters provided in disabling token swap via GSN call test (81ms) ✓ owner and only owner can disable token swap via GSN call success test (446ms) ✓ owner and only owner can set GSN charge test (491ms) ✓ reverts if invalid parameter provided in set stormx reserve address test (76ms) ✓ owner and only owner can set stormx reserve address test (1191ms) 95 passing (1m) Code Coverage The contracts feature excellent test coverage. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 100 94.59 100 100 StormXGSNRecipient.sol 100 80 100 100 StormXToken.sol 100 100 100 100 Swap.sol 100 100 100 100 All files 100 94.59 100 100 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 d87b00c4d1e25e004e3134a39901952d93771572a7d84f32bc1f8ffd5e3763c4 ./contracts/Migrations.sol 4702c6256cc84d644e5fec90da1fe0ed8a0ce19af660c2c4ce6f801989a9cb40 ./contracts/StormXToken.sol 5654854ee811cfcb1e5dcefd9b890f9b4ae1266fa0a8b8b0cc89cb604128cb3d ./contracts/Swap.sol 7029552776a09d30eb61f4d43ad438132856c97bdfd7010fb826912afd01f69d ./contracts/StormXGSNRecipient.sol Tests 7f2e9842aa84dfb0ca2281ece03aa7e2d790a0bcd998dd5c86fa65d5d70886e2 ./test/Constants.js bfd4054b1dd343f44d2ff81b0518d2aa89538b7fefccd7cea86ef2836495d535 ./test/StormXGSNRewarding.test.js aa33128cdddcf6f5e9bd37fc66de07291dc8f14fd7e5f8538bbe842b6e3d8079 ./test/SwapGSNTest.test.js 01f294402df68eb4b92a88abb8135af0cb6d975ba7b2530157ecc4fa46bce5b8 ./test/StormXToken.test.js ea82665a191090df0175fa2f101ecad7b5d1eb47a45d8cd1325b8dc80e629e8e ./test/Swap.test.js 00b7da24c0eafcfbcf69fb151d89e59bfe8ae25477d0490928aa211ee3cc1529 ./test/StormXRewarding.test.js 5bce96cdbe7aae1a069e81491df59c0d0320e7b09aeee8a939fc76affe297131 ./test/Utils.js 1565921b89d01ce27757ec34fca42808d764f5710c57c97c79eca8fbe4b6db9d ./test/StormXGSNStaking.test.js 026468731ac66312447e2c63843e77da9929646c85d1cc78fa1b5f4766c370c3 ./test/StormXGSNTest.test.js Changelog 2020-03-24 - Initial report •2020-03-25 - Revised report based on commit •eb3be3c 2020-03-26 - Revised report based on commit •813acda 2020-04-24 - Revised report based on commit •8177534 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. StormX - Token Swap Audit
Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations - The code is well written, well documented, and well tested. - Several issues and recommendations were communicated to the development team. - Ideas for improvements were provided. Conclusion The main concerns were addressed as of the commit and the code is secure. Issues Count of Minor/Moderate/Major/Critical: Minor: 3 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Transaction order dependencies between and functions that read setChargeFee()chargeFee (QSP-2) 2.b Fix: Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract (QSP-2) 3.a Problem: Allowance Double-Spend Exploit (QSP-3) 3.b Fix: Review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract (QSP-3) Major/Critical: None Observations: • Code review that includes the review of the specifications, sources, and instructions provided to Quantstamp to make sure we understand the size, scope, and functionality of the smart contract. • Testing and automated analysis that includes test coverage analysis, symbolic execution. • Best practices review to improve efficiency, effectiveness, clarify, maintainability, security, and control based on Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: QSP-1 Centralization of Power Problem: Smart contracts will often have variables to designate the person with special privileges to make modifications to the smart contract. Fix: Centralization of power is documented and explained to users. QSP-2 Transaction order dependencies between setChargeFee() and functions that read chargeFee Problem: If chargeFee increases, it may result in rejecting a user's meta- transaction. Fix: No recommendation. Observations: Allowance Double-Spend Exploit is mitigated through use of functions that increase/decrease the allowance relative to its current value, such as approve() and transferFrom(). Conclusion: The audit report found two minor issues with the smart contract, both of which have been addressed. No major or critical issues were found.
// SPDX-License-Identifier: MIT // SWC-Outdated Compiler Version: L3 pragma solidity 0.8.10; contract MooMonsterTimelock { event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint256 indexed newDelay); event CancelTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecuteTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueueTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); uint256 public constant GRACE_PERIOD = 14 days; uint256 public constant MINIMUM_DELAY = 0; uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; bool public admin_initialized; mapping(bytes32 => bool) public queuedTransactions; constructor(address admin_, uint256 delay_) { 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; } receive() external payable {} function setDelay(uint256 delay_) external { 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() external { require( msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin." ); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) external { 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, uint256 value, string memory signature, bytes memory data, uint256 eta ) external returns (bytes32) { require( msg.sender == admin, "Timelock::queueTransaction: Call must come from admin." ); require( eta >= getBlockTimestamp() + 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, uint256 value, string memory signature, bytes memory data, uint256 eta ) external { 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 _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { if (_returnData.length < 68) return "Transaction reverted silently"; assembly { _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) external 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 + 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, _getRevertMsg(returnData)); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } }
Token & Vesting Smart Contract Audit Report Prepared for Moo Monster __________________________________ Date Issued: Dec 2, 2021 Project ID: AUDIT2021049 Version: v1.0 Confidentiality Level: Public Public ________ Report Information Project ID AUDIT2021049 Version v1.0 Client Moo Monster Project Token & Vesting Auditor(s) Weerawat Pawanawiwat Author Weerawat Pawanawiwat Reviewer Suvicha Buakhom Confidentiality Level Public Version History Version Date Description Author(s) 1.0 Dec 2, 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 2 2.1. Project Introduction 2 2.2. Scope 3 3. Methodology 4 3.1. Test Categories 4 3.2. Audit Items 5 3.3. Risk Rating 6 4. Summary of Findings 7 5. Detailed Findings Information 9 5.1. Improper Reward Calculation for Event Emission 9 5.2. Token Withdrawal by Contract Owner 12 5.3. Outdated Solidity Compiler Version 14 5.4. Inexplicit Solidity Compiler Version 15 6. Appendix 16 6.1. About Inspex 16 6.2. References 17 Public ________ 1. Executive Summary As requested by Moo Monster, Inspex team conducted an audit to verify the security posture of the Token & Vesting smart contracts on Nov 29, 2021. During the audit, Inspex team examined all smart contracts and the overall operation within the scope to understand the overview of Token & Vesting 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. 1.1. Audit Result In the initial audit, Inspex found 2 low, 1 very low, and 1 info-severity issues. With the project teamʼs prompt response, 1 low, 1 very low, and 1 info-severity issues were resolved in the reassessment, while 1 low-severity issue was acknowledged by the team. Therefore, Inspex trusts that Token & Vesting smart contracts have sufficient protections to be safe for public use. However, in the long run, Inspex suggests resolving all issues found in this report. 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 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: AUDIT2021049 (v1.0) 1 Public ________ 2. Project Overview 2.1. Project Introduction MooMonster is a Free-to-Play and Play-to-Earn NFT Game. The users can go on an adventure with the Moo monster in the “Mooniverse” world. Token & Vesting smart contracts are responsible for the creation of $MOO, and the distribution of the token to the users in different categories according to the tokenomics. The token will be gradually released in steps, and the users can claim their token in each category through the MooVesting smart contract. Scope Information: Project Name Token & Vesting Website https://moo-monster.com/ Smart Contract Type Ethereum Smart Contract Chain Binance Smart Chain Programming Language Solidity Audit Information: Audit Method Whitebox Audit Date Nov 29, 2021 Reassessment Date Dec 1, 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: AUDIT2021049 (v1.0) 2 Public ________ 2.2. Scope The following smart contracts were audited and reassessed by Inspex in detail: Initial Audit: (Commit: b41b575431843055677bfc2213ac42a4468760dc) Contract Location (URL) MooMonsterToken https://github.com/Moo-Monster/MooMonster-Contract/blob/b41b575431/contracts /tokens/MooMonsterToken.sol MooVesting https://github.com/Moo-Monster/MooMonster-Contract/blob/b41b575431/contracts /vesting/MooVesting.sol Reassessment: (Commit: 2d07e927e5e8f66afea5cbdfb89b32ef74cfe385) Contract Location (URL) MooMonsterToken https://github.com/Moo-Monster/MooMonster-Contract/blob/2d07e927e5/contracts /tokens/MooMonsterToken.sol MooVesting https://github.com/Moo-Monster/MooMonster-Contract/blob/2d07e927e5/contracts /vesting/MooVesting.sol The assessment scope covers only the in-scope smart contracts and the smart contracts that they inherit from. Inspex Smart Contract Audit Report: AUDIT2021049 (v1.0) 3 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: AUDIT2021049 (v1.0) 4 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 Insufficient Logging for Privileged Functions Invoking of Unreliable Smart Contract Use of Upgradable Contract Design Advanced Business Logic Flaw Ownership Takeover Broken Access Control Broken Authentication Improper Kill-Switch Mechanism Inspex Smart Contract Audit Report: AUDIT2021049 (v1.0) 5 Public ________ Improper Front-end Integration Insecure Smart Contract Initiation 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: AUDIT2021049 (v1.0) 6 Public ________ 4. Summary of Findings From the assessments, Inspex has found 4 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: AUDIT2021049 (v1.0) 7 Public ________ The information and status of each issue can be found in the following table: ID Title Category Severity Status IDX-001 Improper Reward Calculation for Event Emission Advanced Low Resolved IDX-002 Token Withdrawal by Contract Owner Advanced Low Acknowledged IDX-003 Outdated Solidity Compiler Version General Very Low Resolved IDX-004 Inexplicit Solidity Compiler Version Best Practice Info Resolved Inspex Smart Contract Audit Report: AUDIT2021049 (v1.0) 8 Public ________ 5. Detailed Findings Information 5.1. Improper Reward Calculation for Event Emission ID IDX-001 Target MooVesting Category Advanced Smart Contract Vulnerability CWE CWE-682: Incorrect Calculation Risk Severity: Low Impact: Low The amount of reward claimed in the event emitted will be incorrect. This disrupts the tracking of token amounts from logs, and may result in loss of reputation for the platform. Likelihood: Medium The miscalculation will happen when the reward is not claimed to the latest step before the claiming of the last step reward. Status Resolved Moo Monster team has resolved this issue as suggested in commit 2 d 0 7 e 9 2 7 e 5 e 8 f 6 6 a f e a 5 c b d f b 8 9 b 3 2 e f 74cfe385 by modifying the calculation logic. 5.1.1. Description The M o o V e s t i n g contract manages the distribution of $MOO by allowing the designated users to receive the token in steps. The claimable amount for each step is calculated using the percentage defined in each category. For the release of the last step, all of the remaining reward will be distributed to the user as seen in line 232. MooVesting.sol 2 1 6 2 1 7 2 1 8 2 1 9 2 2 0 2 2 1 2 2 2 2 2 3 2 2 4 2 2 5 2 2 6 2 2 7 2 2 8 2 2 9 u i n t 2 5 6 s e c o n d R e l e a s e = t g e T i m e s t a m p . a d d (category.cliffAfterTGE); u i n t 2 5 6 r e w a r d e d = a l r e a d y R e w a r d e d [ t a r g e tHash]; / / c l a i m r e w a r d a f t e r T G E f o r ( u i n t 2 5 6 i = l a s t C l a i m e d S t e p [ t a r g e t H a s h ] + 1 ; i < = c a t e g o r y . t o t a l S t e p s ; i + + ) { u i n t 2 5 6 a d d e d A m o u n t = 0 ; i f ( s e c o n d R e l e a s e . a d d ( c a t e g o r y . s t e p Time.mul(i)) < = b l o c k . t i m e s t a m p ) { l a s t C l a i m e d S t e p [ t a r g e t H a s h ] = i ; Inspex Smart Contract Audit Report: AUDIT2021049 (v1.0) 9 Public ________ 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 2 4 0 2 4 1 2 4 2 2 4 3 i f ( i = = c a t e g o r y . t o t a l S t e p s ) { / / l a s t s t e p r e l e a s e a l l a d d e d A m o u n t = _ a m o u n t . s u b ( r e w a r d ed); } e l s e { a d d e d A m o u n t = _ a m o u n t . m u l ( c a t e g o ry.percentAfter).div( 1 0 0 _ 0 0 ) ; } r e w a r d = r e w a r d . a d d ( a d d e d A m o u n t ) ; e m i t S t e p C l a i m ( _ t a r g e t , _ c a t e g o r y , i , addedAmount, b l o c k . t i m e s t a m p ) ; } e l s e { b r e a k ; } } However, if the r e w a r d e d variable is not updated to the latest step before the last, the value of a d d e d A m o u n t will exceed the intended amount. This causes the S t e p C l a i m event to have an improper value of a d d e d A m o u n t amount emitted, which can cause confusions for the people who are monitoring the logs. Furthermore, the reward amount to be claimed in the r e w a r d variable will be overly inflated, but fortunately, the code at line 250-254 has capped the upper limit of the user's eligible reward, so that limit will not be exceeded. MooVesting.sol 2 4 5 2 4 6 2 4 7 2 4 8 2 4 9 2 5 0 2 5 1 2 5 2 2 5 3 2 5 4 2 5 5 2 5 6 2 5 7 r e q u i r e ( r e w a r d > 0 , " M O O V e s t i n g : n o t o k e n s t o c l a i m " ) ; u i n t 2 5 6 r e s u l t R e w a r d = 0 ; / / i f r e w a r d o v e r l i m i t ( s e c u r i t y check) i f ( r e w a r d e d . a d d ( r e w a r d ) > _ a m o u n t ) { r e s u l t R e w a r d = _ a m o u n t . s u b ( r e w a r d e d , " M O O V e s t i n g : n o t o k e n s t o c l a i m (security c h e c k ) " ) ; } e l s e { r e s u l t R e w a r d = r e w a r d ; } Inspex Smart Contract Audit Report: AUDIT2021049 (v1.0) 10 Public ________ 5.1.2. Remediation Inspex suggests modifying the calculation on line 232 to include the reward amount claimed in the current execution, for example: MooVesting.sol 2 2 0 2 2 1 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 2 4 0 2 4 1 2 4 2 2 4 3 f o r ( u i n t 2 5 6 i = l a s t C l a i m e d S t e p [ t a r g e t H a s h ] + 1 ; i < = c a t e g o r y . t o t a l S t e p s ; i + + ) { u i n t 2 5 6 a d d e d A m o u n t = 0 ; i f ( s e c o n d R e l e a s e . a d d ( c a t e g o r y . s t e p Time.mul(i)) < = b l o c k . t i m e s t a m p ) { l a s t C l a i m e d S t e p [ t a r g e t H a s h ] = i ; i f ( i = = c a t e g o r y . t o t a l S t e p s ) { / / l a s t s t e p r e l e a s e a l l a d d e d A m o u n t = _ a m o u n t . s u b ( r e w a r d ed.add(reward)); } e l s e { a d d e d A m o u n t = _ a m o u n t . m u l ( c a t e g o ry.percentAfter).div( 1 0 0 _ 0 0 ) ; } r e w a r d = r e w a r d . a d d ( a d d e d A m o u n t ) ; e m i t S t e p C l a i m ( _ t a r g e t , _ c a t e g o r y , i , addedAmount, b l o c k . t i m e s t a m p ) ; } e l s e { b r e a k ; } } Inspex Smart Contract Audit Report: AUDIT2021049 (v1.0) 11 Public ________ 5.2. Token Withdrawal by Contract Owner ID IDX-002 Target MooVesting Category Advanced Smart Contract Vulnerability CWE CWE-284: Improper Access Control Risk Severity: Low Impact: Medium The users will not be able to claim some parts of the token that they are eligible for, resulting in monetary loss for the users and reputation damage to the platform. Likelihood: Low The withdrawal can only be done 41 months a
Project Introduction Token & Vesting is a smart contract platform that allows users to create and manage their own tokens and vesting contracts. The platform is designed to be secure and reliable, and provides users with a secure and easy-to-use interface for managing their tokens and vesting contracts. 2.2. Scope The scope of this audit includes the following smart contracts: • Token & Vesting Token (Token.sol) • Token & Vesting Vesting (Vesting.sol) • Token & Vesting Event (Event.sol) 3. Methodology 3.1. Test Categories Inspex team conducted the audit using the following test categories: • Security: Security tests are conducted to identify potential security vulnerabilities in the smart contracts. • Functional: Functional tests are conducted to identify potential functional issues in the smart contracts. • Code Quality: Code quality tests are conducted to identify potential code quality issues in the smart contracts. • Business Logic: Business logic tests are conducted to identify potential business logic issues in the smart contracts. 3.2. Audit Items Inspex team conducted the audit using the following audit items: 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 MooMonsterToken.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 audit was conducted using Whitebox method, where the complete source code of the smart contracts were provided for the assessment. - The audit scope covers only the in-scope smart contracts and the smart contracts that they inherit from. - The audit methodology consists of both automated testing with scanning tools and manual testing by experienced testers. Conclusion: The audit of the MooMonster Token & Vesting smart contracts revealed 2 minor issues, which have been fixed. No moderate, major or critical issues were found. Issues Count of Minor/Moderate/Major/Critical - Minor: 4 - Moderate: 8 - Major: 4 - Critical: 0 Minor Issues - Reentrancy Attack (Low Likelihood, Low Impact) - Integer Overflows and Underflows (Low Likelihood, Low Impact) - Unchecked Return Values for Low-Level Calls (Low Likelihood, Low Impact) - Bad Randomness (Low Likelihood, Low Impact) Moderate Issues - Transaction Ordering Dependence (Low Likelihood, Medium Impact) - Time Manipulation (Low Likelihood, Medium Impact) - Short Address Attack (Low Likelihood, Medium Impact) - Outdated Compiler Version (Low Likelihood, Medium Impact) - Use of Known Vulnerable Component (Low Likelihood, Medium Impact) - Deprecated Solidity Features (Low Likelihood, Medium Impact) - Use of Deprecated Component (Low Likelihood, Medium Impact) - Loop with High Gas Consumption (Low Likelihood, Medium Impact) Major Issues - Unauthorized Self-destruct (Medium Likelihood, High Impact) - Redundant Fallback Function (Medium Likelihood, High Impact
// 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): zNS and zAuction systems have potential security issues (19 April 2021 to 21 May 2021). 2.b Fix (one line with code reference): Walkthrough session for the systems in scope to understand the fundamental design decisions of the system and initial security findings were shared with the client. Moderate: 3.a Problem (one line with code reference): zBanc code revision was updated half-way into the week on Wednesday (3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4). 3.b Fix (one line with code reference): Preliminary findings were shared during a sync-up discussing the changing codebase under review. Major: None Critical: None Observations: The assessment team focussed its work on the zNS and zAuction systems in the first week. Details on the scope for the components was set by the client and a walkthrough session 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) - Inadequate input validation in zAuction (line 545) 2.b Fix (one line with code reference) - Add input validation in zAuction (line 545) Observations - Code-style and quality varies a lot for the different repositories under review - Security activities and key milestones should be explicitly included in the software development lifecycle Conclusion - Security review readiness should be established ahead of any security activities - A dedicated role should be created to coordinate security on the team Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unchecked return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395) 2.b Fix: Check return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395) Moderate: 3.a Problem: Unchecked return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72) 3.b Fix: Check return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72) Major: None Critical: None Observations: The assessment was conducted over a period of four weeks, with a one-week hiatus in between. Conclusion: The audit identified two minor issues and one moderate
// 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): zNS and zAuction systems have potential security issues (19 April 2021 to 21 May 2021). 2.b Fix (one line with code reference): Walkthrough session for the systems in scope to understand the fundamental design decisions of the system and initial security findings were shared with the client. Moderate: 3.a Problem (one line with code reference): zBanc code revision was updated half-way into the week on Wednesday (3d6943e82c167c1ae90fb437f9e3ed1a7a7a94c4). 3.b Fix (one line with code reference): Preliminary findings were shared during a sync-up discussing the changing codebase under review. Major: None Critical: None Observations: The assessment team focussed its work on the zNS and zAuction systems in the first week. Details on the scope for the components was set by the client and a walkthrough session 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) - Inadequate input validation in zAuction (line 545) 2.b Fix (one line with code reference) - Add input validation in zAuction (line 545) Observations - Code-style and quality varies a lot for the different repositories under review - Security activities and key milestones should be explicitly included in the software development lifecycle Conclusion - Security review readiness should be established ahead of any security activities - A dedicated role should be created to coordinate security on the team Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Unchecked return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395) 2.b Fix: Check return value in zNS (b05e503ea1ee87dbe62b1d58426aaa518068e395) Moderate: 3.a Problem: Unchecked return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72) 3.b Fix: Check return value in zAuction (50d3b6ce6d7ee00e7181d5b2a9a2eedcdd3fdb72) Major: None Critical: None Observations: The assessment was conducted over a period of four weeks, with a one-week hiatus in between. Conclusion: The audit identified two minor issues and one moderate
// SPDX-License-Identifier: AGPL-3.0-only /** * PermissionsForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; interface IContractManagerForMainnet { function permitted(bytes32 contractName) external view returns (address); } /** * @title PermissionsForMainnet - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ contract PermissionsForMainnet is AccessControlUpgradeSafe { // address of ContractManager address public lockAndDataAddress_; /** * @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( IContractManagerForMainnet( lockAndDataAddress_ ).permitted(keccak256(abi.encodePacked(contractName))) == msg.sender || getOwner() == msg.sender, "Message sender is invalid" ); _; } modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev initialize - sets current address of ContractManager * @param newContractsAddress - current address of ContractManager */ function initialize(address newContractsAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); lockAndDataAddress_ = newContractsAddress; } function getLockAndDataAddress() public view returns ( address a ) { return lockAndDataAddress_; } /** * @dev Returns owner address. */ function getOwner() public view returns ( address ow ) { return getRoleMember(DEFAULT_ADMIN_ROLE, 0); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; interface ContractReceiverForMainnet { function postMessage( address sender, string calldata schainID, address to, uint256 amount, bytes calldata data ) external; } interface IContractManagerSkaleManager { function contracts(bytes32 contractID) external view returns(address); } interface ISchains { function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); } /** * @title Message Proxy for Mainnet * @dev Runs on Mainnet, contains functions to manage the incoming messages from * `dstChainID` and outgoing messages to `srcChainID`. Every SKALE chain with * IMA is therefore connected to MessageProxyForMainnet. * * Messages from SKALE chains are signed using BLS threshold signatures from the * nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet * messages do not need to be signed. */ contract MessageProxyForMainnet is Initializable { // 16 Agents // Synchronize time with time.nist.gov // Every agent checks if it is his time slot // Time slots are in increments of 10 seconds // At the start of his slot each agent: // For each connected schain: // Read incoming counter on the dst chain // Read outgoing counter on the src chain // Calculate the difference outgoing - incoming // Call postIncomingMessages function passing (un)signed message array // ID of this schain, Chain 0 represents ETH mainnet, struct OutgoingMessageData { string dstChain; bytes32 dstChainHash; uint256 msgCounter; address srcContract; address dstContract; address to; uint256 amount; bytes data; uint256 length; } struct ConnectedChainInfo { // message counters start with 0 uint256 incomingMessageCounter; uint256 outgoingMessageCounter; bool inited; } struct Message { address sender; address destinationContract; address to; uint256 amount; bytes data; } struct Signature { uint256[2] blsSignature; uint256 hashA; uint256 hashB; uint256 counter; } string public chainID; // Owner of this chain. For mainnet, the owner is SkaleManager address public owner; address public contractManagerSkaleManager; uint256 private _idxHead; uint256 private _idxTail; mapping(address => bool) public authorizedCaller; mapping(bytes32 => ConnectedChainInfo) public connectedChains; mapping ( uint256 => OutgoingMessageData ) private _outgoingMessageData; /** * @dev Emitted for every outgoing message to `dstChain`. */ event OutgoingMessage( string dstChain, bytes32 indexed dstChainHash, uint256 indexed msgCounter, address indexed srcContract, address dstContract, address to, uint256 amount, bytes data, uint256 length ); event PostMessageError( uint256 indexed msgCounter, bytes32 indexed srcChainHash, address sender, string fromSchainID, address to, uint256 amount, bytes data, string message ); /** * @dev Adds an authorized caller. * * Requirements: * * - `msg.sender` must be an owner. */ function addAuthorizedCaller(address caller) external { require(msg.sender == owner, "Sender is not an owner"); authorizedCaller[caller] = true; } /** * @dev Removes an authorized caller. * * Requirements: * * - `msg.sender` must be an owner. */ function removeAuthorizedCaller(address caller) external { require(msg.sender == owner, "Sender is not an owner"); authorizedCaller[caller] = false; } /** * @dev Adds a `newChainID`. * * Requirements: * * - `msg.sender` must be SKALE Node address. * - `newChainID` must not be "Mainnet". * - `newChainID` must not already be added. */ function addConnectedChain( string calldata newChainID ) external { require(authorizedCaller[msg.sender], "Not authorized caller"); require( keccak256(abi.encodePacked(newChainID)) != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name is incorrect. Inside in MessageProxy"); require( !connectedChains[keccak256(abi.encodePacked(newChainID))].inited, "Chain is already connected" ); connectedChains[ keccak256(abi.encodePacked(newChainID)) ] = ConnectedChainInfo({ incomingMessageCounter: 0, outgoingMessageCounter: 0, inited: true }); } /** * @dev Removes connected chain from this contract. * * Requirements: * * - `msg.sender` must be owner. * - `newChainID` must be initialized. */ function removeConnectedChain(string calldata newChainID) external { require(authorizedCaller[msg.sender], "Not authorized caller"); require( connectedChains[keccak256(abi.encodePacked(newChainID))].inited, "Chain is not initialized" ); delete connectedChains[keccak256(abi.encodePacked(newChainID))]; } /** * @dev Posts message from this contract to `dstChainID` MessageProxy contract. * This is called by a smart contract to make a cross-chain call. * * Requirements: * * - `dstChainID` must be initialized. */ function postOutgoingMessage( string calldata dstChainID, address dstContract, uint256 amount, address to, bytes calldata data ) external { bytes32 dstChainHash = keccak256(abi.encodePacked(dstChainID)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); connectedChains[dstChainHash].outgoingMessageCounter++; _pushOutgoingMessageData( OutgoingMessageData( dstChainID, dstChainHash, connectedChains[dstChainHash].outgoingMessageCounter - 1, msg.sender, dstContract, to, amount, data, data.length ) ); } /** * @dev Posts incoming message from `srcChainID`. * * Requirements: * * - `msg.sender` must be authorized caller. * - `srcChainID` must be initialized. * - `startingCounter` must be equal to the chain's incoming message counter. * - If destination chain is Mainnet, message signature must be valid. */ function postIncomingMessages( string calldata srcChainID, uint256 startingCounter, Message[] calldata messages, Signature calldata sign, uint256 idxLastToPopNotIncluding ) external { bytes32 srcChainHash = keccak256(abi.encodePacked(srcChainID)); require(authorizedCaller[msg.sender], "Not authorized caller"); require(connectedChains[srcChainHash].inited, "Chain is not initialized"); require( startingCounter == connectedChains[srcChainHash].incomingMessageCounter, "Starning counter is not qual to incomin message counter"); if (keccak256(abi.encodePacked(chainID)) == keccak256(abi.encodePacked("Mainnet"))) { _convertAndVerifyMessages(srcChainID, messages, sign); } for (uint256 i = 0; i < messages.length; i++) { try ContractReceiverForMainnet(messages[i].destinationContract).postMessage( messages[i].sender, srcChainID, messages[i].to, messages[i].amount, messages[i].data ) { ++startingCounter; } catch Error(string memory reason) { emit PostMessageError( ++startingCounter, srcChainHash, messages[i].sender, srcChainID, messages[i].to, messages[i].amount, messages[i].data, reason ); } } connectedChains[keccak256(abi.encodePacked(srcChainID))].incomingMessageCounter += uint256(messages.length); _popOutgoingMessageData(idxLastToPopNotIncluding); } /** * @dev Increments incoming message counter. * * Note: Test function. TODO: remove in production. * * Requirements: * * - `msg.sender` must be owner. */ function moveIncomingCounter(string calldata schainName) external { require(msg.sender == owner, "Sender is not an owner"); connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter++; } /** * @dev Sets the incoming and outgoing message counters to zero. * * Note: Test function. TODO: remove in production. * * Requirements: * * - `msg.sender` must be owner. */ function setCountersToZero(string calldata schainName) external { require(msg.sender == owner, "Sender is not an owner"); connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter = 0; connectedChains[keccak256(abi.encodePacked(schainName))].outgoingMessageCounter = 0; } /** * @dev Checks whether chain is currently connected. * * Note: Mainnet chain does not have a public key, and is implicitly * connected to MessageProxy. * * Requirements: * * - `someChainID` must not be Mainnet. */ function isConnectedChain( string calldata someChainID ) external view returns (bool) { //require(msg.sender == owner); // todo: tmp!!!!! require( keccak256(abi.encodePacked(someChainID)) != keccak256(abi.encodePacked("Mainnet")), "Schain id can not be equal Mainnet"); // main net does not have a public key and is implicitly connected if ( ! connectedChains[keccak256(abi.encodePacked(someChainID))].inited ) { return false; } return true; } function getOutgoingMessagesCounter(string calldata dstChainID) external view returns (uint256) { bytes32 dstChainHash = keccak256(abi.encodePacked(dstChainID)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); return connectedChains[dstChainHash].outgoingMessageCounter; } function getIncomingMessagesCounter(string calldata srcChainID) external view returns (uint256) { bytes32 srcChainHash = keccak256(abi.encodePacked(srcChainID)); require(connectedChains[srcChainHash].inited, "Source chain is not initialized"); return connectedChains[srcChainHash].incomingMessageCounter; } /// Create a new message proxy function initialize(string memory newChainID, address newContractManager) public initializer { owner = msg.sender; authorizedCaller[msg.sender] = true; chainID = newChainID; contractManagerSkaleManager = newContractManager; } /** * @dev Checks whether outgoing message is valid. */ function verifyOutgoingMessageData( uint256 idxMessage, address sender, address destinationContract, address to, uint256 amount ) public view returns (bool isValidMessage) { isValidMessage = false; OutgoingMessageData memory d = _outgoingMessageData[idxMessage]; if ( d.dstContract == destinationContract && d.srcContract == sender && d.to == to && d.amount == amount ) isValidMessage = true; } function _convertAndVerifyMessages( string calldata srcChainID, Message[] calldata messages, Signature calldata sign ) internal { Message[] memory input = new Message[](messages.length); for (uint256 i = 0; i < messages.length; i++) { input[i].sender = messages[i].sender; input[i].destinationContract = messages[i].destinationContract; input[i].to = messages[i].to; input[i].amount = messages[i].amount; input[i].data = messages[i].data; } require( _verifyMessageSignature( sign.blsSignature, _hashedArray(input), sign.counter, sign.hashA, sign.hashB, srcChainID ), "Signature is not verified" ); } /** * @dev Checks whether message BLS signature is valid. */ function _verifyMessageSignature( uint256[2] memory blsSignature, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string memory srcChainID ) private view returns (bool) { address skaleSchains = IContractManagerSkaleManager(contractManagerSkaleManager).contracts( keccak256(abi.encodePacked("Schains")) ); return ISchains(skaleSchains).verifySchainSignature( blsSignature[0], blsSignature[1], hash, counter, hashA, hashB, srcChainID ); } /** * @dev Returns hash of message array. */ function _hashedArray(Message[] memory messages) private pure returns (bytes32) { bytes memory data; for (uint256 i = 0; i < messages.length; i++) { data = abi.encodePacked( data, bytes32(bytes20(messages[i].sender)), bytes32(bytes20(messages[i].destinationContract)), bytes32(bytes20(messages[i].to)), messages[i].amount, messages[i].data ); } return keccak256(data); } /** * @dev Push outgoing message into outgoingMessageData array. * * Emits an {OutgoingMessage} event. */ function _pushOutgoingMessageData( OutgoingMessageData memory d ) private { emit OutgoingMessage( d.dstChain, d.dstChainHash, d.msgCounter, d.srcContract, d.dstContract, d.to, d.amount, d.data, d.length ); _outgoingMessageData[_idxTail] = d; ++_idxTail; } /** * @dev Pop outgoing message from outgoingMessageData array. */ function _popOutgoingMessageData( uint256 idxLastToPopNotIncluding ) private returns ( uint256 cntDeleted ) { cntDeleted = 0; for ( uint256 i = _idxHead; i < idxLastToPopNotIncluding; ++ i ) { if ( i >= _idxTail ) break; delete _outgoingMessageData[i]; ++ cntDeleted; } if (cntDeleted > 0) _idxHead += cntDeleted; } } // SPDX-License-Identifier: AGPL-3.0-only /** * ERC721ModuleForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Metadata.sol"; interface ILockAndDataERC721M { function erc721Tokens(uint256 index) external returns (address); function erc721Mapper(address contractERC721) external returns (uint256); function addERC721Token(address contractERC721) external returns (uint256); function sendERC721(address contractHere, address to, uint256 token) external returns (bool); } /** * @title ERC721 Module For Mainnet * @dev Runs on Mainnet, and manages receiving and sending of ERC721 token contracts * and encoding contractPosition in LockAndDataForMainnetERC721. */ contract ERC721ModuleForMainnet is PermissionsForMainnet { /** * @dev Emitted when token is mapped in LockAndDataForMainnetERC721. */ event ERC721TokenAdded(address indexed tokenHere, uint256 contractPosition); /** * @dev Allows DepositBox to receive ERC721 tokens. * * Emits an {ERC721TokenAdded} event. */ function receiveERC721( address contractHere, address to, uint256 tokenId, bool isRAW ) external allow("DepositBox") returns (bytes memory data) { address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); if (!isRAW) { uint256 contractPosition = ILockAndDataERC721M(lockAndDataERC721).erc721Mapper(contractHere); if (contractPosition == 0) { contractPosition = ILockAndDataERC721M(lockAndDataERC721).addERC721Token(contractHere); emit ERC721TokenAdded(contractHere, contractPosition); } data = _encodeData( contractHere, contractPosition, to, tokenId); return data; } else { data = _encodeRawData(to, tokenId); return data; } } /** * @dev Allows DepositBox to send ERC721 tokens. */ function sendERC721(address to, bytes calldata data) external allow("DepositBox") returns (bool) { address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); uint256 contractPosition; address contractAddress; address receiver; uint256 tokenId; if (to == address(0)) { (contractPosition, receiver, tokenId) = _fallbackDataParser(data); contractAddress = ILockAndDataERC721M(lockAndDataERC721).erc721Tokens(contractPosition); } else { (receiver, tokenId) = _fallbackRawDataParser(data); contractAddress = to; } return ILockAndDataERC721M(lockAndDataERC721).sendERC721(contractAddress, receiver, tokenId); } /** * @dev Returns the receiver address of the ERC20 token. */ function getReceiver(address to, bytes calldata data) external pure returns (address receiver) { uint256 contractPosition; uint256 amount; if (to == address(0)) { (contractPosition, receiver, amount) = _fallbackDataParser(data); } else { (receiver, amount) = _fallbackRawDataParser(data); } } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); } /** * @dev Returns encoded creation data for ERC721 token. */ function _encodeData( address contractHere, uint256 contractPosition, address to, uint256 tokenId ) private view returns (bytes memory data) { string memory name = IERC721Metadata(contractHere).name(); string memory symbol = IERC721Metadata(contractHere).symbol(); data = abi.encodePacked( bytes1(uint8(5)), bytes32(contractPosition), bytes32(bytes20(to)), bytes32(tokenId), bytes(name).length, name, bytes(symbol).length, symbol ); } /** * @dev Returns encoded regular data. */ function _encodeRawData(address to, uint256 tokenId) private pure returns (bytes memory data) { data = abi.encodePacked( bytes1(uint8(21)), bytes32(bytes20(to)), bytes32(tokenId) ); } /** * @dev Returns fallback data. */ function _fallbackDataParser(bytes memory data) private pure returns (uint256, address payable, uint256) { bytes32 contractIndex; bytes32 to; bytes32 token; // solhint-disable-next-line no-inline-assembly assembly { contractIndex := mload(add(data, 33)) to := mload(add(data, 65)) token := mload(add(data, 97)) } return ( uint256(contractIndex), address(bytes20(to)), uint256(token) ); } /** * @dev Returns fallback raw data. */ function _fallbackRawDataParser(bytes memory data) private pure returns (address payable, uint256) { bytes32 to; bytes32 token; // solhint-disable-next-line no-inline-assembly assembly { to := mload(add(data, 33)) token := mload(add(data, 65)) } return (address(bytes20(to)), uint256(token)); } } // SPDX-License-Identifier: AGPL-3.0-only /** * ERC20ModuleForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; interface ILockAndDataERC20M { function erc20Tokens(uint256 index) external returns (address); function erc20Mapper(address contractERC20) external returns (uint256); function addERC20Token(address contractERC20) external returns (uint256); function sendERC20(address contractHere, address to, uint256 amount) external returns (bool); } /** * @title ERC20 Module For Mainnet * @dev Runs on Mainnet, and manages receiving and sending of ERC20 token contracts * and encoding contractPosition in LockAndDataForMainnetERC20. */ contract ERC20ModuleForMainnet is PermissionsForMainnet { /** * @dev Emitted when token is mapped in LockAndDataForMainnetERC20. */ event ERC20TokenAdded(address indexed tokenHere, uint256 contractPosition); /** * @dev Emitted when token is received by DepositBox and is ready to be cloned * or transferred on SKALE chain. */ event ERC20TokenReady(address indexed tokenHere, uint256 contractPosition, uint256 amount); /** * @dev Allows DepositBox to receive ERC20 tokens. * * Emits an {ERC20TokenAdded} event on token mapping in LockAndDataForMainnetERC20. * Emits an {ERC20TokenReady} event. * * Requirements: * * - Amount must be less than or equal to the total supply of the ERC20 contract. */ function receiveERC20( address contractHere, address to, uint256 amount, bool isRAW ) external allow("DepositBox") returns (bytes memory data) { address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); uint256 totalSupply = ERC20UpgradeSafe(contractHere).totalSupply(); require(amount <= totalSupply, "Amount is incorrect"); uint256 contractPosition = ILockAndDataERC20M(lockAndDataERC20).erc20Mapper(contractHere); if (contractPosition == 0) { contractPosition = ILockAndDataERC20M(lockAndDataERC20).addERC20Token(contractHere); emit ERC20TokenAdded(contractHere, contractPosition); } if (!isRAW) { data = _encodeCreationData( contractHere, contractPosition, to, amount ); } else { data = _encodeRegularData(to, contractPosition, amount); } emit ERC20TokenReady(contractHere, contractPosition, amount); return data; } /** * @dev Allows DepositBox to send ERC20 tokens. */ function sendERC20(address to, bytes calldata data) external allow("DepositBox") returns (bool) { address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); uint256 contractPosition; address contractAddress; address receiver; uint256 amount; (contractPosition, receiver, amount) = _fallbackDataParser(data); contractAddress = ILockAndDataERC20M(lockAndDataERC20).erc20Tokens(contractPosition); if (to != address(0)) { if (contractAddress == address(0)) { contractAddress = to; } } bool variable = ILockAndDataERC20M(lockAndDataERC20).sendERC20(contractAddress, receiver, amount); return variable; } /** * @dev Returns the receiver address of the ERC20 token. */ function getReceiver(bytes calldata data) external view returns (address receiver) { uint256 contractPosition; uint256 amount; (contractPosition, receiver, amount) = _fallbackDataParser(data); } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); } /** * @dev Returns encoded creation data for ERC20 token. */ function _encodeCreationData( address contractHere, uint256 contractPosition, address to, uint256 amount ) private view returns (bytes memory data) { string memory name = ERC20UpgradeSafe(contractHere).name(); uint8 decimals = ERC20UpgradeSafe(contractHere).decimals(); string memory symbol = ERC20UpgradeSafe(contractHere).symbol(); uint256 totalSupply = ERC20UpgradeSafe(contractHere).totalSupply(); data = abi.encodePacked( bytes1(uint8(3)), bytes32(contractPosition), bytes32(bytes20(to)), bytes32(amount), bytes(name).length, name, bytes(symbol).length, symbol, decimals, totalSupply ); } /** * @dev Returns encoded regular data. */ function _encodeRegularData( address to, uint256 contractPosition, uint256 amount ) private pure returns (bytes memory data) { data = abi.encodePacked( bytes1(uint8(19)), bytes32(contractPosition), bytes32(bytes20(to)), bytes32(amount) ); } /** * @dev Returns fallback data. */ function _fallbackDataParser(bytes memory data) private pure returns (uint256, address payable, uint256) { bytes32 contractIndex; bytes32 to; bytes32 token; // solhint-disable-next-line no-inline-assembly assembly { contractIndex := mload(add(data, 33)) to := mload(add(data, 65)) token := mload(add(data, 97)) } return ( uint256(contractIndex), address(bytes20(to)), uint256(token) ); } } // SPDX-License-Identifier: AGPL-3.0-only /** * LockAndDataForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./OwnableForMainnet.sol"; /** * @title Lock and Data For Mainnet * @dev Runs on Mainnet, holds deposited ETH, and contains mappings and * balances of ETH tokens received through DepositBox. */ contract LockAndDataForMainnet is OwnableForMainnet { mapping(bytes32 => address) public permitted; mapping(bytes32 => address) public tokenManagerAddresses; mapping(address => uint256) public approveTransfers; mapping(address => bool) public authorizedCaller; modifier allow(string memory contractName) { require( permitted[keccak256(abi.encodePacked(contractName))] == msg.sender || getOwner() == msg.sender, "Not allowed" ); _; } /** * @dev Emitted when DepositBox receives ETH. */ event ETHReceived(address from, uint256 amount); /** * @dev Emitted upon failure. */ event Error( address to, uint256 amount, string message ); /** * @dev Allows DepositBox to receive ETH. * * Emits a {ETHReceived} event. */ function receiveEth(address from) external allow("DepositBox") payable { emit ETHReceived(from, msg.value); } /** * @dev Allows Owner to set a new contract address. * * Requirements: * * - New contract address must be non-zero. * - New contract address must not already be added. * - Contract must contain code. */ function setContract(string calldata contractName, address newContract) external virtual onlyOwner { require(newContract != address(0), "New address is equal zero"); bytes32 contractId = keccak256(abi.encodePacked(contractName)); require(permitted[contractId] != newContract, "Contract is already added"); uint256 length; // solhint-disable-next-line no-inline-assembly assembly { length := extcodesize(newContract) } require(length > 0, "Given contract address does not contain code"); permitted[contractId] = newContract; } /** * @dev Adds a SKALE chain and its TokenManager address to * LockAndDataForMainnet. * * Requirements: * * - `msg.sender` must be authorized caller. * - SKALE chain must not already be added. * - TokenManager address must be non-zero. */ function addSchain(string calldata schainID, address tokenManagerAddress) external { require(authorizedCaller[msg.sender], "Not authorized caller"); bytes32 schainHash = keccak256(abi.encodePacked(schainID)); require(tokenManagerAddresses[schainHash] == address(0), "SKALE chain is already set"); require(tokenManagerAddress != address(0), "Incorrect Token Manager address"); tokenManagerAddresses[schainHash] = tokenManagerAddress; } /** * @dev Allows Owner to remove a SKALE chain from contract. * * Requirements: * * - SKALE chain must already be set. */ function removeSchain(string calldata schainID) external onlyOwner { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); require(tokenManagerAddresses[schainHash] != address(0), "SKALE chain is not set"); delete tokenManagerAddresses[schainHash]; } /** * @dev Allows Owner to add an authorized caller. */ function addAuthorizedCaller(address caller) external onlyOwner { authorizedCaller[caller] = true; } /** * @dev Allows Owner to remove an authorized caller. */ function removeAuthorizedCaller(address caller) external onlyOwner { authorizedCaller[caller] = false; } /** * @dev Allows DepositBox to approve transfer. */ function approveTransfer(address to, uint256 amount) external allow("DepositBox") { // SWC-Integer Overflow and Underflow: L145 approveTransfers[to] += amount; } /** * @dev Transfers a user's ETH. * * Requirements: * * - LockAndDataForMainnet must have sufficient ETH. * - User must be approved for ETH transfer. */ function getMyEth() external { require( address(this).balance >= approveTransfers[msg.sender], "Not enough ETH. in `LockAndDataForMainnet.getMyEth`" ); require(approveTransfers[msg.sender] > 0, "User has insufficient ETH"); uint256 amount = approveTransfers[msg.sender]; approveTransfers[msg.sender] = 0; msg.sender.transfer(amount); } /** * @dev Allows DepositBox to send ETH. * * Emits an {Error} upon insufficient ETH in LockAndDataForMainnet. */ function sendEth(address payable to, uint256 amount) external allow("DepositBox") returns (bool) { if (address(this).balance >= amount) { to.transfer(amount); return true; } } /** * @dev Returns the contract address for a given contractName. */ function getContract(string memory contractName) external view returns (address) { return permitted[keccak256(abi.encodePacked(contractName))]; } /** * @dev Checks whether LockAndDataforMainnet is connected to a SKALE chain. */ function hasSchain( string calldata schainID ) external view returns (bool) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); if ( tokenManagerAddresses[schainHash] == address(0) ) { return false; } return true; } function initialize() public override initializer { OwnableForMainnet.initialize(); authorizedCaller[msg.sender] = true; } } // SPDX-License-Identifier: AGPL-3.0-only /** * OwnableForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /** * @title OwnableForMainnet * @dev The OwnableForMainnet contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableForMainnet is Initializable { /** * @dev _ownerAddress is only used after transferOwnership(). * By default, value of "skaleConfig.contractSettings.IMA._ownerAddress" config variable is used */ address private _ownerAddress; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == getOwner(), "Only owner can execute this method"); _; } /** * @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 payable newOwner) external onlyOwner { require(newOwner != address(0), "New owner has to be set"); setOwner(newOwner); } /** * @dev initialize sets the original `owner` of the contract to the sender * account. */ function initialize() public virtual initializer { _ownerAddress = msg.sender; } /** * @dev Sets new owner address. */ // SWC-Function Default Visibility: L70 function setOwner( address newAddressOwner ) public { _ownerAddress = newAddressOwner; } /** * @dev Returns owner address. */ function getOwner() public view returns ( address ow ) { return _ownerAddress; } } // SPDX-License-Identifier: AGPL-3.0-only /** * DepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "./interfaces/IMessageProxy.sol"; import "./interfaces/IERC20Module.sol"; import "./interfaces/IERC721Module.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface ILockAndDataDB { function setContract(string calldata contractName, address newContract) external; function tokenManagerAddresses(bytes32 schainHash) external returns (address); function sendEth(address to, uint256 amount) external returns (bool); function approveTransfer(address to, uint256 amount) external; function addSchain(string calldata schainID, address tokenManagerAddress) external; function receiveEth(address from) external payable; } // This contract runs on the main net and accepts deposits contract DepositBox is PermissionsForMainnet { enum TransactionOperation { transferETH, transferERC20, transferERC721, rawTransferERC20, rawTransferERC721 } uint256 public constant GAS_AMOUNT_POST_MESSAGE = 200000; uint256 public constant AVERAGE_TX_PRICE = 10000000000; event MoneyReceivedMessage( address sender, string fromSchainID, address to, uint256 amount, bytes data ); event Error( address to, uint256 amount, string message ); modifier rightTransaction(string memory schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash); require(schainHash != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name is incorrect"); require(tokenManagerAddress != address(0), "Unconnected chain"); _; } modifier requireGasPayment() { require(msg.value >= GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE, "Gas was not paid"); _; ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } fallback() external payable { revert("Not allowed. in DepositBox"); } function depositWithoutData(string calldata schainID, address to) external payable { deposit(schainID, to); } function depositERC20( string calldata schainID, address contractHere, address to, uint256 amount ) external payable rightTransaction(schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash); address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); address erc20Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC20Module")) ); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); require( IERC20(contractHere).allowance( msg.sender, address(this) ) >= amount, "Not allowed ERC20 Token" ); require( IERC20(contractHere).transferFrom( msg.sender, lockAndDataERC20, amount ), "Could not transfer ERC20 Token" ); bytes memory data = IERC20Module(erc20Module).receiveERC20( contractHere, to, amount, false); IMessageProxy(proxyAddress).postOutgoingMessage( schainID, tokenManagerAddress, msg.value, address(0), data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function rawDepositERC20( string calldata schainID, address contractHere, address contractThere, address to, uint256 amount ) external payable rightTransaction(schainID) { address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses( keccak256(abi.encodePacked(schainID)) ); address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); address erc20Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC20Module")) ); require( IERC20(contractHere).allowance( msg.sender, address(this) ) >= amount, "Not allowed ERC20 Token" ); require( IERC20(contractHere).transferFrom( msg.sender, lockAndDataERC20, amount ), "Could not transfer ERC20 Token" ); bytes memory data = IERC20Module(erc20Module).receiveERC20(contractHere, to, amount, true); IMessageProxy(IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) )).postOutgoingMessage( schainID, tokenManagerAddress, msg.value, contractThere, data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function depositERC721( string calldata schainID, address contractHere, address to, uint256 tokenId) external payable rightTransaction(schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); address erc721Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC721Module")) ); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); require(IERC721(contractHere).ownerOf(tokenId) == address(this), "Not allowed ERC721 Token"); IERC721(contractHere).transferFrom(address(this), lockAndDataERC721, tokenId); require(IERC721(contractHere).ownerOf(tokenId) == lockAndDataERC721, "Did not transfer ERC721 token"); bytes memory data = IERC721Module(erc721Module).receiveERC721( contractHere, to, tokenId, false); IMessageProxy(proxyAddress).postOutgoingMessage( schainID, ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash), msg.value, address(0), data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function rawDepositERC721( string calldata schainID, address contractHere, address contractThere, address to, uint256 tokenId ) external payable rightTransaction(schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); address erc721Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC721Module")) ); require(IERC721(contractHere).ownerOf(tokenId) == address(this), "Not allowed ERC721 Token"); IERC721(contractHere).transferFrom(address(this), lockAndDataERC721, tokenId); require(IERC721(contractHere).ownerOf(tokenId) == lockAndDataERC721, "Did not transfer ERC721 token"); bytes memory data = IERC721Module(erc721Module).receiveERC721( contractHere, to, tokenId, true); IMessageProxy(IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) )).postOutgoingMessage( schainID, ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash), msg.value, contractThere, data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function postMessage( address sender, string calldata fromSchainID, address payable to, uint256 amount, bytes calldata data ) external { require(data.length != 0, "Invalid data"); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); require(msg.sender == proxyAddress, "Incorrect sender"); bytes32 schainHash = keccak256(abi.encodePacked(fromSchainID)); require( schainHash != keccak256(abi.encodePacked("Mainnet")) && sender == ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash), "Receiver chain is incorrect" ); require( amount <= address(lockAndDataAddress_).balance || amount >= GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE, "Not enough money to finish this transaction" ); require( ILockAndDataDB(lockAndDataAddress_).sendEth(getOwner(), GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE), "Could not send money to owner" ); _executePerOperation(to, amount, data); } /// Create a new deposit box function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); } function deposit(string memory schainID, address to) public payable { bytes memory empty = ""; deposit(schainID, to, empty); } function deposit(string memory schainID, address to, bytes memory data) public payable rightTransaction(schainID) requireGasPayment { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); bytes memory newData; newData = abi.encodePacked(bytes1(uint8(1)), data); IMessageProxy(proxyAddress).postOutgoingMessage( schainID, tokenManagerAddress, msg.value, to, newData ); } function _executePerOperation( address payable to, uint256 amount, bytes calldata data ) internal { TransactionOperation operation = _fallbackOperationTypeConvert(data); if (operation == TransactionOperation.transferETH) { if (amount > GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE) { ILockAndDataDB(lockAndDataAddress_).approveTransfer( to, amount - GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE ); } } else if ((operation == TransactionOperation.transferERC20 && to == address(0)) || (operation == TransactionOperation.rawTransferERC20 && to != address(0))) { address erc20Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC20Module")) ); require(IERC20Module(erc20Module).sendERC20(to, data), "Sending of ERC20 was failed"); address receiver = IERC20Module(erc20Module).getReceiver(data); if (amount > GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE) { ILockAndDataDB(lockAndDataAddress_).approveTransfer( receiver, amount - GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE ); } } else if ((operation == TransactionOperation.transferERC721 && to == address(0)) || (operation == TransactionOperation.rawTransferERC721 && to != address(0))) { address erc721Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC721Module")) ); require(IERC721Module(erc721Module).sendERC721(to, data), "Sending of ERC721 was failed"); address receiver = IERC721Module(erc721Module).getReceiver(to, data); if (amount > GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE) { ILockAndDataDB(lockAndDataAddress_).approveTransfer( receiver, amount - GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE ); } } } /** * @dev Convert first byte of data to Operation * 0x01 - transfer eth * 0x03 - transfer ERC20 token * 0x05 - transfer ERC721 token * 0x13 - transfer ERC20 token - raw mode * 0x15 - transfer ERC721 token - raw mode * @param data - received data * @return operation */ function _fallbackOperationTypeConvert(bytes memory data) private pure returns (TransactionOperation) { bytes1 operationType; // solhint-disable-next-line no-inline-assembly assembly { operationType := mload(add(data, 0x20)) } require( operationType == 0x01 || operationType == 0x03 || operationType == 0x05 || operationType == 0x13 || operationType == 0x15, "Operation type is not identified" ); if (operationType == 0x01) { return TransactionOperation.transferETH; } else if (operationType == 0x03) { return TransactionOperation.transferERC20; } else if (operationType == 0x05) { return TransactionOperation.transferERC721; } else if (operationType == 0x13) { return TransactionOperation.rawTransferERC20; } else if (operationType == 0x15) { return TransactionOperation.rawTransferERC721; } } }// SPDX-License-Identifier: AGPL-3.0-only /** * Migrations.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; contract Migrations { address public owner; uint256 public lastCompletedMigration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint256 completed) external restricted { lastCompletedMigration = completed; } function upgrade(address newAddress) external restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } }// SPDX-License-Identifier: AGPL-3.0-only /** * LockAndDataForMainnetERC20.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /** * @title Lock and Data For Mainnet ERC20 * @dev Runs on Mainnet, holds deposited ERC20s, and contains mappings and * balances of ERC20 tokens received through DepositBox. */ contract LockAndDataForMainnetERC20 is PermissionsForMainnet { mapping(uint256 => address) public erc20Tokens; mapping(address => uint256) public erc20Mapper; uint256 public newIndexERC20; /** * @dev Allows ERC20Module to send an ERC20 token from * LockAndDataForMainnetERC20. * * Requirements: * * - `amount` must be less than or equal to the balance * in LockAndDataForMainnetERC20. * - Transfer must be successful. */ function sendERC20(address contractHere, address to, uint256 amount) external allow("ERC20Module") returns (bool) { require(IERC20(contractHere).balanceOf(address(this)) >= amount, "Not enough money"); require(IERC20(contractHere).transfer(to, amount), "something went wrong with `transfer` in ERC20"); return true; } /** * @dev Allows ERC20Module to add an ERC20 token to LockAndDataForMainnetERC20. */ function addERC20Token(address addressERC20) external allow("ERC20Module") returns (uint256) { uint256 index = newIndexERC20; erc20Tokens[index] = addressERC20; erc20Mapper[addressERC20] = index; newIndexERC20++; return index; } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); newIndexERC20 = 1; } } // SPDX-License-Identifier: AGPL-3.0-only /** * LockAndDataForMainnetERC721.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; /** * @title Lock And Data For Mainnet ERC721 * @dev Runs on Mainnet, holds deposited ERC721s, and contains mappings and * balances of ERC721 tokens received through DepositBox. */ contract LockAndDataForMainnetERC721 is PermissionsForMainnet { mapping(uint256 => address) public erc721Tokens; mapping(address => uint256) public erc721Mapper; uint256 public newIndexERC721; /** * @dev Allows ERC721ModuleForMainnet to send an ERC721 token. * * Requirements: * * - If ERC721 is held by LockAndDataForMainnetERC721, token must * transferrable from the contract to the recipient address. */ function sendERC721(address contractHere, address to, uint256 tokenId) external allow("ERC721Module") returns (bool) { if (IERC721(contractHere).ownerOf(tokenId) == address(this)) { IERC721(contractHere).transferFrom(address(this), to, tokenId); require(IERC721(contractHere).ownerOf(tokenId) == to, "Did not transfer"); } return true; } /** * @dev Allows ERC721ModuleForMainnet to add an ERC721 token to * LockAndDataForMainnetERC721. */ function addERC721Token(address addressERC721) external allow("ERC721Module") returns (uint256) { uint256 index = newIndexERC721; erc721Tokens[index] = addressERC721; erc721Mapper[addressERC721] = index; newIndexERC721++; return index; } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); newIndexERC721 = 1; } }
February 3rd 2021— Quantstamp Verified Skale Proxy Contracts This security assessment was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type DeFi Auditors Jake Goh Si Yuan , Senior Security ResearcherJan Gorzny , Blockchain ResearcherKevin Feng , Blockchain ResearcherTimeline 2020-11-16 through 2021-01-26 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification Provided Documentation Documentation Quality High Test Quality Medium Source Code Repository Commit IMA/proxy 8ba7484 None ee72736 None 082b932 Total Issues 5 (4 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 2 (1 Resolved)Informational Risk Issues 2 (2 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 FindingsWe have performed a complete assessment of the codebase provided and discovered 5 issues of varying severities, amongst which there is 1 high, 2 low and 2 informational. We urge the Skale team to address these issues and consider our recommendations with which to go about fixing it. Overall, we have found the codebase to be of good quality with well named methods and inline documentation. That being said, there are some room for improvement with regards to documentation consistency. At the same time, it is important to note that we acknowledge that there exists a node.js agent that handles the communication between mainnet and the separate chains. As this audit was focused only on the smart contracts components, that part is out of scope of the audit and might be a source of centralization for attacks. ID Description Severity Status QSP- 1 Improper access control to a core method High Fixed QSP- 2 Integer Overflow / Underflow Low Fixed QSP- 3 Race Conditions / Front-Running Low Acknowledged QSP- 4 Schain ETH contract is supply limited Informational Fixed QSP- 5 Hardcoded addresses and associated methods with unknown results Informational Mitigated 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.13 • SlitherSteps taken to run the tools: 1. Installed the Slither tool:pip install slither-analyzer 2. Run Slither from the project directory:slither . FindingsQSP-1 Improper access control to a core method Severity: High Risk Fixed Status: , File(s) affected: OwnableForMainnet.sol OwnableForSchain.sol is intended to be a basic singular access control inheritable contract that is used by . The logic of this contract is very similar to a well known and ubiquitous implementation provided by OpenZeppelin, with a major difference in an inclusion of a method . Description:OwnableForMainnet LockAndDataForMainnet Ownable setOwner The method is used via to set the new . However, this method is set to visibility, which means that it can be executed by any arbitrary actor to any arbitrary value. This is extremely dangerous given the relative importance and power of the owner role. setOwnertransferOwnership _ownerAddress public Use OpenZeppelin's implementation instead, as it has already been done for many other contracts, instead of rolling a new owner-logic contract. Otherwise, ensure that is either set to or armed with some access control. Recommendation:setOwner internal QSP-2 Integer Overflow / Underflow Severity: Low Risk Fixed Status: , , File(s) affected: LockAndDataForMainnet.sol LockAndDataForSchain.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 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 { uint8num_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 } } We have discovered these instances in the codebase: 1. LockAndDataForMainnet.sol::L144approveTransfers[to] += amount; 2. LockAndDataForSchain.sol::L206ethCosts[to] += amount 3. MessageProxyForSchain.sol::L428_idxHead += cntDeleted 4. MessageProxyForSchain.sol::L416++ _idxTail; 5. MessageProxyForSchain.sol::L334connectedChains[keccak256(abi.encodePacked(srcChainID))].incomingMessageCounter += uint256(messages.length); 6. MessageProxyForSchain.sol::L340connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter++; 7. MessageProxyForSchain.sol::L252connectedChains[dstChainHash].outgoingMessageCounter++; 8. MessageProxyForMainnet.sol::L532_idxHead += cntDeleted 9. MessageProxyForMainnet.sol::L517++ _idxTail; 10. MessageProxyForMainnet.sol::L315 connectedChains[keccak256(abi.encodePacked(srcChainID))].incomingMessageCounter += uint256(messages.length); 11. MessageProxyForMainnet.sol::L330connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter++; 12. MessageProxyForMainnet.sol::L247 connectedChains[dstChainHash].outgoingMessageCounter++; Use SafeMath for all instances of arithmetic. Recommendation: QSP-3 Race Conditions / Front-Running Severity: Low Risk Acknowledged Status: File(s) affected: EthERC20.sol Related Issue(s): SWC-114 A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:In particular, this refers to the well known frontrunning attack on ERC20. approveImagine two friends — Alice and Bob. Exploit Scenario: 1. Alice decides to allow Bob to spend some of her funds, for example, 1000 tokens. She calls the approve function with the argument equal to 1000.2. Alice rethinks her previous decision and now she wants to allow Bob to spend only 300 tokens. She calls the approve function again with the argument value equal to300. 3. Bob notices the second transaction before it is actually mined. He quickly sends the transaction that calls the transferFrom function and spends 1000 tokens.4. Since Bob is smart, he sets very high fee for his transaction, so that miner will definitely want to include his transaction in the block. If Bob is as quick as he is generous,his transaction will be executed before the Alice’s one. 5. In that case, Bob has already spent 1000 Alice’s tokens. The number of Alice’s tokens that Bob can transfer is equal to zero. 6.Then the Alice’s second transaction ismined. That means, that the Bob’s allowance is set to 300. 7.Now Bob can spend 300 more tokens by calling the transferFrom function. As a result, Bob has spent 1300 tokens. Alice has lost 1000 tokens and one friend. Make this issue well known such that users who use the allowance feature would be aware of it in such transitions. One may also include some defensive programming by allowing changes to only go to 0 or from 0. Recommendation:QSP-4 Schain ETH contract is supply limited Severity:Informational Fixed Status: File(s) affected: EthERC20.sol The ETH contract on Schain that acts as an analogue token for the native ETH token on mainnet is limited by a variable that cannot be increased beyond an initially declared . However, given that the supply of ETH is not hard limited, it means that this contract would not be able to mint beyond that value. Description:_capacity 120 * (10 ** 6) * (10 ** 18) Have some methods to change . Recommendation: _capacity QSP-5 Hardcoded addresses and associated methods with unknown results Severity: Informational Mitigated Status: , , , , , File(s) affected: LockAndDataForSchain.sol MessageProxyForSchain.sol LockAndDataOwnable.sol OwnableForSchain.sol PermissionsForSchain.sol TokenManager.sol There are some hardcoded addresses within the predeployed section, used within some of the key methods of the some of the contracts. As we are not able to see the logic that is predeployed and its' exact effects, we will not be able to certify methods utilizing these logic: Description:1. In LockAndDataForSchain.sol, the method. _checkPermitted 2. In LockAndDataForSchain.sol, the method. getEthERC20Address 3. In LockAndDataOwnable.sol, the method. getOwner 4. In MessageProxyForSchain.sol, the method. getChainID 5. In MessageProxyForSchain.sol, the method. getOwner 6. In MessageProxyForSchain.sol, the method. checkIsAuthorizedCaller 7. In OwnableForSchain.sol, the method. getOwner 8. In PermissionsForSchain.sol, the method. getLockAndDataAddress 9. In TokenManager.sol, the method. getChainID 10. In TokenManager.sol, the method . getProxyForSchainAddress The reaudit commit has refactored the approach but the issue remains the same that any logic approaching address is opaque to the audit unless there is an independent way for the auditors to retrieve and check the data on . Update:0xC033b369416c9Ecd8e4A07AaFA8b06b4107419E2 0x00c033b369416c9ecd8e4a07aafa8b06b4107419e2 From the Skale team : "One note about QSP-5, the hard coded address 0xC033b369416c9Ecd8e4A07AaFA8b06b4107419E2 refers to the predeployed address for SkaleFeatures contract. Searching the repo for that address will show you the deployment scripts, that make SkaleFeatures accessible to the schain IMA system. I believe with this info, the issue is effectively resolved." Update:Due to the zeal and information provided by the Skale team, we have decided to upgrade the status from to . It will remain the recommendation of the Quantstamp team that users independently verify that the hardcoded address has the expected contract code. Update:Unresolved Mitigated Automated Analyses Slither All of the results were checked through and were flagged as false positives. The following are best practices recommendations that should be adhered to : getChainID() should be declared external: - MessageProxyForSchain.getChainID() (predeployed/MessageProxyForSchain.sol#349-357) setOwner(address) should be declared external: - MessageProxyForSchain.setOwner(address) (predeployed/MessageProxyForSchain.sol#369-371) verifyOutgoingMessageData(uint256,address,address,address,uint256) should be declared external: - MessageProxyForSchain.verifyOutgoingMessageData(uint256,address,address,address,uint256) (predeployed/MessageProxyForSchain.sol#386-401) initialize(string,address) should be declared external: - MessageProxyForMainnet.initialize(string,address) (MessageProxyForMainnet.sol#398-403) verifyOutgoingMessageData(uint256,address,address,address,uint256) should be declared external: - MessageProxyForMainnet.verifyOutgoingMessageData(uint256,address,address,address,uint256) (MessageProxyForMainnet.sol#408-423) mint(address,uint256) should be declared external: - ERC20OnChain.mint(address,uint256) (predeployed/TokenFactory.sol#60-64) getLockAndDataAddress() should be declared external: - PermissionsForMainnet.getLockAndDataAddress() (PermissionsForMainnet.sol#70-72) logMessage(string) should be declared external: - SkaleFeatures.logMessage(string) (predeployed/SkaleFeatures.sol#60-62) logDebug(string) should be declared external: - SkaleFeatures.logDebug(string) (predeployed/SkaleFeatures.sol#64-66) logTrace(string) should be declared external: - SkaleFeatures.logTrace(string) (predeployed/SkaleFeatures.sol#68-70) logWarning(string) should be declared external: - SkaleFeatures.logWarning(string) (predeployed/SkaleFeatures.sol#72-74) logError(string) should be declared external: - SkaleFeatures.logError(string) (predeployed/SkaleFeatures.sol#76-78) logFatal(string) should be declared external: - SkaleFeatures.logFatal(string) (predeployed/SkaleFeatures.sol#80-82) getConfigVariableUint256(string) should be declared external: - SkaleFeatures.getConfigVariableUint256(string) (predeployed/SkaleFeatures.sol#84-97) getConfigVariableAddress(string) should be declared external: - SkaleFeatures.getConfigVariableAddress(string) (predeployed/SkaleFeatures.sol#99-112) getConfigVariableString(string) should be declared external: - SkaleFeatures.getConfigVariableString(string) (predeployed/SkaleFeatures.sol#114-126) concatenateStrings(string,string) should be declared external: - SkaleFeatures.concatenateStrings(string,string) (predeployed/SkaleFeatures.sol#128-148) getConfigPermissionFlag(address,string) should be declared external: - SkaleFeatures.getConfigPermissionFlag(address,string) (predeployed/SkaleFeatures.sol#150-165) name() should be declared external: - EthERC20.name() (predeployed/EthERC20.sol#84-86) symbol() should be declared external: - EthERC20.symbol() (predeployed/EthERC20.sol#92-94) decimals() should be declared external: - EthERC20.decimals() (predeployed/EthERC20.sol#109-111) increaseAllowance(address,uint256) should be declared external: - EthERC20.increaseAllowance(address,uint256) (predeployed/EthERC20.sol#194-197) decreaseAllowance(address,uint256) should be declared external: - EthERC20.decreaseAllowance(address,uint256) (predeployed/EthERC20.sol#213-220) Code Documentation 1. [FIXED] In EthERC20.sol::L48 to be consistent with other type declarations,-> . uint uint2562. In LockAndDataForSchain.sol::L234should be . sendEth sendETH 3. In LockAndDataForSchain.sol::L242should be . receiveEth receiveETH 4.In LockAndDataForSchain.sol::L250should be . getEthERC20Address getETH_ERC20Address 5. [FIXED] In LockAndDataForSchain.sol::L260-> . name and adress are permitted name and address are permitted 6. In TokenManager.sol::[L528,L521]-> . addEthCost addETHCost 7. In TokenManager.sol::L119-> . addEthCostWithoutAddress addETHCostWithoutAddress 8. [FIXED] In MessageProxyForMainnet.sol::L215, the commentshould be . msg.sender must be owner. msg.sender must be SKALE Node address. 9. [FIXED] In MessageProxyForMainnet.sol::L365,and commented out code should be removed. todo10. [FIXED] In MessageProxyForMainnet.sol::L286 -> . qual equal11. [FIXED] In MessageProxyForMainnet.sol::L258should be . Starning counter is not equal to incomin message counterStarting counter is not equal to incoming message counter Adherence to Best Practices 1. [FIXED] In DepositBox.sol, thevalue is used multiple times, but the constants themselves are never used seperately. It would be optimal to precalculate the value. GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE2. [FIXED] In EthERC20.sol, the functionis not used. _setupDecimals 3. [FIXED] In MessageProxyForSchain.sol::L276-277 is redundant as L275 already ensures that it will never execute.4. [FIXED] In LockAndDataForSchainERC20.sol, for consistency,should emit an event when a new ERC20 Token address is added. addERC20Token 5. [FIXED] In LockAndDataForSchainERC721.sol, for consistency,should emit an event when a new ERC721 Token address is added. addERC721Token 6. [FIXED] In LockAndDataForSchainERC20.sol, input validation in function. addERC20Token, addressERC20 7. [FIXED] In LockAndDataForSchainERC721.sol, input validation in function. addERC721Token, addressERC721 8. [FIXED] In TokenFactory.sol, input validation in function. constructor, erc20Module 9. In TokenManger.sol, input validation in function. constructor, newProxyAddress 10. [FIXED] In TokenManager.sol, to ensure consistent execution across all other functions, ensure that for all input for functions and for , to validate against zero address. contractThere[rawExitToMainERC20, rawTransferToSchainERC20, rawExitToMainERC721, rawTransferToSchainERC721] to [exitToMain, transferToSchain]11. [FIXED] In LockAndDataForMainnetERC20.sol, input validation in functionand . sendERC20, contractHere addERC20Token, addressERC20 12. [FIXED] In LockAndDataForMainnetERC721.sol, input validation in function and . sendERC721, contractHere addERC721Token, addressERC721 13. In MessageProxyForMainnet.sol, input validation in function and . initialize, newContractManager postOutgoingMessage, to Test Results Test Suite Results We were able to run the tests successfully in both initial and reaudit stages. The following results corresponds to the reaudit stage Contract: DepositBox Your project has Truffle migrations, which have to be turn into a fixture to run your tests with Buidler tests for `deposit` function ✓ should rejected with `Unconnected chain` when invoke `deposit` (102ms) ✓ should rejected with `SKALE chain name is incorrect` when invoke `deposit` (66ms) ✓ should rejected with `Not enough money` when invoke `deposit` (148ms) ✓ should invoke `deposit` without mistakes (174ms) ✓ should revert `Not allowed. in DepositBox` (53ms) tests with `ERC20` tests for `depositERC20` function ✓ should rejected with `Not allowed ERC20 Token` (172ms) ✓ should invoke `depositERC20` without mistakes (394ms) ✓ should invoke `depositERC20` with some ETH without mistakes (379ms) tests for `rawDepositERC20` function ✓ should rejected with `Not allowed ERC20 Token` when invoke `rawDepositERC20` (167ms) ✓ should invoke `rawDepositERC20` without mistakes (348ms) ✓ should invoke `rawDepositERC20` with some ETH without mistakes (319ms) tests with `ERC721` tests for `depositERC721` function ✓ should rejected with `Not allowed ERC721 Token` (150ms) ✓ should invoke `depositERC721` without mistakes (291ms) tests for `rawDepositERC721` function ✓ should rejected with `Not allowed ERC721 Token` (146ms) ✓ should invoke `rawDepositERC721` without mistakes (281ms) tests for `postMessage` function ✓ should rejected with `Message sender is invalid` (57ms) ✓ should rejected with message `Receiver chain is incorrect` when schainID=`mainnet` (134ms) ✓ should rejected with message `Receiver chain is incorrect` when `sender != ILockAndDataDB(lockAndDataAddress).tokenManagerAddresses(schainHash)` (118ms) ✓ should rejected with message `Not enough money to finish this transaction` (134ms) ✓ should rejected with message `Invalid data` (186ms) ✓ should rejected with message `Could not send money to owner` (192ms) ✓ should transfer eth (212ms) ✓ should transfer ERC20 token (602ms) ✓ should transfer ERC20 for RAW mode token (854ms) ✓ should transfer ERC721 token (1042ms) ✓ should transfer RawERC721 token (606ms) Contract: ERC20ModuleForMainnet ✓ should invoke `receiveERC20` with `isRaw==true` (115ms) ✓ should invoke `receiveERC20` with `isRaw==false` (199ms) ✓ should return `true` when invoke `sendERC20` with `to0==address(0)` (597ms) ✓ should return `true` when invoke `sendERC20` with `to0==ethERC20.address` (285ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==ethERC20.address` (246ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (287ms) Contract: ERC20ModuleForSchain ✓ should invoke `receiveERC20` with `isRaw==true` (253ms) ✓ should rejected with `ERC20 contract does not exist on SKALE chain.` with `isRaw==false` (133ms) ✓ should invoke `receiveERC20` with `isRaw==false` (399ms) ✓ should return `true` when invoke `sendERC20` with `to0==address(0)` (572ms) ✓ should return send ERC20 token twice (521ms) ✓ should return `true` for `sendERC20` with `to0==address(0)` and `contractAddreess==address(0)` (442ms) ✓ should be rejected with incorrect Minter when invoke `sendERC20` with `to0==ethERC20.address` (593ms) ✓ should return true when invoke `sendERC20` with `to0==ethERC20.address` (668ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==ethERC20.address` (394ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (429ms) Contract: ERC721ModuleForMainnet ✓ should invoke `receiveERC721` with `isRaw==true` ✓ should invoke `receiveERC721` with `isRaw==false` (55ms) ✓ should return `true` when invoke `sendERC721` with `to0==address(0)` (459ms) ✓ should return `true` when invoke `sendERC721` with `to0==eRC721OnChain.address` (324ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==eRC721OnChain.address` (124ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (207ms) Contract: ERC721ModuleForSchain ✓ should invoke `receiveERC721` with `isRaw==true` (84ms)✓ should rejected with `ERC721 contract does not exist on SKALE chain` with `isRaw==false` (127ms) ✓ should invoke `receiveERC721` with `isRaw==false` (390ms) ✓ should return `true` for `sendERC721` with `to0==address(0)` and `contractAddreess==address(0)` (502ms) ✓ should return `true` when invoke `sendERC721` with `to0==address(0)` (706ms) ✓ should return `true` when invoke `sendERC721` with `to0==eRC721OnChain.address` (377ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==eRC721OnChain.address` (205ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (467ms) Contract: LockAndDataForMainnet ✓ should add wei to `lockAndDataForMainnet` (51ms) ✓ should check sendEth returned bool value (168ms) ✓ should work `sendEth` (112ms) ✓ should work `approveTransfer` (118ms) ✓ should work `getMyEth` (142ms) ✓ should rejected with `User has insufficient ETH` when invoke `getMyEth` (75ms) ✓ should rejected with `Not enough ETH. in `LockAndDataForMainnet.getMyEth`` when invoke `getMyEth` (131ms) ✓ should check contract without mistakes ✓ should rejected with `New address is equal zero` when invoke `getMyEth` (48ms) ✓ should rejected with `Contract is already added` when invoke `setContract` (47ms) ✓ should invoke addSchain without mistakes (91ms) ✓ should rejected with `SKALE chain is already set` when invoke `addSchain` (129ms) ✓ should rejected with `Incorrect Token Manager address` when invoke `addSchain` (64ms) ✓ should return true when invoke `hasSchain` (104ms) ✓ should return false when invoke `hasSchain` ✓ should invoke `removeSchain` without mistakes (216ms) ✓ should rejected with `SKALE chain is not set` when invoke `removeSchain` (160ms) Contract: LockAndDataForMainnetERC20 ✓ should rejected with `Not enough money` (71ms) ✓ should return `true` after invoke `sendERC20` (184ms) ✓ should return `token index` after invoke `addERC20Token` (369ms) Contract: LockAndDataForMainnetERC721 ✓ should NOT to send ERC721 to `to` when invoke `sendERC721` (145ms) ✓ should to send ERC721 to `to` when invoke `sendERC721` (240ms) ✓ should add ERC721 token when invoke `sendERC721` (135ms) Contract: LockAndDataForSchain ✓ should set EthERC20 address (109ms) ✓ should set contract (356ms) ✓ should add schain (217ms) ✓ should add deposit box (210ms) ✓ should add gas costs (126ms) ✓ should remove gas costs (184ms) ✓ should reduce gas costs (397ms) ✓ should send Eth (282ms) ✓ should receive Eth (235ms) ✓ should return true when invoke `hasSchain` (67ms) ✓ should return false when invoke `hasSchain` ✓ should return true when invoke `hasDepositBox` (63ms) ✓ should return false when invoke `hasDepositBox` ✓ should invoke `removeSchain` without mistakes (174ms) ✓ should rejected with `SKALE chain is not set` when invoke `removeSchain` (98ms) ✓ should work `addAuthorizedCaller` (66ms) ✓ should work `removeAuthorizedCaller` (62ms) ✓ should invoke `removeDepositBox` without mistakes (107ms) ✓ should rejected with `Deposit Box is not set` when invoke `removeDepositBox` (50ms) Contract: LockAndDataForSchain ✓ should set EthERC20 address (111ms) ✓ should set contract (439ms) ✓ should add schain (356ms) ✓ should add deposit box (252ms) ✓ should add gas costs (114ms) ✓ should reduce gas costs (409ms) ✓ should send Eth (246ms) ✓ should receive Eth (236ms) ✓ should return true when invoke `hasSchain` (72ms) ✓ should return false when invoke `hasSchain` ✓ should return true when invoke `hasDepositBox` (100ms) ✓ should return false when invoke `hasDepositBox` ✓ should invoke `removeSchain` without mistakes (115ms) ✓ should rejected with `SKALE chain is not set` when invoke `removeSchain` (130ms) ✓ should work `addAuthorizedCaller` (65ms) ✓ should work `removeAuthorizedCaller` (101ms) ✓ should invoke `removeDepositBox` without mistakes (120ms) ✓ should rejected with `Deposit Box is not set` when invoke `removeDepositBox` (59ms) Contract: LockAndDataForSchainERC20 ✓ should invoke `sendERC20` without mistakes (232ms) ✓ should rejected with `Amount not transfered` (69ms) ✓ should return `true` after invoke `receiveERC20` (218ms) ✓ should set `ERC20Tokens` and `ERC20Mapper` (106ms) Contract: LockAndDataForSchainERC721 ✓ should invoke `sendERC721` without mistakes (169ms) ✓ should rejected with `Token not transfered` after invoke `receiveERC721` (128ms) ✓ should return `true` after invoke `receiveERC721` (518ms) ✓ should set `ERC721Tokens` and `ERC721Mapper` (94ms) Contract: MessageProxy MessageProxyForMainnet for mainnet ✓ should detect registration state by `isConnectedChain` function (210ms) ✓ should add connected chain (135ms) ✓ should remove connected chain (258ms) ✓ should post outgoing message (191ms) ✓ should post incoming messages (272ms) ✓ should get outgoing messages counter (181ms) ✓ should get incoming messages counter (499ms) ✓ should move incoming counter (160ms) ✓ should get incoming messages counter (734ms) MessageProxyForSchain for schain ✓ should detect registration state by `isConnectedChain` function (87ms) ✓ should add connected chain (124ms) ✓ should remove connected chain (237ms) ✓ should post outgoing message (269ms) ✓ should post incoming messages (474ms) ✓ should get outgoing messages counter (169ms) ✓ should get incoming messages counter (508ms) Contract: TokenFactory ✓ should createERC20 (173ms) ✓ should createERC721 (203ms) Contract: ERC20OnChain ✓ should invoke `totalSupplyOnMainnet` ✓ should rejected with `Call does not go from ERC20Module` when invoke `setTotalSupplyOnMainnet` (53ms) ✓ should invoke `setTotalSupplyOnMainnet` (103ms) ✓ should invoke `_mint` as internal (63ms) ✓ should invoke `burn` (107ms) ✓ should invoke `burnFrom` (157ms) Contract: ERC721OnChain ✓ should invoke `mint` (71ms) ✓ should invoke `burn` (143ms) ✓ should reject with `ERC721Burnable: caller is not owner nor approved` when invoke `burn` (163ms) ✓ should invoke `setTokenURI` (106ms) Contract: TokenManager ✓ should send Eth to somebody on Mainnet, closed to Mainnet, called by schain (305ms) ✓ should transfer to somebody on schain Eth and some data (566ms) ✓ should add Eth cost (428ms) ✓ should remove Eth cost (502ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `exitToMainERC20` (376ms) ✓ should rejected with `Not enough gas sent` when invoke `exitToMainERC20` (394ms) ✓ should invoke `exitToMainERC20` without mistakes (794ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `rawExitToMainERC20` (364ms) ✓ should rejected with `Not enough gas sent` when invoke `rawExitToMainERC20` (400ms) ✓ should revert `Not allowed. in TokenManager` ✓ should invoke `rawExitToMainERC20` without mistakes (733ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `transferToSchainERC20` (611ms) ✓ should invoke `transferToSchainERC20` without mistakes (706ms) ✓ should invoke `rawTransferToSchainERC20` without mistakes (715ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `rawTransferToSchainERC20` (639ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `exitToMainERC721` (674ms) ✓ should rejected with `Not enough gas sent` when invoke `exitToMainERC721` (668ms) ✓ should invoke `exitToMainERC721` without mistakes (831ms) ✓ should invoke `rawExitToMainERC721` without mistakes (719ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `rawExitToMainERC721` (686ms) ✓ should rejected with `Not enough gas sent` when invoke `rawExitToMainERC721` (671ms) ✓ should invoke `transferToSchainERC721` without mistakes (773ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `transferToSchainERC721` (652ms) ✓ should invoke `rawTransferToSchainERC721` without mistakes (759ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `rawTransferToSchainERC721` (646ms) tests for `postMessage` function ✓ should rejected with `Not a sender` (67ms) ✓ should be Error event with message `Receiver chain is incorrect` when schainID=`mainnet` (285ms) ✓ should be Error event with message `Invalid data` (273ms) ✓ should transfer eth (447ms) ✓ should rejected with `Incorrect receiver` when `eth` transfer (439ms) ✓ should transfer ERC20 token (855ms) ✓ should transfer rawERC20 token (1099ms) ✓ should transfer ERC721 token (849ms) ✓ should transfer rawERC721 token (845ms) 186 passing (4m)Code Coverage Whilst there exists tests which provides code coverage up to a passable level, it is our strong recommendation that all code coverage be raised to the acceptable 100% level for all branches. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 94.35 71.08 92.86 92.65 DepositBox.sol 100 78.79 100 100 ERC20ModuleForMainnet.sol 97.3 70 100 97.37 105 ERC721ModuleForMainnet.sol 100 87.5 100 100 LockAndDataForMainnet.sol 82.86 65.38 91.67 81.58 … 91,93,96,97 LockAndDataForMainnetERC20.sol 100 62.5 100 100 LockAndDataForMainnetERC721.sol 100 62.5 100 100 MessageProxyForMainnet.sol 89.55 63.89 94.12 84.72 … 535,536,539 PermissionsForMainnet.sol 62.5 50 50 60 56,57,71,82 contracts/ interfaces/ 100 100 100 100 IContractManager.sol 100 100 100 100 IERC20Module.sol 100 100 100 100 IERC721Module.sol 100 100 100 100 IMessageProxy.sol 100 100 100 100 ISchainsInternal.sol 100 100 100 100 contracts/ predeployed/ 86.74 70.36 85.16 85.79 ERC20ModuleForSchain.sol 100 92.86 100 100 ERC721ModuleForSchain.sol 100 91.67 100 100 EthERC20.sol 92.16 57.14 90.48 92.16 191,192,210,215 LockAndDataForSchain.sol 82.72 80.77 96.43 83.53 … 349,350,352 LockAndDataForSchainERC20.sol 100 75 100 100 LockAndDataForSchainERC721.sol 100 66.67 100 100 MessageProxyForSchain.sol 63.29 54 63.64 61.63 … 456,457,460 OwnableForSchain.sol 66.67 62.5 83.33 72.73 66,77,86 PermissionsForSchain.sol 80 50 100 83.33 63 SkaleFeatures.sol 0 100 0 0 … 140,141,143 TokenFactory.sol 100 64.29 100 100 TokenManager.sol 98.36 71.57 100 98.32 558,573 All files 89.45 70.63 87.56 88.22 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 a581162e7409df3a9f5f72b4350eff7a1b4b0a46fdf155f6d5d832eaf82a514a ./IMA/proxy/contracts/PermissionsForMainnet.sol c30eb440430f7a314575fa9e199186f4beca58ee13d8ab1b63893ea559928088 ./IMA/proxy/contracts/MessageProxyForMainnet.sol 56463900f833cca487f4624a7bdd66f6dae6ad046fd60f429e146cf1844b1ae1 ./IMA/proxy/contracts/ERC721ModuleForMainnet.sol f958dc1a1a4915a88aa5af6a16c8195fe6de16487421ee625e073bd3aa5eaa0a ./IMA/proxy/contracts/ERC20ModuleForMainnet.sol f68cb3d41c8632cca0a232513a188b947effef88dafe64651be8834b53d3c5c7 ./IMA/proxy/contracts/LockAndDataForMainnet.sol c5af2b09f10e237cffd5f889849d63315531e900e6fd1d7a2f961c6c19ea6e06 ./IMA/proxy/contracts/DepositBox.sol e3ff22a8995e628d1e05e99edcfc9a1a2016a337e06f9a4c69196233abce6e45 ./IMA/proxy/contracts/LockAndDataForMainnetERC20.sol c4362ddc47d59c3cadb24fd1b02128ed57b86347c118355ac284a568a52326e0 ./IMA/proxy/contracts/LockAndDataForMainnetERC721.sol 595d60fef2ebc7636f86da980a0bc17b73a71aefc40d354583dbdc9e1dc85daf ./IMA/proxy/contracts/predeployed/LockAndDataForSchainERC721.sol f767a8c51b9ce643bad75038b1fb967315cc95300abb4123327c3498af457889 ./IMA/proxy/contracts/predeployed/EthERC20.sol dcd8e5cfcbedc8fbb57d89c5bafd73983c1b53af96bd8d9baac7999ad0ff0484 ./IMA/proxy/contracts/predeployed/ERC721ModuleForSchain.sol a9d832d8379d078e3243c6d8d1dc5bf1b9da2a9f3fb1415742d6cb501a5b4553 ./IMA/proxy/contracts/predeployed/SkaleFeatures.sol 24ed25959a167758b740280ce2c764842e1e4f66d09e0b9aca3a38973e2d1f97 ./IMA/proxy/contracts/predeployed/TokenManager.sol c40815ae415cb7195fa490bb1f210cf46d8a5f98090e0b80f86589a95787f0d7 ./IMA/proxy/contracts/predeployed/ERC20ModuleForSchain.sol 1c2ea3213b643a27989da484b1e710999a48ceed2e03a0a2f43ad851500ebe84 ./IMA/proxy/contracts/predeployed/OwnableForSchain.sol 0a7f8b0fc3633c649ee88720ddb5f3afda9e25c646ab2d815cc1ac52a82ded3f ./IMA/proxy/contracts/predeployed/MessageProxyForSchain.sol 0f6335e2b01d4d9eccada33da333b7bffd084f1277de28930bbf2d02443d4ae7 ./IMA/proxy/contracts/predeployed/PermissionsForSchain.sol 1dffd83fa2735b0b1300ddad511048b709d9961ae76fbba569b4dbd693bb1ce4 ./IMA/proxy/contracts/predeployed/LockAndDataForSchainERC20.sol 29880794a37dcac5ec49c10701f21bb6041dbdd06e38f0dd658bebfcebf473f2 ./IMA/proxy/contracts/predeployed/LockAndDataForSchain.sol e9932454e8bd531e6d286a345272f6e91fa4a1a51bf957b6c22a5e5f36b0b065 ./IMA/proxy/contracts/predeployed/TokenFactory.sol Tests 0c773f9f428d7653f3cb703db8b4837194c372323682b1853db3a7b0521867a0 ./IMA/proxy/contracts/test/TestSchains.sol c1a6440a6517a7679d32397f564ad9d0da71a90f7ca6656cd3432fd55acf00a9 ./IMA/proxy/contracts/test/LockAndDataForMainnetWorkaround.sol 444018e4c5b9e392d9692a693aecc320d46acf2fedad1e0cf70acb586ba08a3e ./IMA/proxy/contracts/test/TestContractManager.sol 50164312e001184f94fd273b06a526a5b13d59bb1043b3b285c9576c22277199 ./IMA/proxy/contracts/test/LockAndDataForSchainWorkaround.sol f736320870ae68daf01e28ef15fecc22012ad57bd211e8564cd66f55b91367d0 ./IMA/proxy/contracts/test/TestSchainsInternal.sol 550d7a3578e5b48ae010dd15f3d99a5829ab0ed78a09edb0649a668854ddef8a ./IMA/proxy/test/TokenFactory.spec.ts 22a0f39473f0037cf21988638eb5e93e57a10f3fd5fb107cd906054bf27f80ea ./IMA/proxy/test/LockAndDataForSchain.spec.ts 7dde350053fde8a66be59e4d2c843458057a257ac6db45281f0e125246f81e03 ./IMA/proxy/test/ERC20ModuleForSchain.spec.ts a324105ee84e934b8b95231864d5247d97904f6a49fe14cba1554687ac2c96a6 ./IMA/proxy/test/ERC20ModuleForMainnet.spec.ts c8520091ac471813239af2b2c29abfbd3ddbfb982a93a165ae36da411af82cde ./IMA/proxy/test/LockAndDataForSchainERC721.spec.ts d5bea9f0badf80af6a6cd3db97c61563ff3db517dfaaf07aad52914b749c4b73 ./IMA/proxy/test/ERC721ModuleForMainnet.spec.ts db738bce93d60527695f1b712f9a8adb4d9027a89e551aea3ea97e47ed2f4989 ./IMA/proxy/test/LockAndDataForSchain.ts 1cc7afa874135961b7d19f79fccf1bd298b95ac250b18dd2a4fa52a36db580f9 ./IMA/proxy/test/LockAndDataForMainnet.spec.ts 98829fbff58d80f7c01479ba683b1422297004059df06d4e6a0fe7f861cb29a5 ./IMA/proxy/test/MessageProxy.ts 7216cdccccd431b7cc69e22a033c665439cc5b4ecb9f19896f7b94f1c35adf4a ./IMA/proxy/test/LockAndDataForMainnetERC20.spec.ts ede56d39f6e06dade0b2cba440958037f0786b3b292f18b4b5b3f493ab409bcb ./IMA/proxy/test/LockAndDataForSchainERC20.spec.ts 089a8b6b66c70ea027b275295152af0da87bfdf556754b2c7771eea9095f720e ./IMA/proxy/test/ERC721ModuleForSchain.spec.ts 38ab965ac85c122bcce1c81095394668d104d665e7205b5c1575824903635ff8 ./IMA/proxy/test/DepositBox.spec.ts 00bbcdc73dadad90a67d8e0d0ee2a0b88721bf52255105795b1d21dacd2306c1 ./IMA/proxy/test/LockAndDataForMainnetERC721.spec.ts 47d4300744251d5e525a57c1f3ef9bebbd7d47179aca60befa4f13fad5c27634 ./IMA/proxy/test/TokenManager.spec.ts e44d967443fcc1efaf477308fca44c5cf85618f0d08c7bda09fdd448e40b8d53 ./IMA/proxy/test/utils/helper.ts dd3c4dd574f0aea1c9854c428d768f9d3e1ae579a5e4f1e44fd5cb128039784e ./IMA/proxy/test/utils/command_line.ts f6876bdbdcb522a00e3672b9ebfc3a5f9f6f4823c0dec67c7d62fa3b9c59f7de ./IMA/proxy/test/utils/time.ts 319269694633baacde87d3d7178888d172812f01e714646435f22d0673b2a599 ./IMA/proxy/test/utils/deploy/lockAndDataForMainnetERC721.ts 259298babbc37f7f980911a37716cb0d1deb94f8a2f5827c65a35d2b6314e866 ./IMA/proxy/test/utils/deploy/lockAndDataForMainnet.ts 9c6e1427ab9a7dd7c9a111746fd1c4e7740e56a4cfaec849951fdc42f33cb934 ./IMA/proxy/test/utils/deploy/messageProxyForMainnet.ts 13eac3123265b210d829cba03c1c0c5901aa4f9a2982a16796c049001d5f1a51 ./IMA/proxy/test/utils/deploy/erc721ModuleForMainnet.ts 231ebc8de6d392832df586df7dfd8623f344fb6058f6f056f76e41311aa54e31 ./IMA/proxy/test/utils/deploy/erc20ModuleForMainnet.ts 87d2f2f0ced1a0ea5cece4c6f1ffee429f4510e5c34cd8eb00b8ce2c45fa9ab4 ./IMA/proxy/test/utils/deploy/depositBox.ts b99061587a7ca6579456fdaca85439d40b20005d9174032773d7f1a62f19c0d8 ./IMA/proxy/test/utils/deploy/lockAndDataForMainnetERC20.ts Changelog2020-11-25 - Initial report •2021-01-08 - Reaudit commit taken at •ee72736 2021-01-14 - Tests results updated along with coverage. Also explicitly stated Best Practices and Documentation statuses when fixed or mitigated, along with adding one new documentation issue and removing stamp for addressing all best practices. •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 Proxy Contracts Audit
Issues Count of Minor/Moderate/Major/Critical - High Risk: 1 (1 Resolved) - Medium Risk: 0 (0 Resolved) - Low Risk: 2 (1 Resolved) - Informational Risk: 2 (2 Resolved) - Undetermined Risk: 0 (0 Resolved) Minor Issues - Problem: None - Fix: None Moderate - Problem: None - Fix: None Major - Problem: None - Fix: None Critical - 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. - Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations - We have found the codebase to be of good quality with well named methods and inline documentation. - There are some room for improvement with regards to documentation consistency. Conclusion We urge the Skale team to address the 5 issues of varying severities and consider our recommendations with which to go about fixing it. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Integer Overflow / Underflow 2.b Fix: Fixed Moderate 3.a Problem: Race Conditions / Front-Running 3.b Fix: Acknowledged Major None Critical None Observations • 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. • 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, Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Integer Overflow/Underflow (QSP-2) 2.b Fix: Use unsigned integers with a range of 0-2^256 Observations: 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. Conclusion: It is recommended to use OpenZeppelin's implementation instead of rolling a new owner-logic contract. Otherwise, ensure that setOwner is either set to internal or armed with some access control.
// SPDX-License-Identifier: AGPL-3.0-only /** * PermissionsForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; interface IContractManagerForMainnet { function permitted(bytes32 contractName) external view returns (address); } /** * @title PermissionsForMainnet - connected module for Upgradeable approach, knows ContractManager * @author Artem Payvin */ contract PermissionsForMainnet is AccessControlUpgradeSafe { // address of ContractManager address public lockAndDataAddress_; /** * @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( IContractManagerForMainnet( lockAndDataAddress_ ).permitted(keccak256(abi.encodePacked(contractName))) == msg.sender || getOwner() == msg.sender, "Message sender is invalid" ); _; } modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev initialize - sets current address of ContractManager * @param newContractsAddress - current address of ContractManager */ function initialize(address newContractsAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); lockAndDataAddress_ = newContractsAddress; } function getLockAndDataAddress() public view returns ( address a ) { return lockAndDataAddress_; } /** * @dev Returns owner address. */ function getOwner() public view returns ( address ow ) { return getRoleMember(DEFAULT_ADMIN_ROLE, 0); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } } // SPDX-License-Identifier: AGPL-3.0-only /** * MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; interface ContractReceiverForMainnet { function postMessage( address sender, string calldata schainID, address to, uint256 amount, bytes calldata data ) external; } interface IContractManagerSkaleManager { function contracts(bytes32 contractID) external view returns(address); } interface ISchains { function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); } /** * @title Message Proxy for Mainnet * @dev Runs on Mainnet, contains functions to manage the incoming messages from * `dstChainID` and outgoing messages to `srcChainID`. Every SKALE chain with * IMA is therefore connected to MessageProxyForMainnet. * * Messages from SKALE chains are signed using BLS threshold signatures from the * nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet * messages do not need to be signed. */ contract MessageProxyForMainnet is Initializable { // 16 Agents // Synchronize time with time.nist.gov // Every agent checks if it is his time slot // Time slots are in increments of 10 seconds // At the start of his slot each agent: // For each connected schain: // Read incoming counter on the dst chain // Read outgoing counter on the src chain // Calculate the difference outgoing - incoming // Call postIncomingMessages function passing (un)signed message array // ID of this schain, Chain 0 represents ETH mainnet, struct OutgoingMessageData { string dstChain; bytes32 dstChainHash; uint256 msgCounter; address srcContract; address dstContract; address to; uint256 amount; bytes data; uint256 length; } struct ConnectedChainInfo { // message counters start with 0 uint256 incomingMessageCounter; uint256 outgoingMessageCounter; bool inited; } struct Message { address sender; address destinationContract; address to; uint256 amount; bytes data; } struct Signature { uint256[2] blsSignature; uint256 hashA; uint256 hashB; uint256 counter; } string public chainID; // Owner of this chain. For mainnet, the owner is SkaleManager address public owner; address public contractManagerSkaleManager; uint256 private _idxHead; uint256 private _idxTail; mapping(address => bool) public authorizedCaller; mapping(bytes32 => ConnectedChainInfo) public connectedChains; mapping ( uint256 => OutgoingMessageData ) private _outgoingMessageData; /** * @dev Emitted for every outgoing message to `dstChain`. */ event OutgoingMessage( string dstChain, bytes32 indexed dstChainHash, uint256 indexed msgCounter, address indexed srcContract, address dstContract, address to, uint256 amount, bytes data, uint256 length ); event PostMessageError( uint256 indexed msgCounter, bytes32 indexed srcChainHash, address sender, string fromSchainID, address to, uint256 amount, bytes data, string message ); /** * @dev Adds an authorized caller. * * Requirements: * * - `msg.sender` must be an owner. */ function addAuthorizedCaller(address caller) external { require(msg.sender == owner, "Sender is not an owner"); authorizedCaller[caller] = true; } /** * @dev Removes an authorized caller. * * Requirements: * * - `msg.sender` must be an owner. */ function removeAuthorizedCaller(address caller) external { require(msg.sender == owner, "Sender is not an owner"); authorizedCaller[caller] = false; } /** * @dev Adds a `newChainID`. * * Requirements: * * - `msg.sender` must be SKALE Node address. * - `newChainID` must not be "Mainnet". * - `newChainID` must not already be added. */ function addConnectedChain( string calldata newChainID ) external { require(authorizedCaller[msg.sender], "Not authorized caller"); require( keccak256(abi.encodePacked(newChainID)) != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name is incorrect. Inside in MessageProxy"); require( !connectedChains[keccak256(abi.encodePacked(newChainID))].inited, "Chain is already connected" ); connectedChains[ keccak256(abi.encodePacked(newChainID)) ] = ConnectedChainInfo({ incomingMessageCounter: 0, outgoingMessageCounter: 0, inited: true }); } /** * @dev Removes connected chain from this contract. * * Requirements: * * - `msg.sender` must be owner. * - `newChainID` must be initialized. */ function removeConnectedChain(string calldata newChainID) external { require(authorizedCaller[msg.sender], "Not authorized caller"); require( connectedChains[keccak256(abi.encodePacked(newChainID))].inited, "Chain is not initialized" ); delete connectedChains[keccak256(abi.encodePacked(newChainID))]; } /** * @dev Posts message from this contract to `dstChainID` MessageProxy contract. * This is called by a smart contract to make a cross-chain call. * * Requirements: * * - `dstChainID` must be initialized. */ function postOutgoingMessage( string calldata dstChainID, address dstContract, uint256 amount, address to, bytes calldata data ) external { bytes32 dstChainHash = keccak256(abi.encodePacked(dstChainID)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); connectedChains[dstChainHash].outgoingMessageCounter++; _pushOutgoingMessageData( OutgoingMessageData( dstChainID, dstChainHash, connectedChains[dstChainHash].outgoingMessageCounter - 1, msg.sender, dstContract, to, amount, data, data.length ) ); } /** * @dev Posts incoming message from `srcChainID`. * * Requirements: * * - `msg.sender` must be authorized caller. * - `srcChainID` must be initialized. * - `startingCounter` must be equal to the chain's incoming message counter. * - If destination chain is Mainnet, message signature must be valid. */ function postIncomingMessages( string calldata srcChainID, uint256 startingCounter, Message[] calldata messages, Signature calldata sign, uint256 idxLastToPopNotIncluding ) external { bytes32 srcChainHash = keccak256(abi.encodePacked(srcChainID)); require(authorizedCaller[msg.sender], "Not authorized caller"); require(connectedChains[srcChainHash].inited, "Chain is not initialized"); require( startingCounter == connectedChains[srcChainHash].incomingMessageCounter, "Starning counter is not qual to incomin message counter"); if (keccak256(abi.encodePacked(chainID)) == keccak256(abi.encodePacked("Mainnet"))) { _convertAndVerifyMessages(srcChainID, messages, sign); } for (uint256 i = 0; i < messages.length; i++) { try ContractReceiverForMainnet(messages[i].destinationContract).postMessage( messages[i].sender, srcChainID, messages[i].to, messages[i].amount, messages[i].data ) { ++startingCounter; } catch Error(string memory reason) { emit PostMessageError( ++startingCounter, srcChainHash, messages[i].sender, srcChainID, messages[i].to, messages[i].amount, messages[i].data, reason ); } } connectedChains[keccak256(abi.encodePacked(srcChainID))].incomingMessageCounter += uint256(messages.length); _popOutgoingMessageData(idxLastToPopNotIncluding); } /** * @dev Increments incoming message counter. * * Note: Test function. TODO: remove in production. * * Requirements: * * - `msg.sender` must be owner. */ function moveIncomingCounter(string calldata schainName) external { require(msg.sender == owner, "Sender is not an owner"); connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter++; } /** * @dev Sets the incoming and outgoing message counters to zero. * * Note: Test function. TODO: remove in production. * * Requirements: * * - `msg.sender` must be owner. */ function setCountersToZero(string calldata schainName) external { require(msg.sender == owner, "Sender is not an owner"); connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter = 0; connectedChains[keccak256(abi.encodePacked(schainName))].outgoingMessageCounter = 0; } /** * @dev Checks whether chain is currently connected. * * Note: Mainnet chain does not have a public key, and is implicitly * connected to MessageProxy. * * Requirements: * * - `someChainID` must not be Mainnet. */ function isConnectedChain( string calldata someChainID ) external view returns (bool) { //require(msg.sender == owner); // todo: tmp!!!!! require( keccak256(abi.encodePacked(someChainID)) != keccak256(abi.encodePacked("Mainnet")), "Schain id can not be equal Mainnet"); // main net does not have a public key and is implicitly connected if ( ! connectedChains[keccak256(abi.encodePacked(someChainID))].inited ) { return false; } return true; } function getOutgoingMessagesCounter(string calldata dstChainID) external view returns (uint256) { bytes32 dstChainHash = keccak256(abi.encodePacked(dstChainID)); require(connectedChains[dstChainHash].inited, "Destination chain is not initialized"); return connectedChains[dstChainHash].outgoingMessageCounter; } function getIncomingMessagesCounter(string calldata srcChainID) external view returns (uint256) { bytes32 srcChainHash = keccak256(abi.encodePacked(srcChainID)); require(connectedChains[srcChainHash].inited, "Source chain is not initialized"); return connectedChains[srcChainHash].incomingMessageCounter; } /// Create a new message proxy function initialize(string memory newChainID, address newContractManager) public initializer { owner = msg.sender; authorizedCaller[msg.sender] = true; chainID = newChainID; contractManagerSkaleManager = newContractManager; } /** * @dev Checks whether outgoing message is valid. */ function verifyOutgoingMessageData( uint256 idxMessage, address sender, address destinationContract, address to, uint256 amount ) public view returns (bool isValidMessage) { isValidMessage = false; OutgoingMessageData memory d = _outgoingMessageData[idxMessage]; if ( d.dstContract == destinationContract && d.srcContract == sender && d.to == to && d.amount == amount ) isValidMessage = true; } function _convertAndVerifyMessages( string calldata srcChainID, Message[] calldata messages, Signature calldata sign ) internal { Message[] memory input = new Message[](messages.length); for (uint256 i = 0; i < messages.length; i++) { input[i].sender = messages[i].sender; input[i].destinationContract = messages[i].destinationContract; input[i].to = messages[i].to; input[i].amount = messages[i].amount; input[i].data = messages[i].data; } require( _verifyMessageSignature( sign.blsSignature, _hashedArray(input), sign.counter, sign.hashA, sign.hashB, srcChainID ), "Signature is not verified" ); } /** * @dev Checks whether message BLS signature is valid. */ function _verifyMessageSignature( uint256[2] memory blsSignature, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string memory srcChainID ) private view returns (bool) { address skaleSchains = IContractManagerSkaleManager(contractManagerSkaleManager).contracts( keccak256(abi.encodePacked("Schains")) ); return ISchains(skaleSchains).verifySchainSignature( blsSignature[0], blsSignature[1], hash, counter, hashA, hashB, srcChainID ); } /** * @dev Returns hash of message array. */ function _hashedArray(Message[] memory messages) private pure returns (bytes32) { bytes memory data; for (uint256 i = 0; i < messages.length; i++) { data = abi.encodePacked( data, bytes32(bytes20(messages[i].sender)), bytes32(bytes20(messages[i].destinationContract)), bytes32(bytes20(messages[i].to)), messages[i].amount, messages[i].data ); } return keccak256(data); } /** * @dev Push outgoing message into outgoingMessageData array. * * Emits an {OutgoingMessage} event. */ function _pushOutgoingMessageData( OutgoingMessageData memory d ) private { emit OutgoingMessage( d.dstChain, d.dstChainHash, d.msgCounter, d.srcContract, d.dstContract, d.to, d.amount, d.data, d.length ); _outgoingMessageData[_idxTail] = d; ++_idxTail; } /** * @dev Pop outgoing message from outgoingMessageData array. */ function _popOutgoingMessageData( uint256 idxLastToPopNotIncluding ) private returns ( uint256 cntDeleted ) { cntDeleted = 0; for ( uint256 i = _idxHead; i < idxLastToPopNotIncluding; ++ i ) { if ( i >= _idxTail ) break; delete _outgoingMessageData[i]; ++ cntDeleted; } if (cntDeleted > 0) _idxHead += cntDeleted; } } // SPDX-License-Identifier: AGPL-3.0-only /** * ERC721ModuleForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Metadata.sol"; interface ILockAndDataERC721M { function erc721Tokens(uint256 index) external returns (address); function erc721Mapper(address contractERC721) external returns (uint256); function addERC721Token(address contractERC721) external returns (uint256); function sendERC721(address contractHere, address to, uint256 token) external returns (bool); } /** * @title ERC721 Module For Mainnet * @dev Runs on Mainnet, and manages receiving and sending of ERC721 token contracts * and encoding contractPosition in LockAndDataForMainnetERC721. */ contract ERC721ModuleForMainnet is PermissionsForMainnet { /** * @dev Emitted when token is mapped in LockAndDataForMainnetERC721. */ event ERC721TokenAdded(address indexed tokenHere, uint256 contractPosition); /** * @dev Allows DepositBox to receive ERC721 tokens. * * Emits an {ERC721TokenAdded} event. */ function receiveERC721( address contractHere, address to, uint256 tokenId, bool isRAW ) external allow("DepositBox") returns (bytes memory data) { address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); if (!isRAW) { uint256 contractPosition = ILockAndDataERC721M(lockAndDataERC721).erc721Mapper(contractHere); if (contractPosition == 0) { contractPosition = ILockAndDataERC721M(lockAndDataERC721).addERC721Token(contractHere); emit ERC721TokenAdded(contractHere, contractPosition); } data = _encodeData( contractHere, contractPosition, to, tokenId); return data; } else { data = _encodeRawData(to, tokenId); return data; } } /** * @dev Allows DepositBox to send ERC721 tokens. */ function sendERC721(address to, bytes calldata data) external allow("DepositBox") returns (bool) { address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); uint256 contractPosition; address contractAddress; address receiver; uint256 tokenId; if (to == address(0)) { (contractPosition, receiver, tokenId) = _fallbackDataParser(data); contractAddress = ILockAndDataERC721M(lockAndDataERC721).erc721Tokens(contractPosition); } else { (receiver, tokenId) = _fallbackRawDataParser(data); contractAddress = to; } return ILockAndDataERC721M(lockAndDataERC721).sendERC721(contractAddress, receiver, tokenId); } /** * @dev Returns the receiver address of the ERC20 token. */ function getReceiver(address to, bytes calldata data) external pure returns (address receiver) { uint256 contractPosition; uint256 amount; if (to == address(0)) { (contractPosition, receiver, amount) = _fallbackDataParser(data); } else { (receiver, amount) = _fallbackRawDataParser(data); } } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); } /** * @dev Returns encoded creation data for ERC721 token. */ function _encodeData( address contractHere, uint256 contractPosition, address to, uint256 tokenId ) private view returns (bytes memory data) { string memory name = IERC721Metadata(contractHere).name(); string memory symbol = IERC721Metadata(contractHere).symbol(); data = abi.encodePacked( bytes1(uint8(5)), bytes32(contractPosition), bytes32(bytes20(to)), bytes32(tokenId), bytes(name).length, name, bytes(symbol).length, symbol ); } /** * @dev Returns encoded regular data. */ function _encodeRawData(address to, uint256 tokenId) private pure returns (bytes memory data) { data = abi.encodePacked( bytes1(uint8(21)), bytes32(bytes20(to)), bytes32(tokenId) ); } /** * @dev Returns fallback data. */ function _fallbackDataParser(bytes memory data) private pure returns (uint256, address payable, uint256) { bytes32 contractIndex; bytes32 to; bytes32 token; // solhint-disable-next-line no-inline-assembly assembly { contractIndex := mload(add(data, 33)) to := mload(add(data, 65)) token := mload(add(data, 97)) } return ( uint256(contractIndex), address(bytes20(to)), uint256(token) ); } /** * @dev Returns fallback raw data. */ function _fallbackRawDataParser(bytes memory data) private pure returns (address payable, uint256) { bytes32 to; bytes32 token; // solhint-disable-next-line no-inline-assembly assembly { to := mload(add(data, 33)) token := mload(add(data, 65)) } return (address(bytes20(to)), uint256(token)); } } // SPDX-License-Identifier: AGPL-3.0-only /** * ERC20ModuleForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; interface ILockAndDataERC20M { function erc20Tokens(uint256 index) external returns (address); function erc20Mapper(address contractERC20) external returns (uint256); function addERC20Token(address contractERC20) external returns (uint256); function sendERC20(address contractHere, address to, uint256 amount) external returns (bool); } /** * @title ERC20 Module For Mainnet * @dev Runs on Mainnet, and manages receiving and sending of ERC20 token contracts * and encoding contractPosition in LockAndDataForMainnetERC20. */ contract ERC20ModuleForMainnet is PermissionsForMainnet { /** * @dev Emitted when token is mapped in LockAndDataForMainnetERC20. */ event ERC20TokenAdded(address indexed tokenHere, uint256 contractPosition); /** * @dev Emitted when token is received by DepositBox and is ready to be cloned * or transferred on SKALE chain. */ event ERC20TokenReady(address indexed tokenHere, uint256 contractPosition, uint256 amount); /** * @dev Allows DepositBox to receive ERC20 tokens. * * Emits an {ERC20TokenAdded} event on token mapping in LockAndDataForMainnetERC20. * Emits an {ERC20TokenReady} event. * * Requirements: * * - Amount must be less than or equal to the total supply of the ERC20 contract. */ function receiveERC20( address contractHere, address to, uint256 amount, bool isRAW ) external allow("DepositBox") returns (bytes memory data) { address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); uint256 totalSupply = ERC20UpgradeSafe(contractHere).totalSupply(); require(amount <= totalSupply, "Amount is incorrect"); uint256 contractPosition = ILockAndDataERC20M(lockAndDataERC20).erc20Mapper(contractHere); if (contractPosition == 0) { contractPosition = ILockAndDataERC20M(lockAndDataERC20).addERC20Token(contractHere); emit ERC20TokenAdded(contractHere, contractPosition); } if (!isRAW) { data = _encodeCreationData( contractHere, contractPosition, to, amount ); } else { data = _encodeRegularData(to, contractPosition, amount); } emit ERC20TokenReady(contractHere, contractPosition, amount); return data; } /** * @dev Allows DepositBox to send ERC20 tokens. */ function sendERC20(address to, bytes calldata data) external allow("DepositBox") returns (bool) { address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); uint256 contractPosition; address contractAddress; address receiver; uint256 amount; (contractPosition, receiver, amount) = _fallbackDataParser(data); contractAddress = ILockAndDataERC20M(lockAndDataERC20).erc20Tokens(contractPosition); if (to != address(0)) { if (contractAddress == address(0)) { contractAddress = to; } } bool variable = ILockAndDataERC20M(lockAndDataERC20).sendERC20(contractAddress, receiver, amount); return variable; } /** * @dev Returns the receiver address of the ERC20 token. */ function getReceiver(bytes calldata data) external view returns (address receiver) { uint256 contractPosition; uint256 amount; (contractPosition, receiver, amount) = _fallbackDataParser(data); } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); } /** * @dev Returns encoded creation data for ERC20 token. */ function _encodeCreationData( address contractHere, uint256 contractPosition, address to, uint256 amount ) private view returns (bytes memory data) { string memory name = ERC20UpgradeSafe(contractHere).name(); uint8 decimals = ERC20UpgradeSafe(contractHere).decimals(); string memory symbol = ERC20UpgradeSafe(contractHere).symbol(); uint256 totalSupply = ERC20UpgradeSafe(contractHere).totalSupply(); data = abi.encodePacked( bytes1(uint8(3)), bytes32(contractPosition), bytes32(bytes20(to)), bytes32(amount), bytes(name).length, name, bytes(symbol).length, symbol, decimals, totalSupply ); } /** * @dev Returns encoded regular data. */ function _encodeRegularData( address to, uint256 contractPosition, uint256 amount ) private pure returns (bytes memory data) { data = abi.encodePacked( bytes1(uint8(19)), bytes32(contractPosition), bytes32(bytes20(to)), bytes32(amount) ); } /** * @dev Returns fallback data. */ function _fallbackDataParser(bytes memory data) private pure returns (uint256, address payable, uint256) { bytes32 contractIndex; bytes32 to; bytes32 token; // solhint-disable-next-line no-inline-assembly assembly { contractIndex := mload(add(data, 33)) to := mload(add(data, 65)) token := mload(add(data, 97)) } return ( uint256(contractIndex), address(bytes20(to)), uint256(token) ); } } // SPDX-License-Identifier: AGPL-3.0-only /** * LockAndDataForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./OwnableForMainnet.sol"; /** * @title Lock and Data For Mainnet * @dev Runs on Mainnet, holds deposited ETH, and contains mappings and * balances of ETH tokens received through DepositBox. */ contract LockAndDataForMainnet is OwnableForMainnet { mapping(bytes32 => address) public permitted; mapping(bytes32 => address) public tokenManagerAddresses; mapping(address => uint256) public approveTransfers; mapping(address => bool) public authorizedCaller; modifier allow(string memory contractName) { require( permitted[keccak256(abi.encodePacked(contractName))] == msg.sender || getOwner() == msg.sender, "Not allowed" ); _; } /** * @dev Emitted when DepositBox receives ETH. */ event ETHReceived(address from, uint256 amount); /** * @dev Emitted upon failure. */ event Error( address to, uint256 amount, string message ); /** * @dev Allows DepositBox to receive ETH. * * Emits a {ETHReceived} event. */ function receiveEth(address from) external allow("DepositBox") payable { emit ETHReceived(from, msg.value); } /** * @dev Allows Owner to set a new contract address. * * Requirements: * * - New contract address must be non-zero. * - New contract address must not already be added. * - Contract must contain code. */ function setContract(string calldata contractName, address newContract) external virtual onlyOwner { require(newContract != address(0), "New address is equal zero"); bytes32 contractId = keccak256(abi.encodePacked(contractName)); require(permitted[contractId] != newContract, "Contract is already added"); uint256 length; // solhint-disable-next-line no-inline-assembly assembly { length := extcodesize(newContract) } require(length > 0, "Given contract address does not contain code"); permitted[contractId] = newContract; } /** * @dev Adds a SKALE chain and its TokenManager address to * LockAndDataForMainnet. * * Requirements: * * - `msg.sender` must be authorized caller. * - SKALE chain must not already be added. * - TokenManager address must be non-zero. */ function addSchain(string calldata schainID, address tokenManagerAddress) external { require(authorizedCaller[msg.sender], "Not authorized caller"); bytes32 schainHash = keccak256(abi.encodePacked(schainID)); require(tokenManagerAddresses[schainHash] == address(0), "SKALE chain is already set"); require(tokenManagerAddress != address(0), "Incorrect Token Manager address"); tokenManagerAddresses[schainHash] = tokenManagerAddress; } /** * @dev Allows Owner to remove a SKALE chain from contract. * * Requirements: * * - SKALE chain must already be set. */ function removeSchain(string calldata schainID) external onlyOwner { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); require(tokenManagerAddresses[schainHash] != address(0), "SKALE chain is not set"); delete tokenManagerAddresses[schainHash]; } /** * @dev Allows Owner to add an authorized caller. */ function addAuthorizedCaller(address caller) external onlyOwner { authorizedCaller[caller] = true; } /** * @dev Allows Owner to remove an authorized caller. */ function removeAuthorizedCaller(address caller) external onlyOwner { authorizedCaller[caller] = false; } /** * @dev Allows DepositBox to approve transfer. */ function approveTransfer(address to, uint256 amount) external allow("DepositBox") { approveTransfers[to] += amount; } /** * @dev Transfers a user's ETH. * * Requirements: * * - LockAndDataForMainnet must have sufficient ETH. * - User must be approved for ETH transfer. */ function getMyEth() external { require( address(this).balance >= approveTransfers[msg.sender], "Not enough ETH. in `LockAndDataForMainnet.getMyEth`" ); require(approveTransfers[msg.sender] > 0, "User has insufficient ETH"); uint256 amount = approveTransfers[msg.sender]; approveTransfers[msg.sender] = 0; msg.sender.transfer(amount); } /** * @dev Allows DepositBox to send ETH. * * Emits an {Error} upon insufficient ETH in LockAndDataForMainnet. */ function sendEth(address payable to, uint256 amount) external allow("DepositBox") returns (bool) { if (address(this).balance >= amount) { to.transfer(amount); return true; } } /** * @dev Returns the contract address for a given contractName. */ function getContract(string memory contractName) external view returns (address) { return permitted[keccak256(abi.encodePacked(contractName))]; } /** * @dev Checks whether LockAndDataforMainnet is connected to a SKALE chain. */ function hasSchain( string calldata schainID ) external view returns (bool) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); if ( tokenManagerAddresses[schainHash] == address(0) ) { return false; } return true; } function initialize() public override initializer { OwnableForMainnet.initialize(); authorizedCaller[msg.sender] = true; } } // SPDX-License-Identifier: AGPL-3.0-only /** * OwnableForMainnet.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /** * @title OwnableForMainnet * @dev The OwnableForMainnet contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract OwnableForMainnet is Initializable { /** * @dev _ownerAddress is only used after transferOwnership(). * By default, value of "skaleConfig.contractSettings.IMA._ownerAddress" config variable is used */ address private _ownerAddress; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == getOwner(), "Only owner can execute this method"); _; } /** * @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 payable newOwner) external onlyOwner { require(newOwner != address(0), "New owner has to be set"); setOwner(newOwner); } /** * @dev initialize sets the original `owner` of the contract to the sender * account. */ function initialize() public virtual initializer { _ownerAddress = msg.sender; } /** * @dev Sets new owner address. */ function setOwner( address newAddressOwner ) public { _ownerAddress = newAddressOwner; } /** * @dev Returns owner address. */ function getOwner() public view returns ( address ow ) { return _ownerAddress; } } // SPDX-License-Identifier: AGPL-3.0-only /** * DepositBox.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "./interfaces/IMessageProxy.sol"; import "./interfaces/IERC20Module.sol"; import "./interfaces/IERC721Module.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface ILockAndDataDB { function setContract(string calldata contractName, address newContract) external; function tokenManagerAddresses(bytes32 schainHash) external returns (address); function sendEth(address to, uint256 amount) external returns (bool); function approveTransfer(address to, uint256 amount) external; function addSchain(string calldata schainID, address tokenManagerAddress) external; function receiveEth(address from) external payable; } // This contract runs on the main net and accepts deposits contract DepositBox is PermissionsForMainnet { enum TransactionOperation { transferETH, transferERC20, transferERC721, rawTransferERC20, rawTransferERC721 } uint256 public constant GAS_AMOUNT_POST_MESSAGE = 200000; uint256 public constant AVERAGE_TX_PRICE = 10000000000; event MoneyReceivedMessage( address sender, string fromSchainID, address to, uint256 amount, bytes data ); event Error( address to, uint256 amount, string message ); modifier rightTransaction(string memory schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash); require(schainHash != keccak256(abi.encodePacked("Mainnet")), "SKALE chain name is incorrect"); require(tokenManagerAddress != address(0), "Unconnected chain"); _; } modifier requireGasPayment() { require(msg.value >= GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE, "Gas was not paid"); _; ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } fallback() external payable { revert("Not allowed. in DepositBox"); } function depositWithoutData(string calldata schainID, address to) external payable { deposit(schainID, to); } function depositERC20( string calldata schainID, address contractHere, address to, uint256 amount ) external payable rightTransaction(schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash); address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); address erc20Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC20Module")) ); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); require( IERC20(contractHere).allowance( msg.sender, address(this) ) >= amount, "Not allowed ERC20 Token" ); require( IERC20(contractHere).transferFrom( msg.sender, lockAndDataERC20, amount ), "Could not transfer ERC20 Token" ); bytes memory data = IERC20Module(erc20Module).receiveERC20( contractHere, to, amount, false); IMessageProxy(proxyAddress).postOutgoingMessage( schainID, tokenManagerAddress, msg.value, address(0), data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function rawDepositERC20( string calldata schainID, address contractHere, address contractThere, address to, uint256 amount ) external payable rightTransaction(schainID) { address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses( keccak256(abi.encodePacked(schainID)) ); address lockAndDataERC20 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC20")) ); address erc20Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC20Module")) ); require( IERC20(contractHere).allowance( msg.sender, address(this) ) >= amount, "Not allowed ERC20 Token" ); require( IERC20(contractHere).transferFrom( msg.sender, lockAndDataERC20, amount ), "Could not transfer ERC20 Token" ); bytes memory data = IERC20Module(erc20Module).receiveERC20(contractHere, to, amount, true); IMessageProxy(IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) )).postOutgoingMessage( schainID, tokenManagerAddress, msg.value, contractThere, data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function depositERC721( string calldata schainID, address contractHere, address to, uint256 tokenId) external payable rightTransaction(schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); address erc721Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC721Module")) ); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); require(IERC721(contractHere).ownerOf(tokenId) == address(this), "Not allowed ERC721 Token"); IERC721(contractHere).transferFrom(address(this), lockAndDataERC721, tokenId); require(IERC721(contractHere).ownerOf(tokenId) == lockAndDataERC721, "Did not transfer ERC721 token"); bytes memory data = IERC721Module(erc721Module).receiveERC721( contractHere, to, tokenId, false); IMessageProxy(proxyAddress).postOutgoingMessage( schainID, ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash), msg.value, address(0), data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function rawDepositERC721( string calldata schainID, address contractHere, address contractThere, address to, uint256 tokenId ) external payable rightTransaction(schainID) { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address lockAndDataERC721 = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("LockAndDataERC721")) ); address erc721Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC721Module")) ); require(IERC721(contractHere).ownerOf(tokenId) == address(this), "Not allowed ERC721 Token"); IERC721(contractHere).transferFrom(address(this), lockAndDataERC721, tokenId); require(IERC721(contractHere).ownerOf(tokenId) == lockAndDataERC721, "Did not transfer ERC721 token"); bytes memory data = IERC721Module(erc721Module).receiveERC721( contractHere, to, tokenId, true); IMessageProxy(IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) )).postOutgoingMessage( schainID, ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash), msg.value, contractThere, data ); if (msg.value > 0) { ILockAndDataDB(lockAndDataAddress_).receiveEth.value(msg.value)(msg.sender); } } function postMessage( address sender, string calldata fromSchainID, address payable to, uint256 amount, bytes calldata data ) external { require(data.length != 0, "Invalid data"); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); require(msg.sender == proxyAddress, "Incorrect sender"); bytes32 schainHash = keccak256(abi.encodePacked(fromSchainID)); require( schainHash != keccak256(abi.encodePacked("Mainnet")) && sender == ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash), "Receiver chain is incorrect" ); require( amount <= address(lockAndDataAddress_).balance || amount >= GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE, "Not enough money to finish this transaction" ); require( ILockAndDataDB(lockAndDataAddress_).sendEth(getOwner(), GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE), "Could not send money to owner" ); _executePerOperation(to, amount, data); } /// Create a new deposit box function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); } function deposit(string memory schainID, address to) public payable { bytes memory empty = ""; deposit(schainID, to, empty); } function deposit(string memory schainID, address to, bytes memory data) public payable rightTransaction(schainID) requireGasPayment { bytes32 schainHash = keccak256(abi.encodePacked(schainID)); address tokenManagerAddress = ILockAndDataDB(lockAndDataAddress_).tokenManagerAddresses(schainHash); address proxyAddress = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("MessageProxy")) ); bytes memory newData; newData = abi.encodePacked(bytes1(uint8(1)), data); IMessageProxy(proxyAddress).postOutgoingMessage( schainID, tokenManagerAddress, msg.value, to, newData ); } function _executePerOperation( address payable to, uint256 amount, bytes calldata data ) internal { TransactionOperation operation = _fallbackOperationTypeConvert(data); if (operation == TransactionOperation.transferETH) { if (amount > GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE) { ILockAndDataDB(lockAndDataAddress_).approveTransfer( to, amount - GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE ); } } else if ((operation == TransactionOperation.transferERC20 && to == address(0)) || (operation == TransactionOperation.rawTransferERC20 && to != address(0))) { address erc20Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC20Module")) ); require(IERC20Module(erc20Module).sendERC20(to, data), "Sending of ERC20 was failed"); address receiver = IERC20Module(erc20Module).getReceiver(data); if (amount > GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE) { ILockAndDataDB(lockAndDataAddress_).approveTransfer( receiver, amount - GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE ); } } else if ((operation == TransactionOperation.transferERC721 && to == address(0)) || (operation == TransactionOperation.rawTransferERC721 && to != address(0))) { address erc721Module = IContractManagerForMainnet(lockAndDataAddress_).permitted( keccak256(abi.encodePacked("ERC721Module")) ); require(IERC721Module(erc721Module).sendERC721(to, data), "Sending of ERC721 was failed"); address receiver = IERC721Module(erc721Module).getReceiver(to, data); if (amount > GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE) { ILockAndDataDB(lockAndDataAddress_).approveTransfer( receiver, amount - GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE ); } } } /** * @dev Convert first byte of data to Operation * 0x01 - transfer eth * 0x03 - transfer ERC20 token * 0x05 - transfer ERC721 token * 0x13 - transfer ERC20 token - raw mode * 0x15 - transfer ERC721 token - raw mode * @param data - received data * @return operation */ function _fallbackOperationTypeConvert(bytes memory data) private pure returns (TransactionOperation) { bytes1 operationType; // solhint-disable-next-line no-inline-assembly assembly { operationType := mload(add(data, 0x20)) } require( operationType == 0x01 || operationType == 0x03 || operationType == 0x05 || operationType == 0x13 || operationType == 0x15, "Operation type is not identified" ); if (operationType == 0x01) { return TransactionOperation.transferETH; } else if (operationType == 0x03) { return TransactionOperation.transferERC20; } else if (operationType == 0x05) { return TransactionOperation.transferERC721; } else if (operationType == 0x13) { return TransactionOperation.rawTransferERC20; } else if (operationType == 0x15) { return TransactionOperation.rawTransferERC721; } } }// SPDX-License-Identifier: AGPL-3.0-only /** * Migrations.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; contract Migrations { address public owner; uint256 public lastCompletedMigration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint256 completed) external restricted { lastCompletedMigration = completed; } function upgrade(address newAddress) external restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(lastCompletedMigration); } }// SPDX-License-Identifier: AGPL-3.0-only /** * LockAndDataForMainnetERC20.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /** * @title Lock and Data For Mainnet ERC20 * @dev Runs on Mainnet, holds deposited ERC20s, and contains mappings and * balances of ERC20 tokens received through DepositBox. */ contract LockAndDataForMainnetERC20 is PermissionsForMainnet { mapping(uint256 => address) public erc20Tokens; mapping(address => uint256) public erc20Mapper; uint256 public newIndexERC20; /** * @dev Allows ERC20Module to send an ERC20 token from * LockAndDataForMainnetERC20. * * Requirements: * * - `amount` must be less than or equal to the balance * in LockAndDataForMainnetERC20. * - Transfer must be successful. */ function sendERC20(address contractHere, address to, uint256 amount) external allow("ERC20Module") returns (bool) { require(IERC20(contractHere).balanceOf(address(this)) >= amount, "Not enough money"); require(IERC20(contractHere).transfer(to, amount), "something went wrong with `transfer` in ERC20"); return true; } /** * @dev Allows ERC20Module to add an ERC20 token to LockAndDataForMainnetERC20. */ function addERC20Token(address addressERC20) external allow("ERC20Module") returns (uint256) { uint256 index = newIndexERC20; erc20Tokens[index] = addressERC20; erc20Mapper[addressERC20] = index; newIndexERC20++; return index; } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); newIndexERC20 = 1; } } // SPDX-License-Identifier: AGPL-3.0-only /** * LockAndDataForMainnetERC721.sol - SKALE Interchain Messaging Agent * Copyright (C) 2019-Present SKALE Labs * @author Artem Payvin * * SKALE IMA 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 IMA 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 IMA. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; import "./PermissionsForMainnet.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; /** * @title Lock And Data For Mainnet ERC721 * @dev Runs on Mainnet, holds deposited ERC721s, and contains mappings and * balances of ERC721 tokens received through DepositBox. */ contract LockAndDataForMainnetERC721 is PermissionsForMainnet { mapping(uint256 => address) public erc721Tokens; mapping(address => uint256) public erc721Mapper; uint256 public newIndexERC721; /** * @dev Allows ERC721ModuleForMainnet to send an ERC721 token. * * Requirements: * * - If ERC721 is held by LockAndDataForMainnetERC721, token must * transferrable from the contract to the recipient address. */ function sendERC721(address contractHere, address to, uint256 tokenId) external allow("ERC721Module") returns (bool) { if (IERC721(contractHere).ownerOf(tokenId) == address(this)) { IERC721(contractHere).transferFrom(address(this), to, tokenId); require(IERC721(contractHere).ownerOf(tokenId) == to, "Did not transfer"); } return true; } /** * @dev Allows ERC721ModuleForMainnet to add an ERC721 token to * LockAndDataForMainnetERC721. */ function addERC721Token(address addressERC721) external allow("ERC721Module") returns (uint256) { uint256 index = newIndexERC721; erc721Tokens[index] = addressERC721; erc721Mapper[addressERC721] = index; newIndexERC721++; return index; } function initialize(address newLockAndDataAddress) public override initializer { PermissionsForMainnet.initialize(newLockAndDataAddress); newIndexERC721 = 1; } }
February 3rd 2021— Quantstamp Verified Skale Proxy Contracts This security assessment was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type DeFi Auditors Jake Goh Si Yuan , Senior Security ResearcherJan Gorzny , Blockchain ResearcherKevin Feng , Blockchain ResearcherTimeline 2020-11-16 through 2021-01-26 EVM Muir Glacier Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review Specification Provided Documentation Documentation Quality High Test Quality Medium Source Code Repository Commit IMA/proxy 8ba7484 None ee72736 None 082b932 Total Issues 5 (4 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 0 (0 Resolved)Low Risk Issues 2 (1 Resolved)Informational Risk Issues 2 (2 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 FindingsWe have performed a complete assessment of the codebase provided and discovered 5 issues of varying severities, amongst which there is 1 high, 2 low and 2 informational. We urge the Skale team to address these issues and consider our recommendations with which to go about fixing it. Overall, we have found the codebase to be of good quality with well named methods and inline documentation. That being said, there are some room for improvement with regards to documentation consistency. At the same time, it is important to note that we acknowledge that there exists a node.js agent that handles the communication between mainnet and the separate chains. As this audit was focused only on the smart contracts components, that part is out of scope of the audit and might be a source of centralization for attacks. ID Description Severity Status QSP- 1 Improper access control to a core method High Fixed QSP- 2 Integer Overflow / Underflow Low Fixed QSP- 3 Race Conditions / Front-Running Low Acknowledged QSP- 4 Schain ETH contract is supply limited Informational Fixed QSP- 5 Hardcoded addresses and associated methods with unknown results Informational Mitigated 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.13 • SlitherSteps taken to run the tools: 1. Installed the Slither tool:pip install slither-analyzer 2. Run Slither from the project directory:slither . FindingsQSP-1 Improper access control to a core method Severity: High Risk Fixed Status: , File(s) affected: OwnableForMainnet.sol OwnableForSchain.sol is intended to be a basic singular access control inheritable contract that is used by . The logic of this contract is very similar to a well known and ubiquitous implementation provided by OpenZeppelin, with a major difference in an inclusion of a method . Description:OwnableForMainnet LockAndDataForMainnet Ownable setOwner The method is used via to set the new . However, this method is set to visibility, which means that it can be executed by any arbitrary actor to any arbitrary value. This is extremely dangerous given the relative importance and power of the owner role. setOwnertransferOwnership _ownerAddress public Use OpenZeppelin's implementation instead, as it has already been done for many other contracts, instead of rolling a new owner-logic contract. Otherwise, ensure that is either set to or armed with some access control. Recommendation:setOwner internal QSP-2 Integer Overflow / Underflow Severity: Low Risk Fixed Status: , , File(s) affected: LockAndDataForMainnet.sol LockAndDataForSchain.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 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 { uint8num_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 } } We have discovered these instances in the codebase: 1. LockAndDataForMainnet.sol::L144approveTransfers[to] += amount; 2. LockAndDataForSchain.sol::L206ethCosts[to] += amount 3. MessageProxyForSchain.sol::L428_idxHead += cntDeleted 4. MessageProxyForSchain.sol::L416++ _idxTail; 5. MessageProxyForSchain.sol::L334connectedChains[keccak256(abi.encodePacked(srcChainID))].incomingMessageCounter += uint256(messages.length); 6. MessageProxyForSchain.sol::L340connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter++; 7. MessageProxyForSchain.sol::L252connectedChains[dstChainHash].outgoingMessageCounter++; 8. MessageProxyForMainnet.sol::L532_idxHead += cntDeleted 9. MessageProxyForMainnet.sol::L517++ _idxTail; 10. MessageProxyForMainnet.sol::L315 connectedChains[keccak256(abi.encodePacked(srcChainID))].incomingMessageCounter += uint256(messages.length); 11. MessageProxyForMainnet.sol::L330connectedChains[keccak256(abi.encodePacked(schainName))].incomingMessageCounter++; 12. MessageProxyForMainnet.sol::L247 connectedChains[dstChainHash].outgoingMessageCounter++; Use SafeMath for all instances of arithmetic. Recommendation: QSP-3 Race Conditions / Front-Running Severity: Low Risk Acknowledged Status: File(s) affected: EthERC20.sol Related Issue(s): SWC-114 A block is an ordered collection of transactions from all around the network. It's possible for the ordering of these transactions to manipulate the end result of a block. A miner attacker can take advantage of this by generating and moving transactions in a way that benefits themselves. Description:In particular, this refers to the well known frontrunning attack on ERC20. approveImagine two friends — Alice and Bob. Exploit Scenario: 1. Alice decides to allow Bob to spend some of her funds, for example, 1000 tokens. She calls the approve function with the argument equal to 1000.2. Alice rethinks her previous decision and now she wants to allow Bob to spend only 300 tokens. She calls the approve function again with the argument value equal to300. 3. Bob notices the second transaction before it is actually mined. He quickly sends the transaction that calls the transferFrom function and spends 1000 tokens.4. Since Bob is smart, he sets very high fee for his transaction, so that miner will definitely want to include his transaction in the block. If Bob is as quick as he is generous,his transaction will be executed before the Alice’s one. 5. In that case, Bob has already spent 1000 Alice’s tokens. The number of Alice’s tokens that Bob can transfer is equal to zero. 6.Then the Alice’s second transaction ismined. That means, that the Bob’s allowance is set to 300. 7.Now Bob can spend 300 more tokens by calling the transferFrom function. As a result, Bob has spent 1300 tokens. Alice has lost 1000 tokens and one friend. Make this issue well known such that users who use the allowance feature would be aware of it in such transitions. One may also include some defensive programming by allowing changes to only go to 0 or from 0. Recommendation:QSP-4 Schain ETH contract is supply limited Severity:Informational Fixed Status: File(s) affected: EthERC20.sol The ETH contract on Schain that acts as an analogue token for the native ETH token on mainnet is limited by a variable that cannot be increased beyond an initially declared . However, given that the supply of ETH is not hard limited, it means that this contract would not be able to mint beyond that value. Description:_capacity 120 * (10 ** 6) * (10 ** 18) Have some methods to change . Recommendation: _capacity QSP-5 Hardcoded addresses and associated methods with unknown results Severity: Informational Mitigated Status: , , , , , File(s) affected: LockAndDataForSchain.sol MessageProxyForSchain.sol LockAndDataOwnable.sol OwnableForSchain.sol PermissionsForSchain.sol TokenManager.sol There are some hardcoded addresses within the predeployed section, used within some of the key methods of the some of the contracts. As we are not able to see the logic that is predeployed and its' exact effects, we will not be able to certify methods utilizing these logic: Description:1. In LockAndDataForSchain.sol, the method. _checkPermitted 2. In LockAndDataForSchain.sol, the method. getEthERC20Address 3. In LockAndDataOwnable.sol, the method. getOwner 4. In MessageProxyForSchain.sol, the method. getChainID 5. In MessageProxyForSchain.sol, the method. getOwner 6. In MessageProxyForSchain.sol, the method. checkIsAuthorizedCaller 7. In OwnableForSchain.sol, the method. getOwner 8. In PermissionsForSchain.sol, the method. getLockAndDataAddress 9. In TokenManager.sol, the method. getChainID 10. In TokenManager.sol, the method . getProxyForSchainAddress The reaudit commit has refactored the approach but the issue remains the same that any logic approaching address is opaque to the audit unless there is an independent way for the auditors to retrieve and check the data on . Update:0xC033b369416c9Ecd8e4A07AaFA8b06b4107419E2 0x00c033b369416c9ecd8e4a07aafa8b06b4107419e2 From the Skale team : "One note about QSP-5, the hard coded address 0xC033b369416c9Ecd8e4A07AaFA8b06b4107419E2 refers to the predeployed address for SkaleFeatures contract. Searching the repo for that address will show you the deployment scripts, that make SkaleFeatures accessible to the schain IMA system. I believe with this info, the issue is effectively resolved." Update:Due to the zeal and information provided by the Skale team, we have decided to upgrade the status from to . It will remain the recommendation of the Quantstamp team that users independently verify that the hardcoded address has the expected contract code. Update:Unresolved Mitigated Automated Analyses Slither All of the results were checked through and were flagged as false positives. The following are best practices recommendations that should be adhered to : getChainID() should be declared external: - MessageProxyForSchain.getChainID() (predeployed/MessageProxyForSchain.sol#349-357) setOwner(address) should be declared external: - MessageProxyForSchain.setOwner(address) (predeployed/MessageProxyForSchain.sol#369-371) verifyOutgoingMessageData(uint256,address,address,address,uint256) should be declared external: - MessageProxyForSchain.verifyOutgoingMessageData(uint256,address,address,address,uint256) (predeployed/MessageProxyForSchain.sol#386-401) initialize(string,address) should be declared external: - MessageProxyForMainnet.initialize(string,address) (MessageProxyForMainnet.sol#398-403) verifyOutgoingMessageData(uint256,address,address,address,uint256) should be declared external: - MessageProxyForMainnet.verifyOutgoingMessageData(uint256,address,address,address,uint256) (MessageProxyForMainnet.sol#408-423) mint(address,uint256) should be declared external: - ERC20OnChain.mint(address,uint256) (predeployed/TokenFactory.sol#60-64) getLockAndDataAddress() should be declared external: - PermissionsForMainnet.getLockAndDataAddress() (PermissionsForMainnet.sol#70-72) logMessage(string) should be declared external: - SkaleFeatures.logMessage(string) (predeployed/SkaleFeatures.sol#60-62) logDebug(string) should be declared external: - SkaleFeatures.logDebug(string) (predeployed/SkaleFeatures.sol#64-66) logTrace(string) should be declared external: - SkaleFeatures.logTrace(string) (predeployed/SkaleFeatures.sol#68-70) logWarning(string) should be declared external: - SkaleFeatures.logWarning(string) (predeployed/SkaleFeatures.sol#72-74) logError(string) should be declared external: - SkaleFeatures.logError(string) (predeployed/SkaleFeatures.sol#76-78) logFatal(string) should be declared external: - SkaleFeatures.logFatal(string) (predeployed/SkaleFeatures.sol#80-82) getConfigVariableUint256(string) should be declared external: - SkaleFeatures.getConfigVariableUint256(string) (predeployed/SkaleFeatures.sol#84-97) getConfigVariableAddress(string) should be declared external: - SkaleFeatures.getConfigVariableAddress(string) (predeployed/SkaleFeatures.sol#99-112) getConfigVariableString(string) should be declared external: - SkaleFeatures.getConfigVariableString(string) (predeployed/SkaleFeatures.sol#114-126) concatenateStrings(string,string) should be declared external: - SkaleFeatures.concatenateStrings(string,string) (predeployed/SkaleFeatures.sol#128-148) getConfigPermissionFlag(address,string) should be declared external: - SkaleFeatures.getConfigPermissionFlag(address,string) (predeployed/SkaleFeatures.sol#150-165) name() should be declared external: - EthERC20.name() (predeployed/EthERC20.sol#84-86) symbol() should be declared external: - EthERC20.symbol() (predeployed/EthERC20.sol#92-94) decimals() should be declared external: - EthERC20.decimals() (predeployed/EthERC20.sol#109-111) increaseAllowance(address,uint256) should be declared external: - EthERC20.increaseAllowance(address,uint256) (predeployed/EthERC20.sol#194-197) decreaseAllowance(address,uint256) should be declared external: - EthERC20.decreaseAllowance(address,uint256) (predeployed/EthERC20.sol#213-220) Code Documentation 1. [FIXED] In EthERC20.sol::L48 to be consistent with other type declarations,-> . uint uint2562. In LockAndDataForSchain.sol::L234should be . sendEth sendETH 3. In LockAndDataForSchain.sol::L242should be . receiveEth receiveETH 4.In LockAndDataForSchain.sol::L250should be . getEthERC20Address getETH_ERC20Address 5. [FIXED] In LockAndDataForSchain.sol::L260-> . name and adress are permitted name and address are permitted 6. In TokenManager.sol::[L528,L521]-> . addEthCost addETHCost 7. In TokenManager.sol::L119-> . addEthCostWithoutAddress addETHCostWithoutAddress 8. [FIXED] In MessageProxyForMainnet.sol::L215, the commentshould be . msg.sender must be owner. msg.sender must be SKALE Node address. 9. [FIXED] In MessageProxyForMainnet.sol::L365,and commented out code should be removed. todo10. [FIXED] In MessageProxyForMainnet.sol::L286 -> . qual equal11. [FIXED] In MessageProxyForMainnet.sol::L258should be . Starning counter is not equal to incomin message counterStarting counter is not equal to incoming message counter Adherence to Best Practices 1. [FIXED] In DepositBox.sol, thevalue is used multiple times, but the constants themselves are never used seperately. It would be optimal to precalculate the value. GAS_AMOUNT_POST_MESSAGE * AVERAGE_TX_PRICE2. [FIXED] In EthERC20.sol, the functionis not used. _setupDecimals 3. [FIXED] In MessageProxyForSchain.sol::L276-277 is redundant as L275 already ensures that it will never execute.4. [FIXED] In LockAndDataForSchainERC20.sol, for consistency,should emit an event when a new ERC20 Token address is added. addERC20Token 5. [FIXED] In LockAndDataForSchainERC721.sol, for consistency,should emit an event when a new ERC721 Token address is added. addERC721Token 6. [FIXED] In LockAndDataForSchainERC20.sol, input validation in function. addERC20Token, addressERC20 7. [FIXED] In LockAndDataForSchainERC721.sol, input validation in function. addERC721Token, addressERC721 8. [FIXED] In TokenFactory.sol, input validation in function. constructor, erc20Module 9. In TokenManger.sol, input validation in function. constructor, newProxyAddress 10. [FIXED] In TokenManager.sol, to ensure consistent execution across all other functions, ensure that for all input for functions and for , to validate against zero address. contractThere[rawExitToMainERC20, rawTransferToSchainERC20, rawExitToMainERC721, rawTransferToSchainERC721] to [exitToMain, transferToSchain]11. [FIXED] In LockAndDataForMainnetERC20.sol, input validation in functionand . sendERC20, contractHere addERC20Token, addressERC20 12. [FIXED] In LockAndDataForMainnetERC721.sol, input validation in function and . sendERC721, contractHere addERC721Token, addressERC721 13. In MessageProxyForMainnet.sol, input validation in function and . initialize, newContractManager postOutgoingMessage, to Test Results Test Suite Results We were able to run the tests successfully in both initial and reaudit stages. The following results corresponds to the reaudit stage Contract: DepositBox Your project has Truffle migrations, which have to be turn into a fixture to run your tests with Buidler tests for `deposit` function ✓ should rejected with `Unconnected chain` when invoke `deposit` (102ms) ✓ should rejected with `SKALE chain name is incorrect` when invoke `deposit` (66ms) ✓ should rejected with `Not enough money` when invoke `deposit` (148ms) ✓ should invoke `deposit` without mistakes (174ms) ✓ should revert `Not allowed. in DepositBox` (53ms) tests with `ERC20` tests for `depositERC20` function ✓ should rejected with `Not allowed ERC20 Token` (172ms) ✓ should invoke `depositERC20` without mistakes (394ms) ✓ should invoke `depositERC20` with some ETH without mistakes (379ms) tests for `rawDepositERC20` function ✓ should rejected with `Not allowed ERC20 Token` when invoke `rawDepositERC20` (167ms) ✓ should invoke `rawDepositERC20` without mistakes (348ms) ✓ should invoke `rawDepositERC20` with some ETH without mistakes (319ms) tests with `ERC721` tests for `depositERC721` function ✓ should rejected with `Not allowed ERC721 Token` (150ms) ✓ should invoke `depositERC721` without mistakes (291ms) tests for `rawDepositERC721` function ✓ should rejected with `Not allowed ERC721 Token` (146ms) ✓ should invoke `rawDepositERC721` without mistakes (281ms) tests for `postMessage` function ✓ should rejected with `Message sender is invalid` (57ms) ✓ should rejected with message `Receiver chain is incorrect` when schainID=`mainnet` (134ms) ✓ should rejected with message `Receiver chain is incorrect` when `sender != ILockAndDataDB(lockAndDataAddress).tokenManagerAddresses(schainHash)` (118ms) ✓ should rejected with message `Not enough money to finish this transaction` (134ms) ✓ should rejected with message `Invalid data` (186ms) ✓ should rejected with message `Could not send money to owner` (192ms) ✓ should transfer eth (212ms) ✓ should transfer ERC20 token (602ms) ✓ should transfer ERC20 for RAW mode token (854ms) ✓ should transfer ERC721 token (1042ms) ✓ should transfer RawERC721 token (606ms) Contract: ERC20ModuleForMainnet ✓ should invoke `receiveERC20` with `isRaw==true` (115ms) ✓ should invoke `receiveERC20` with `isRaw==false` (199ms) ✓ should return `true` when invoke `sendERC20` with `to0==address(0)` (597ms) ✓ should return `true` when invoke `sendERC20` with `to0==ethERC20.address` (285ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==ethERC20.address` (246ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (287ms) Contract: ERC20ModuleForSchain ✓ should invoke `receiveERC20` with `isRaw==true` (253ms) ✓ should rejected with `ERC20 contract does not exist on SKALE chain.` with `isRaw==false` (133ms) ✓ should invoke `receiveERC20` with `isRaw==false` (399ms) ✓ should return `true` when invoke `sendERC20` with `to0==address(0)` (572ms) ✓ should return send ERC20 token twice (521ms) ✓ should return `true` for `sendERC20` with `to0==address(0)` and `contractAddreess==address(0)` (442ms) ✓ should be rejected with incorrect Minter when invoke `sendERC20` with `to0==ethERC20.address` (593ms) ✓ should return true when invoke `sendERC20` with `to0==ethERC20.address` (668ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==ethERC20.address` (394ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (429ms) Contract: ERC721ModuleForMainnet ✓ should invoke `receiveERC721` with `isRaw==true` ✓ should invoke `receiveERC721` with `isRaw==false` (55ms) ✓ should return `true` when invoke `sendERC721` with `to0==address(0)` (459ms) ✓ should return `true` when invoke `sendERC721` with `to0==eRC721OnChain.address` (324ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==eRC721OnChain.address` (124ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (207ms) Contract: ERC721ModuleForSchain ✓ should invoke `receiveERC721` with `isRaw==true` (84ms)✓ should rejected with `ERC721 contract does not exist on SKALE chain` with `isRaw==false` (127ms) ✓ should invoke `receiveERC721` with `isRaw==false` (390ms) ✓ should return `true` for `sendERC721` with `to0==address(0)` and `contractAddreess==address(0)` (502ms) ✓ should return `true` when invoke `sendERC721` with `to0==address(0)` (706ms) ✓ should return `true` when invoke `sendERC721` with `to0==eRC721OnChain.address` (377ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==eRC721OnChain.address` (205ms) ✓ should return `receiver` when invoke `getReceiver` with `to0==address(0)` (467ms) Contract: LockAndDataForMainnet ✓ should add wei to `lockAndDataForMainnet` (51ms) ✓ should check sendEth returned bool value (168ms) ✓ should work `sendEth` (112ms) ✓ should work `approveTransfer` (118ms) ✓ should work `getMyEth` (142ms) ✓ should rejected with `User has insufficient ETH` when invoke `getMyEth` (75ms) ✓ should rejected with `Not enough ETH. in `LockAndDataForMainnet.getMyEth`` when invoke `getMyEth` (131ms) ✓ should check contract without mistakes ✓ should rejected with `New address is equal zero` when invoke `getMyEth` (48ms) ✓ should rejected with `Contract is already added` when invoke `setContract` (47ms) ✓ should invoke addSchain without mistakes (91ms) ✓ should rejected with `SKALE chain is already set` when invoke `addSchain` (129ms) ✓ should rejected with `Incorrect Token Manager address` when invoke `addSchain` (64ms) ✓ should return true when invoke `hasSchain` (104ms) ✓ should return false when invoke `hasSchain` ✓ should invoke `removeSchain` without mistakes (216ms) ✓ should rejected with `SKALE chain is not set` when invoke `removeSchain` (160ms) Contract: LockAndDataForMainnetERC20 ✓ should rejected with `Not enough money` (71ms) ✓ should return `true` after invoke `sendERC20` (184ms) ✓ should return `token index` after invoke `addERC20Token` (369ms) Contract: LockAndDataForMainnetERC721 ✓ should NOT to send ERC721 to `to` when invoke `sendERC721` (145ms) ✓ should to send ERC721 to `to` when invoke `sendERC721` (240ms) ✓ should add ERC721 token when invoke `sendERC721` (135ms) Contract: LockAndDataForSchain ✓ should set EthERC20 address (109ms) ✓ should set contract (356ms) ✓ should add schain (217ms) ✓ should add deposit box (210ms) ✓ should add gas costs (126ms) ✓ should remove gas costs (184ms) ✓ should reduce gas costs (397ms) ✓ should send Eth (282ms) ✓ should receive Eth (235ms) ✓ should return true when invoke `hasSchain` (67ms) ✓ should return false when invoke `hasSchain` ✓ should return true when invoke `hasDepositBox` (63ms) ✓ should return false when invoke `hasDepositBox` ✓ should invoke `removeSchain` without mistakes (174ms) ✓ should rejected with `SKALE chain is not set` when invoke `removeSchain` (98ms) ✓ should work `addAuthorizedCaller` (66ms) ✓ should work `removeAuthorizedCaller` (62ms) ✓ should invoke `removeDepositBox` without mistakes (107ms) ✓ should rejected with `Deposit Box is not set` when invoke `removeDepositBox` (50ms) Contract: LockAndDataForSchain ✓ should set EthERC20 address (111ms) ✓ should set contract (439ms) ✓ should add schain (356ms) ✓ should add deposit box (252ms) ✓ should add gas costs (114ms) ✓ should reduce gas costs (409ms) ✓ should send Eth (246ms) ✓ should receive Eth (236ms) ✓ should return true when invoke `hasSchain` (72ms) ✓ should return false when invoke `hasSchain` ✓ should return true when invoke `hasDepositBox` (100ms) ✓ should return false when invoke `hasDepositBox` ✓ should invoke `removeSchain` without mistakes (115ms) ✓ should rejected with `SKALE chain is not set` when invoke `removeSchain` (130ms) ✓ should work `addAuthorizedCaller` (65ms) ✓ should work `removeAuthorizedCaller` (101ms) ✓ should invoke `removeDepositBox` without mistakes (120ms) ✓ should rejected with `Deposit Box is not set` when invoke `removeDepositBox` (59ms) Contract: LockAndDataForSchainERC20 ✓ should invoke `sendERC20` without mistakes (232ms) ✓ should rejected with `Amount not transfered` (69ms) ✓ should return `true` after invoke `receiveERC20` (218ms) ✓ should set `ERC20Tokens` and `ERC20Mapper` (106ms) Contract: LockAndDataForSchainERC721 ✓ should invoke `sendERC721` without mistakes (169ms) ✓ should rejected with `Token not transfered` after invoke `receiveERC721` (128ms) ✓ should return `true` after invoke `receiveERC721` (518ms) ✓ should set `ERC721Tokens` and `ERC721Mapper` (94ms) Contract: MessageProxy MessageProxyForMainnet for mainnet ✓ should detect registration state by `isConnectedChain` function (210ms) ✓ should add connected chain (135ms) ✓ should remove connected chain (258ms) ✓ should post outgoing message (191ms) ✓ should post incoming messages (272ms) ✓ should get outgoing messages counter (181ms) ✓ should get incoming messages counter (499ms) ✓ should move incoming counter (160ms) ✓ should get incoming messages counter (734ms) MessageProxyForSchain for schain ✓ should detect registration state by `isConnectedChain` function (87ms) ✓ should add connected chain (124ms) ✓ should remove connected chain (237ms) ✓ should post outgoing message (269ms) ✓ should post incoming messages (474ms) ✓ should get outgoing messages counter (169ms) ✓ should get incoming messages counter (508ms) Contract: TokenFactory ✓ should createERC20 (173ms) ✓ should createERC721 (203ms) Contract: ERC20OnChain ✓ should invoke `totalSupplyOnMainnet` ✓ should rejected with `Call does not go from ERC20Module` when invoke `setTotalSupplyOnMainnet` (53ms) ✓ should invoke `setTotalSupplyOnMainnet` (103ms) ✓ should invoke `_mint` as internal (63ms) ✓ should invoke `burn` (107ms) ✓ should invoke `burnFrom` (157ms) Contract: ERC721OnChain ✓ should invoke `mint` (71ms) ✓ should invoke `burn` (143ms) ✓ should reject with `ERC721Burnable: caller is not owner nor approved` when invoke `burn` (163ms) ✓ should invoke `setTokenURI` (106ms) Contract: TokenManager ✓ should send Eth to somebody on Mainnet, closed to Mainnet, called by schain (305ms) ✓ should transfer to somebody on schain Eth and some data (566ms) ✓ should add Eth cost (428ms) ✓ should remove Eth cost (502ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `exitToMainERC20` (376ms) ✓ should rejected with `Not enough gas sent` when invoke `exitToMainERC20` (394ms) ✓ should invoke `exitToMainERC20` without mistakes (794ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `rawExitToMainERC20` (364ms) ✓ should rejected with `Not enough gas sent` when invoke `rawExitToMainERC20` (400ms) ✓ should revert `Not allowed. in TokenManager` ✓ should invoke `rawExitToMainERC20` without mistakes (733ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `transferToSchainERC20` (611ms) ✓ should invoke `transferToSchainERC20` without mistakes (706ms) ✓ should invoke `rawTransferToSchainERC20` without mistakes (715ms) ✓ should rejected with `Not allowed ERC20 Token` when invoke `rawTransferToSchainERC20` (639ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `exitToMainERC721` (674ms) ✓ should rejected with `Not enough gas sent` when invoke `exitToMainERC721` (668ms) ✓ should invoke `exitToMainERC721` without mistakes (831ms) ✓ should invoke `rawExitToMainERC721` without mistakes (719ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `rawExitToMainERC721` (686ms) ✓ should rejected with `Not enough gas sent` when invoke `rawExitToMainERC721` (671ms) ✓ should invoke `transferToSchainERC721` without mistakes (773ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `transferToSchainERC721` (652ms) ✓ should invoke `rawTransferToSchainERC721` without mistakes (759ms) ✓ should rejected with `Not allowed ERC721 Token` when invoke `rawTransferToSchainERC721` (646ms) tests for `postMessage` function ✓ should rejected with `Not a sender` (67ms) ✓ should be Error event with message `Receiver chain is incorrect` when schainID=`mainnet` (285ms) ✓ should be Error event with message `Invalid data` (273ms) ✓ should transfer eth (447ms) ✓ should rejected with `Incorrect receiver` when `eth` transfer (439ms) ✓ should transfer ERC20 token (855ms) ✓ should transfer rawERC20 token (1099ms) ✓ should transfer ERC721 token (849ms) ✓ should transfer rawERC721 token (845ms) 186 passing (4m)Code Coverage Whilst there exists tests which provides code coverage up to a passable level, it is our strong recommendation that all code coverage be raised to the acceptable 100% level for all branches. File % Stmts % Branch % Funcs % Lines Uncovered Lines contracts/ 94.35 71.08 92.86 92.65 DepositBox.sol 100 78.79 100 100 ERC20ModuleForMainnet.sol 97.3 70 100 97.37 105 ERC721ModuleForMainnet.sol 100 87.5 100 100 LockAndDataForMainnet.sol 82.86 65.38 91.67 81.58 … 91,93,96,97 LockAndDataForMainnetERC20.sol 100 62.5 100 100 LockAndDataForMainnetERC721.sol 100 62.5 100 100 MessageProxyForMainnet.sol 89.55 63.89 94.12 84.72 … 535,536,539 PermissionsForMainnet.sol 62.5 50 50 60 56,57,71,82 contracts/ interfaces/ 100 100 100 100 IContractManager.sol 100 100 100 100 IERC20Module.sol 100 100 100 100 IERC721Module.sol 100 100 100 100 IMessageProxy.sol 100 100 100 100 ISchainsInternal.sol 100 100 100 100 contracts/ predeployed/ 86.74 70.36 85.16 85.79 ERC20ModuleForSchain.sol 100 92.86 100 100 ERC721ModuleForSchain.sol 100 91.67 100 100 EthERC20.sol 92.16 57.14 90.48 92.16 191,192,210,215 LockAndDataForSchain.sol 82.72 80.77 96.43 83.53 … 349,350,352 LockAndDataForSchainERC20.sol 100 75 100 100 LockAndDataForSchainERC721.sol 100 66.67 100 100 MessageProxyForSchain.sol 63.29 54 63.64 61.63 … 456,457,460 OwnableForSchain.sol 66.67 62.5 83.33 72.73 66,77,86 PermissionsForSchain.sol 80 50 100 83.33 63 SkaleFeatures.sol 0 100 0 0 … 140,141,143 TokenFactory.sol 100 64.29 100 100 TokenManager.sol 98.36 71.57 100 98.32 558,573 All files 89.45 70.63 87.56 88.22 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 a581162e7409df3a9f5f72b4350eff7a1b4b0a46fdf155f6d5d832eaf82a514a ./IMA/proxy/contracts/PermissionsForMainnet.sol c30eb440430f7a314575fa9e199186f4beca58ee13d8ab1b63893ea559928088 ./IMA/proxy/contracts/MessageProxyForMainnet.sol 56463900f833cca487f4624a7bdd66f6dae6ad046fd60f429e146cf1844b1ae1 ./IMA/proxy/contracts/ERC721ModuleForMainnet.sol f958dc1a1a4915a88aa5af6a16c8195fe6de16487421ee625e073bd3aa5eaa0a ./IMA/proxy/contracts/ERC20ModuleForMainnet.sol f68cb3d41c8632cca0a232513a188b947effef88dafe64651be8834b53d3c5c7 ./IMA/proxy/contracts/LockAndDataForMainnet.sol c5af2b09f10e237cffd5f889849d63315531e900e6fd1d7a2f961c6c19ea6e06 ./IMA/proxy/contracts/DepositBox.sol e3ff22a8995e628d1e05e99edcfc9a1a2016a337e06f9a4c69196233abce6e45 ./IMA/proxy/contracts/LockAndDataForMainnetERC20.sol c4362ddc47d59c3cadb24fd1b02128ed57b86347c118355ac284a568a52326e0 ./IMA/proxy/contracts/LockAndDataForMainnetERC721.sol 595d60fef2ebc7636f86da980a0bc17b73a71aefc40d354583dbdc9e1dc85daf ./IMA/proxy/contracts/predeployed/LockAndDataForSchainERC721.sol f767a8c51b9ce643bad75038b1fb967315cc95300abb4123327c3498af457889 ./IMA/proxy/contracts/predeployed/EthERC20.sol dcd8e5cfcbedc8fbb57d89c5bafd73983c1b53af96bd8d9baac7999ad0ff0484 ./IMA/proxy/contracts/predeployed/ERC721ModuleForSchain.sol a9d832d8379d078e3243c6d8d1dc5bf1b9da2a9f3fb1415742d6cb501a5b4553 ./IMA/proxy/contracts/predeployed/SkaleFeatures.sol 24ed25959a167758b740280ce2c764842e1e4f66d09e0b9aca3a38973e2d1f97 ./IMA/proxy/contracts/predeployed/TokenManager.sol c40815ae415cb7195fa490bb1f210cf46d8a5f98090e0b80f86589a95787f0d7 ./IMA/proxy/contracts/predeployed/ERC20ModuleForSchain.sol 1c2ea3213b643a27989da484b1e710999a48ceed2e03a0a2f43ad851500ebe84 ./IMA/proxy/contracts/predeployed/OwnableForSchain.sol 0a7f8b0fc3633c649ee88720ddb5f3afda9e25c646ab2d815cc1ac52a82ded3f ./IMA/proxy/contracts/predeployed/MessageProxyForSchain.sol 0f6335e2b01d4d9eccada33da333b7bffd084f1277de28930bbf2d02443d4ae7 ./IMA/proxy/contracts/predeployed/PermissionsForSchain.sol 1dffd83fa2735b0b1300ddad511048b709d9961ae76fbba569b4dbd693bb1ce4 ./IMA/proxy/contracts/predeployed/LockAndDataForSchainERC20.sol 29880794a37dcac5ec49c10701f21bb6041dbdd06e38f0dd658bebfcebf473f2 ./IMA/proxy/contracts/predeployed/LockAndDataForSchain.sol e9932454e8bd531e6d286a345272f6e91fa4a1a51bf957b6c22a5e5f36b0b065 ./IMA/proxy/contracts/predeployed/TokenFactory.sol Tests 0c773f9f428d7653f3cb703db8b4837194c372323682b1853db3a7b0521867a0 ./IMA/proxy/contracts/test/TestSchains.sol c1a6440a6517a7679d32397f564ad9d0da71a90f7ca6656cd3432fd55acf00a9 ./IMA/proxy/contracts/test/LockAndDataForMainnetWorkaround.sol 444018e4c5b9e392d9692a693aecc320d46acf2fedad1e0cf70acb586ba08a3e ./IMA/proxy/contracts/test/TestContractManager.sol 50164312e001184f94fd273b06a526a5b13d59bb1043b3b285c9576c22277199 ./IMA/proxy/contracts/test/LockAndDataForSchainWorkaround.sol f736320870ae68daf01e28ef15fecc22012ad57bd211e8564cd66f55b91367d0 ./IMA/proxy/contracts/test/TestSchainsInternal.sol 550d7a3578e5b48ae010dd15f3d99a5829ab0ed78a09edb0649a668854ddef8a ./IMA/proxy/test/TokenFactory.spec.ts 22a0f39473f0037cf21988638eb5e93e57a10f3fd5fb107cd906054bf27f80ea ./IMA/proxy/test/LockAndDataForSchain.spec.ts 7dde350053fde8a66be59e4d2c843458057a257ac6db45281f0e125246f81e03 ./IMA/proxy/test/ERC20ModuleForSchain.spec.ts a324105ee84e934b8b95231864d5247d97904f6a49fe14cba1554687ac2c96a6 ./IMA/proxy/test/ERC20ModuleForMainnet.spec.ts c8520091ac471813239af2b2c29abfbd3ddbfb982a93a165ae36da411af82cde ./IMA/proxy/test/LockAndDataForSchainERC721.spec.ts d5bea9f0badf80af6a6cd3db97c61563ff3db517dfaaf07aad52914b749c4b73 ./IMA/proxy/test/ERC721ModuleForMainnet.spec.ts db738bce93d60527695f1b712f9a8adb4d9027a89e551aea3ea97e47ed2f4989 ./IMA/proxy/test/LockAndDataForSchain.ts 1cc7afa874135961b7d19f79fccf1bd298b95ac250b18dd2a4fa52a36db580f9 ./IMA/proxy/test/LockAndDataForMainnet.spec.ts 98829fbff58d80f7c01479ba683b1422297004059df06d4e6a0fe7f861cb29a5 ./IMA/proxy/test/MessageProxy.ts 7216cdccccd431b7cc69e22a033c665439cc5b4ecb9f19896f7b94f1c35adf4a ./IMA/proxy/test/LockAndDataForMainnetERC20.spec.ts ede56d39f6e06dade0b2cba440958037f0786b3b292f18b4b5b3f493ab409bcb ./IMA/proxy/test/LockAndDataForSchainERC20.spec.ts 089a8b6b66c70ea027b275295152af0da87bfdf556754b2c7771eea9095f720e ./IMA/proxy/test/ERC721ModuleForSchain.spec.ts 38ab965ac85c122bcce1c81095394668d104d665e7205b5c1575824903635ff8 ./IMA/proxy/test/DepositBox.spec.ts 00bbcdc73dadad90a67d8e0d0ee2a0b88721bf52255105795b1d21dacd2306c1 ./IMA/proxy/test/LockAndDataForMainnetERC721.spec.ts 47d4300744251d5e525a57c1f3ef9bebbd7d47179aca60befa4f13fad5c27634 ./IMA/proxy/test/TokenManager.spec.ts e44d967443fcc1efaf477308fca44c5cf85618f0d08c7bda09fdd448e40b8d53 ./IMA/proxy/test/utils/helper.ts dd3c4dd574f0aea1c9854c428d768f9d3e1ae579a5e4f1e44fd5cb128039784e ./IMA/proxy/test/utils/command_line.ts f6876bdbdcb522a00e3672b9ebfc3a5f9f6f4823c0dec67c7d62fa3b9c59f7de ./IMA/proxy/test/utils/time.ts 319269694633baacde87d3d7178888d172812f01e714646435f22d0673b2a599 ./IMA/proxy/test/utils/deploy/lockAndDataForMainnetERC721.ts 259298babbc37f7f980911a37716cb0d1deb94f8a2f5827c65a35d2b6314e866 ./IMA/proxy/test/utils/deploy/lockAndDataForMainnet.ts 9c6e1427ab9a7dd7c9a111746fd1c4e7740e56a4cfaec849951fdc42f33cb934 ./IMA/proxy/test/utils/deploy/messageProxyForMainnet.ts 13eac3123265b210d829cba03c1c0c5901aa4f9a2982a16796c049001d5f1a51 ./IMA/proxy/test/utils/deploy/erc721ModuleForMainnet.ts 231ebc8de6d392832df586df7dfd8623f344fb6058f6f056f76e41311aa54e31 ./IMA/proxy/test/utils/deploy/erc20ModuleForMainnet.ts 87d2f2f0ced1a0ea5cece4c6f1ffee429f4510e5c34cd8eb00b8ce2c45fa9ab4 ./IMA/proxy/test/utils/deploy/depositBox.ts b99061587a7ca6579456fdaca85439d40b20005d9174032773d7f1a62f19c0d8 ./IMA/proxy/test/utils/deploy/lockAndDataForMainnetERC20.ts Changelog2020-11-25 - Initial report •2021-01-08 - Reaudit commit taken at •ee72736 2021-01-14 - Tests results updated along with coverage. Also explicitly stated Best Practices and Documentation statuses when fixed or mitigated, along with adding one new documentation issue and removing stamp for addressing all best practices. •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 Proxy Contracts Audit
Issues Count of Minor/Moderate/Major/Critical - High Risk: 1 (1 Resolved) - Medium Risk: 0 (0 Resolved) - Low Risk: 2 (1 Resolved) - Informational Risk: 2 (2 Resolved) - Undetermined Risk: 0 (0 Resolved) Minor Issues - Problem: None - Fix: None Moderate - Problem: None - Fix: None Major - Problem: None - Fix: None Critical - 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. - Fix: Adjusted program implementation, requirements or constraints to eliminate the risk. Observations - We have found the codebase to be of good quality with well named methods and inline documentation. - There are some room for improvement with regards to documentation consistency. Conclusion We urge the Skale team to address the 5 issues of varying severities and consider our recommendations with which to go about fixing it. Issues Count of Minor/Moderate/Major/Critical Minor: 1 Moderate: 1 Major: 0 Critical: 0 Minor Issues 2.a Problem: Integer Overflow / Underflow 2.b Fix: Fixed Moderate 3.a Problem: Race Conditions / Front-Running 3.b Fix: Acknowledged Major None Critical None Observations • 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. • 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, Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: Integer Overflow/Underflow (QSP-2) 2.b Fix: Use unsigned integers with a range of 0-2^256 Observations: 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. Conclusion: It is recommended to use OpenZeppelin's implementation instead of rolling a new owner-logic contract. Otherwise, ensure that setOwner is either set to internal or armed with some access control.
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IRelayEncoder.sol"; import "../interfaces/IxTokens.sol"; import "../interfaces/IXcmTransactor.sol"; import "../interfaces/ILedger.sol"; contract Controller { // ledger controller account uint16 public rootDerivativeIndex; // relay side account id bytes32 public relayAccount; // vKSM precompile IERC20 internal vKSM; // relay call builder precompile IRelayEncoder internal relayEncoder; // xcm transactor precompile IXcmTransactor internal xcmTransactor; // xTokens precompile IxTokens internal xTokens; // Second layer derivative-proxy account to index mapping(address => uint16) public senderToIndex; mapping(uint16 => bytes32) public indexToAccount; uint16 public tododelete; enum WEIGHT { AS_DERIVATIVE, // 410_000_000 BOND_BASE, // 600_000_000 BOND_EXTRA_BASE, // 1_100_000_000 UNBOND_BASE, // 1_250_000_000 WITHDRAW_UNBONDED_BASE, // 500_000_000 WITHDRAW_UNBONDED_PER_UNIT, // 60_000 REBOND_BASE, // 1_200_000_000 REBOND_PER_UNIT, // 40_000 CHILL_BASE, // 900_000_000 NOMINATE_BASE, // 1_000_000_000 NOMINATE_PER_UNIT, // 31_000_000 TRANSFER_TO_PARA_BASE, // 700_000_000 TRANSFER_TO_RELAY_BASE // 4_000_000_000 } uint64 public MAX_WEIGHT;// = 1_835_300_000; uint64[] public weights; event WeightUpdated ( uint8 index, uint64 newValue ); event Bond ( address caller, bytes32 stash, bytes32 controller, uint256 amount ); event BondExtra ( address caller, bytes32 stash, uint256 amount ); event Unbond ( address caller, bytes32 stash, uint256 amount ); event Rebond ( address caller, bytes32 stash, uint256 amount ); event Withdraw ( address caller, bytes32 stash ); event Nominate ( address caller, bytes32 stash, bytes32[] validators ); event Chill ( address caller, bytes32 stash ); event TransferToRelaychain ( address from, bytes32 to, uint256 amount ); event TransferToParachain ( bytes32 from, address to, uint256 amount ); modifier onlyRegistred() { require(senderToIndex[msg.sender] != 0, "sender isn't registred"); _; } function initialize() external {} //stub /** * @notice Initialize ledger contract. * @param _rootDerivativeIndex - stash account id * @param _relayAccount - controller account id * @param _vKSM - vKSM contract address * @param _relayEncoder - relayEncoder(relaychain calls builder) contract address * @param _xcmTransactor - xcmTransactor(relaychain calls relayer) contract address * @param _xTokens - minimal allowed nominator balance */ function init( uint16 _rootDerivativeIndex, bytes32 _relayAccount, address _vKSM, address _relayEncoder, address _xcmTransactor, address _xTokens ) external { relayAccount = _relayAccount; rootDerivativeIndex = _rootDerivativeIndex; vKSM = IERC20(_vKSM); relayEncoder = IRelayEncoder(_relayEncoder); xcmTransactor = IXcmTransactor(_xcmTransactor); xTokens = IxTokens(_xTokens); } function getWeight(WEIGHT weightType) public returns(uint64) { return weights[uint256(weightType)]; } function setMaxWeight(uint64 maxWeight) external { MAX_WEIGHT = maxWeight; } function setWeights( uint128[] calldata _weights ) external { require(_weights.length == uint256(type(WEIGHT).max) + 1, "wrong weights size"); for (uint256 i = 0; i < _weights.length; ++i) { if ((_weights[i] >> 64) > 0) { if (weights.length == i) { weights.push(0); } weights[i] = uint64(_weights[i]); emit WeightUpdated(uint8(i), weights[i]); } } } function newSubAccount(uint16 index, bytes32 accountId, address paraAddress) external { require(indexToAccount[index + 1] == bytes32(0), "already registred"); senderToIndex[paraAddress] = index + 1; indexToAccount[index + 1] = accountId; } function nominate(bytes32[] calldata validators) external onlyRegistred { uint256[] memory convertedValidators = new uint256[](validators.length); for (uint256 i = 0; i < validators.length; ++i) { convertedValidators[i] = uint256(validators[i]); } callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.NOMINATE_BASE) + getWeight(WEIGHT.NOMINATE_PER_UNIT) * uint64(validators.length), relayEncoder.encode_nominate(convertedValidators) ); emit Nominate(msg.sender, getSenderAccount(), validators); } function bond(bytes32 controller, uint256 amount) external onlyRegistred { callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.BOND_BASE), relayEncoder.encode_bond(uint256(controller), amount, bytes(hex"00")) ); emit Bond(msg.sender, getSenderAccount(), controller, amount); } function bondExtra(uint256 amount) external onlyRegistred { callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.BOND_EXTRA_BASE), relayEncoder.encode_bond_extra(amount) ); emit BondExtra(msg.sender, getSenderAccount(), amount); } function unbond(uint256 amount) external onlyRegistred { callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.UNBOND_BASE), relayEncoder.encode_unbond(amount) ); emit Unbond(msg.sender, getSenderAccount(), amount); } function withdrawUnbonded() external onlyRegistred { callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.WITHDRAW_UNBONDED_BASE) + getWeight(WEIGHT.WITHDRAW_UNBONDED_PER_UNIT) * 10, relayEncoder.encode_withdraw_unbonded(10/* TODO fix*/) ); emit Withdraw(msg.sender, getSenderAccount()); } function rebond(uint256 amount) external onlyRegistred { callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.REBOND_BASE) + getWeight(WEIGHT.REBOND_PER_UNIT) * 10 /*TODO fix*/, relayEncoder.encode_rebond(amount) ); emit Rebond(msg.sender, getSenderAccount(), amount); } function chill() external onlyRegistred { callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.CHILL_BASE), relayEncoder.encode_chill() ); emit Chill(msg.sender, getSenderAccount()); } function transferToParachain(uint256 amount) external onlyRegistred { // to - msg.sender, from - getSenderIndex() callThroughDerivative( getSenderIndex(), getWeight(WEIGHT.TRANSFER_TO_PARA_BASE), encodeReverseTransfer(msg.sender, amount) ); emit TransferToParachain(getSenderAccount(), msg.sender, amount); } function transferToRelaychain(uint256 amount) external onlyRegistred { // to - getSenderIndex(), from - msg.sender vKSM.transferFrom(msg.sender, address(this), amount); IxTokens.Multilocation memory destination; destination.parents = 1; destination.interior = new bytes[](1); destination.interior[0] = bytes.concat(bytes1(hex"01"), getSenderAccount(), bytes1(hex"00")); // X2, NetworkId: Any xTokens.transfer(address(vKSM), amount + 18900000000, destination, getWeight(WEIGHT.TRANSFER_TO_RELAY_BASE)); emit TransferToRelaychain(msg.sender, getSenderAccount(), amount); } function getSenderIndex() internal returns(uint16) { return senderToIndex[msg.sender] - 1; } function getSenderAccount() internal returns(bytes32) { return indexToAccount[senderToIndex[msg.sender]]; } function callThroughDerivative(uint16 index, uint64 weight, bytes memory call) internal { bytes memory le_index = new bytes(2); le_index[0] = bytes1(uint8(index)); le_index[1] = bytes1(uint8(index >> 8)); uint64 total_weight = weight + getWeight(WEIGHT.AS_DERIVATIVE); require(total_weight <= MAX_WEIGHT, "too much weight"); xcmTransactor.transact_through_derivative(0, rootDerivativeIndex, address(vKSM), total_weight, bytes.concat(hex"1001", le_index, call) ); } function encodeReverseTransfer(address to, uint256 amount) internal returns(bytes memory) { return bytes.concat( hex"630201000100a10f0100010300", abi.encodePacked(to), hex"010400000000", scaleCompactUint(amount), hex"00000000" ); } function toLeBytes(uint256 value, uint256 len) internal returns(bytes memory) { bytes memory out = new bytes(len); for (uint256 idx = 0; idx < len; ++idx) { out[idx] = bytes1(uint8(value)); value = value >> 8; } return out; } function scaleCompactUint(uint256 value) internal returns(bytes memory) { if (value < 1<<6) { return toLeBytes(value << 2, 1); } else if(value < 1 << 14) { return toLeBytes((value << 2) + 1, 2); } else if(value < 1 << 30) { return toLeBytes((value << 2) + 2, 4); } else { uint256 numBytes = 0; { uint256 m = value; for (; numBytes < 256 && m != 0; ++numBytes) { m = m >> 8; } } bytes memory out = new bytes(numBytes + 1); out[0] = bytes1(uint8(((numBytes - 4) << 2) + 3)); for (uint256 i = 0; i < numBytes; ++i) { out[i + 1] = bytes1(uint8(value & 0xFF)); value = value >> 8; } return out; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../interfaces/IOracleMaster.sol"; import "../interfaces/ILedger.sol"; import "../interfaces/IController.sol"; import "../interfaces/IAuthManager.sol"; import "./stKSM.sol"; contract Lido is stKSM, Initializable { using Clones for address; using SafeCast for uint256; // Records a deposit made by a user event Deposited(address indexed sender, uint256 amount); // Created redeem order event Redeemed(address indexed receiver, uint256 amount); // Claimed vKSM tokens back event Claimed(address indexed receiver, uint256 amount); // Fee was updated event FeeSet(uint16 fee, uint16 feeOperatorsBP, uint16 feeTreasuryBP, uint16 feeDevelopersBP); // Rewards distributed event Rewards(address ledger, uint256 rewards, uint256 balance); // Rewards distributed event Losses(address ledger, uint256 losses, uint256 balance); // Added new ledger event LedgerAdd( address addr, bytes32 stashAccount, bytes32 controllerAccount, uint256 share ); // Ledger removed event LedgerRemove( address addr ); // Ledger share setted event LedgerSetShare( address addr, uint256 share ); // sum of all deposits and rewards uint256 private fundRaisedBalance; struct Claim { uint256 balance; uint64 timeout; } // one claim for account mapping(address => Claim[]) public claimOrders; // pending claims total uint256 public pendingClaimsTotal; // Ledger accounts address[] private ledgers; // Ledger address by stash account id mapping(bytes32 => address) private ledgerByStash; // Map to check ledger existence by address mapping(address => uint256) private ledgerByAddress; // Ledger shares map mapping(address => uint256) public ledgerShares; // Sum of all ledger shares uint256 public ledgerSharesTotal; // haven't executed buffrered deposits uint256 public bufferedDeposits; // haven't executed buffrered redeems uint256 public bufferedRedeems; // Ledger stakes mapping(address => uint256) public ledgerStake; // vKSM precompile IERC20 public vKSM; // controller address public controller; // auth manager contract address address public AUTH_MANAGER; // Maximum number of ledgers uint256 public MAX_LEDGERS_AMOUNT; // Who pay off relay chain transaction fees bytes32 public GARANTOR; /** fee interest in basis points. It's packed uint256 consist of three uint16 (total_fee, treasury_fee, developers_fee). where total_fee = treasury_fee + developers_fee + 3000 (3% operators fee) */ Types.Fee private FEE; // ledger clone template contract address public LEDGER_CLONE; // oracle master contract address public ORACLE_MASTER; // relay spec Types.RelaySpec public RELAY_SPEC; // developers fund address public developers; // treasury fund address public treasury; /** default interest value in base points. */ uint16 internal constant DEFAULT_DEVELOPERS_FEE = 140; uint16 internal constant DEFAULT_OPERATORS_FEE = 300; uint16 internal constant DEFAULT_TREASURY_FEE = 560; // Missing member index uint256 internal constant MEMBER_NOT_FOUND = type(uint256).max; // Spec manager role bytes32 internal constant ROLE_SPEC_MANAGER = keccak256("ROLE_SPEC_MANAGER"); // Pause manager role bytes32 internal constant ROLE_PAUSE_MANAGER = keccak256("ROLE_PAUSE_MANAGER"); // Fee manager role bytes32 internal constant ROLE_FEE_MANAGER = keccak256("ROLE_FEE_MANAGER"); // Oracle manager role bytes32 internal constant ROLE_ORACLE_MANAGER = keccak256("ROLE_ORACLE_MANAGER"); // Ledger manager role bytes32 internal constant ROLE_LEDGER_MANAGER = keccak256("ROLE_LEDGER_MANAGER"); // Stake manager role bytes32 internal constant ROLE_STAKE_MANAGER = keccak256("ROLE_STAKE_MANAGER"); // Treasury manager role bytes32 internal constant ROLE_TREASURY = keccak256("ROLE_SET_TREASURY"); // Developers address change role bytes32 internal constant ROLE_DEVELOPERS = keccak256("ROLE_SET_DEVELOPERS"); // max amount of claims in parallel uint16 internal constant MAX_CLAIMS = 10; modifier auth(bytes32 role) { require(IAuthManager(AUTH_MANAGER).has(role, msg.sender), "LIDO: UNAUTHORIZED"); _; } /** * @notice Initialize lido contract. * @param _authManager - auth manager contract address * @param _vKSM - vKSM contract address * @param _controller - relay controller address * @param _developers - devs address * @param _treasury - treasury address */ function initialize( address _authManager, address _vKSM, address _controller, address _developers, address _treasury ) external initializer { vKSM = IERC20(_vKSM); controller = _controller; AUTH_MANAGER = _authManager; MAX_LEDGERS_AMOUNT = 200; Types.Fee memory _fee; _fee.total = DEFAULT_OPERATORS_FEE + DEFAULT_DEVELOPERS_FEE + DEFAULT_TREASURY_FEE; _fee.operators = DEFAULT_OPERATORS_FEE; _fee.developers = DEFAULT_DEVELOPERS_FEE; _fee.treasury = DEFAULT_TREASURY_FEE; FEE = _fee; // SWC-Presence of unused variables: L202 GARANTOR = 0x00; treasury = _treasury; developers =_developers; } /** * @notice Stub fallback for native token, always reverting */ fallback() external { revert("FORBIDDEN"); } /** * @notice Set treasury address to '_treasury' */ function setTreasury(address _treasury) external auth(ROLE_TREASURY) { treasury = _treasury; } /** * @notice Set developers address to '_developers' */ function setDevelopers(address _developers) external auth(ROLE_DEVELOPERS) { developers = _developers; } /** * @notice Return unbonded tokens amount for user * @param _holder - user account for whom need to calculate unbonding * @return waiting - amount of tokens which are not unbonded yet * @return unbonded - amount of token which unbonded and ready to claim */ function getUnbonded(address _holder) external view returns (uint256 waiting, uint256 unbonded) { uint256 waitingToUnbonding = 0; uint256 readyToClaim = 0; Claim[] storage orders = claimOrders[_holder]; for (uint256 i = 0; i < orders.length; ++i) { if (orders[i].timeout < block.timestamp) { readyToClaim += orders[i].balance; } else { waitingToUnbonding += orders[i].balance; } } return (waitingToUnbonding, readyToClaim); } /** * @notice Return relay chain stash account addresses * @return Array of bytes32 relaychain stash accounts */ function getStashAccounts() public view returns (bytes32[] memory) { bytes32[] memory _stashes = new bytes32[](ledgers.length); for (uint i = 0; i < ledgers.length; i++) { _stashes[i] = bytes32(ILedger(ledgers[i]).stashAccount()); } return _stashes; } /** * @notice Return ledger contract addresses * @dev Each ledger contract linked with single stash account on the relaychain side * @return Array of ledger contract addresses */ function getLedgerAddresses() public view returns (address[] memory) { return ledgers; } /** * @notice Return ledger address by stash account id * @dev If ledger not found function returns ZERO address * @param _stashAccount - relaychain stash account id * @return Linked ledger contract address */ function findLedger(bytes32 _stashAccount) external view returns (address) { return ledgerByStash[_stashAccount]; } /** * @notice Return vKSM amount available for stake by ledger * @dev If we have balance less than pendingClaimsTotal that means * that ledgers already have locked KSMs */ function avaliableForStake() external view returns(uint256) { uint256 freeBalance = vKSM.balanceOf(address(this)); return freeBalance < pendingClaimsTotal ? 0 : freeBalance - pendingClaimsTotal; } /** * @notice Set relay chain spec, allowed to call only by ROLE_SPEC_MANAGER * @dev if some params are changed function will iterate over oracles and ledgers, be careful * @param _relaySpec - new relaychain spec */ function setRelaySpec(Types.RelaySpec calldata _relaySpec) external auth(ROLE_SPEC_MANAGER) { require(ORACLE_MASTER != address(0), "LIDO: ORACLE_MASTER_UNDEFINED"); require(_relaySpec.genesisTimestamp > 0, "LIDO: BAD_GENESIS_TIMESTAMP"); require(_relaySpec.secondsPerEra > 0, "LIDO: BAD_SECONDS_PER_ERA"); require(_relaySpec.unbondingPeriod > 0, "LIDO: BAD_UNBONDING_PERIOD"); require(_relaySpec.maxValidatorsPerLedger > 0, "LIDO: BAD_MAX_VALIDATORS_PER_LEDGER"); //TODO loop through ledgerByAddress and oracles if some params changed RELAY_SPEC = _relaySpec; IOracleMaster(ORACLE_MASTER).setRelayParams(_relaySpec.genesisTimestamp, _relaySpec.secondsPerEra); } /** * @notice Set oracle master address, allowed to call only by ROLE_ORACLE_MANAGER and only once * @dev After setting non zero address it cannot be changed more * @param _oracleMaster - oracle master address */ function setOracleMaster(address _oracleMaster) external auth(ROLE_ORACLE_MANAGER) { require(ORACLE_MASTER == address(0), "LIDO: ORACLE_MASTER_ALREADY_DEFINED"); ORACLE_MASTER = _oracleMaster; IOracleMaster(ORACLE_MASTER).setLido(address(this)); } /** * @notice Set new ledger clone contract address, allowed to call only by ROLE_LEDGER_MANAGER * @dev After setting new ledger clone address, old ledgers won't be affected, be careful * @param _ledgerClone - ledger clone address */ function setLedgerClone(address _ledgerClone) external auth(ROLE_LEDGER_MANAGER) { LEDGER_CLONE = _ledgerClone; } /** * @notice Set new lido fee, allowed to call only by ROLE_FEE_MANAGER * @param _feeOperators - Operators percentage in basis points. It's always 3% * @param _feeTreasury - Treasury fund percentage in basis points * @param _feeDevelopers - Developers percentage in basis points */ function setFee(uint16 _feeOperators, uint16 _feeTreasury, uint16 _feeDevelopers) external auth(ROLE_FEE_MANAGER) { Types.Fee memory _fee; _fee.total = _feeTreasury + _feeOperators + _feeDevelopers; require(_fee.total <= 10000 && (_feeTreasury > 0 || _feeDevelopers > 0) , "LIDO: FEE_DONT_ADD_UP"); emit FeeSet(_fee.total, _feeOperators, _feeTreasury, _feeDevelopers); _fee.developers = _feeDevelopers; _fee.operators = _feeOperators; _fee.treasury = _feeTreasury; FEE = _fee; } /** * @notice Returns total fee basis points */ function getFee() external view returns (uint16){ return FEE.total; } /** * @notice Returns operators fee basis points */ function getOperatorsFee() external view returns (uint16){ return FEE.operators; } /** * @notice Returns treasury fee basis points */ function getTreasuryFee() external view returns (uint16){ return FEE.treasury; } /** * @notice Returns developers fee basis points */ function getDevelopersFee() external view returns (uint16){ return FEE.developers; } /** * @notice Stop pool routine operations (deposit, redeem, claimUnbonded), * allowed to call only by ROLE_PAUSE_MANAGER */ function pause() external auth(ROLE_PAUSE_MANAGER) { _pause(); } /** * @notice Resume pool routine operations (deposit, redeem, claimUnbonded), * allowed to call only by ROLE_PAUSE_MANAGER */ function resume() external auth(ROLE_PAUSE_MANAGER) { _unpause(); } /** * @notice Add new ledger, allowed to call only by ROLE_LEDGER_MANAGER * @dev That function deploys new ledger for provided stash account * Also method triggers rebalancing stakes accross ledgers, recommended to carefully calculate share value to avoid significant rebalancing. * @param _stashAccount - relaychain stash account id * @param _controllerAccount - controller account id for given stash * @param _share - share of managing stake from total pooled tokens * @return created ledger address */ function addLedger( bytes32 _stashAccount, bytes32 _controllerAccount, uint16 _index, uint256 _share ) external auth(ROLE_LEDGER_MANAGER) returns(address) { require(LEDGER_CLONE != address(0), "LIDO: UNSPECIFIED_LEDGER_CLONE"); require(ORACLE_MASTER != address(0), "LIDO: NO_ORACLE_MASTER"); require(ledgers.length < MAX_LEDGERS_AMOUNT, "LIDO: LEDGERS_POOL_LIMIT"); require(ledgerByStash[_stashAccount] == address(0), "LIDO: STASH_ALREADY_EXISTS"); address ledger = LEDGER_CLONE.cloneDeterministic(_stashAccount); // skip one era before commissioning ILedger(ledger).initialize( _stashAccount, _controllerAccount, address(vKSM), controller, RELAY_SPEC.minNominatorBalance ); ledgers.push(ledger); ledgerByStash[_stashAccount] = ledger; ledgerByAddress[ledger] = ledgers.length; ledgerShares[ledger] = _share; ledgerSharesTotal += _share; IOracleMaster(ORACLE_MASTER).addLedger(ledger); // vKSM.approve(ledger, type(uint256).max); IController(controller).newSubAccount(_index, _stashAccount, ledger); emit LedgerAdd(ledger, _stashAccount, _controllerAccount, _share); return ledger; } /** * @notice Set new share for existing ledger, allowed to call only by ROLE_LEDGER_MANAGER * @param _ledger - target ledger address * @param _newShare - new stare amount */ function setLedgerShare(address _ledger, uint256 _newShare) external auth(ROLE_LEDGER_MANAGER) { require(ledgerByAddress[_ledger] != 0, "LIDO: LEDGER_NOT_FOUND"); ledgerSharesTotal -= ledgerShares[_ledger]; ledgerShares[_ledger] = _newShare; ledgerSharesTotal += _newShare; emit LedgerSetShare(_ledger, _newShare); } /** * @notice Remove ledger, allowed to call only by ROLE_LEDGER_MANAGER * @dev That method cannot be executed for running ledger, so need to drain funds * from ledger by setting zero share and wait for unbonding period. * @param _ledgerAddress - target ledger address */ function removeLedger(address _ledgerAddress) external auth(ROLE_LEDGER_MANAGER) { require(ledgerByAddress[_ledgerAddress] != 0, "LIDO: LEDGER_NOT_FOUND"); require(ledgerShares[_ledgerAddress] == 0, "LIDO: LEDGER_HAS_NON_ZERO_SHARE"); ILedger ledger = ILedger(_ledgerAddress); require(ledger.isEmpty(), "LIDO: LEDGER_IS_NOT_EMPTY"); address lastLedger = ledgers[ledgers.length - 1]; uint256 idxToRemove = ledgerByAddress[_ledgerAddress] - 1; ledgers[idxToRemove] = lastLedger; // put last ledger to removing ledger position ledgerByAddress[lastLedger] = idxToRemove + 1; // fix last ledger index after swap ledgers.pop(); delete ledgerByAddress[_ledgerAddress]; delete ledgerByStash[ledger.stashAccount()]; delete ledgerShares[_ledgerAddress]; IOracleMaster(ORACLE_MASTER).removeLedger(_ledgerAddress); vKSM.approve(address(ledger), 0); emit LedgerRemove(_ledgerAddress); } /** * @notice Nominate on behalf of gived stash account, allowed to call only by ROLE_STAKE_MANAGER * @dev Method spawns xcm call to relaychain * @param _stashAccount - target stash account id * @param _validators - validators set to be nominated */ function nominate(bytes32 _stashAccount, bytes32[] calldata _validators) external auth(ROLE_STAKE_MANAGER) { require(ledgerByStash[_stashAccount] != address(0), "UNKNOWN_STASH_ACCOUNT"); ILedger(ledgerByStash[_stashAccount]).nominate(_validators); } /** * @notice Deposit vKSM tokens to the pool and recieve stKSM(liquid staked tokens) instead. User should approve tokens before executing this call. * @dev Method accoumulate vKSMs on contract * @param _amount - amount of vKSM tokens to be deposited */ function deposit(uint256 _amount) external whenNotPaused { vKSM.transferFrom(msg.sender, address(this), _amount); _submit(_amount); emit Deposited(msg.sender, _amount); } /** * @notice Create request to redeem vKSM in exchange of stKSM. stKSM will be instantly burned and created claim order, (see `getUnbonded` method). User can have up to 10 redeem requests in parallel. * @param _amount - amount of stKSM tokens to be redeemed */ function redeem(uint256 _amount) external whenNotPaused { uint256 _shares = getSharesByPooledKSM(_amount); require(_shares <= _sharesOf(msg.sender), "LIDO: REDEEM_AMOUNT_EXCEEDS_BALANCE"); require(claimOrders[msg.sender].length < MAX_CLAIMS, "LIDO: MAX_CLAIMS_EXCEEDS"); _burnShares(msg.sender, _shares); fundRaisedBalance -= _amount; bufferedRedeems += _amount; Claim memory newClaim = Claim(_amount, uint64(block.timestamp) + RELAY_SPEC.unbondingPeriod); claimOrders[msg.sender].push(newClaim); pendingClaimsTotal += _amount; // emit event about burning (compatible with ERC20) emit Transfer(msg.sender, address(0), _amount); // lido event about redeemed emit Redeemed(msg.sender, _amount); } /** * @notice Claim all unbonded tokens at this point of time. Executed redeem requests will be removed and approproate amount of vKSM transferred to calling account. */ function claimUnbonded() external whenNotPaused { uint256 readyToClaim = 0; uint256 readyToClaimCount = 0; Claim[] storage orders = claimOrders[msg.sender]; for (uint256 i = 0; i < orders.length; ++i) { if (orders[i].timeout < block.timestamp) { readyToClaim += orders[i].balance; readyToClaimCount += 1; } else { orders[i - readyToClaimCount] = orders[i]; } } // remove claimed items for (uint256 i = 0; i < readyToClaimCount; ++i) { orders.pop(); } if (readyToClaim > 0) { vKSM.transfer(msg.sender, readyToClaim); pendingClaimsTotal -= readyToClaim; emit Claimed(msg.sender, readyToClaim); } } /** * @notice Distribute rewards earned by ledger, allowed to call only by ledger */ function distributeRewards(uint256 _totalRewards, uint256 ledgerBalance) external { require(ledgerByAddress[msg.sender] != 0, "LIDO: NOT_FROM_LEDGER"); Types.Fee memory _fee = FEE; // it's `feeDevelopers` + `feeTreasure` uint256 _feeDevTreasure = uint256(_fee.developers + _fee.treasury); assert(_feeDevTreasure>0); fundRaisedBalance += _totalRewards; if (ledgerShares[msg.sender] > 0) { ledgerStake[msg.sender] += _totalRewards; } uint256 _rewards = _totalRewards * _feeDevTreasure / uint256(10000 - _fee.operators); uint256 shares2mint = _rewards * _getTotalShares() / (_getTotalPooledKSM() - _rewards); _mintShares(treasury, shares2mint); uint256 _devShares = shares2mint * uint256(_fee.developers) / _feeDevTreasure; _transferShares(treasury, developers, _devShares); _emitTransferAfterMintingShares(developers, _devShares); _emitTransferAfterMintingShares(treasury, shares2mint - _devShares); emit Rewards(msg.sender, _totalRewards, ledgerBalance); } /** * @notice Distribute lossed by ledger, allowed to call only by ledger */ function distributeLosses(uint256 _totalLosses, uint256 ledgerBalance) external { require(ledgerByAddress[msg.sender] != 0, "LIDO: NOT_FROM_LEDGER"); fundRaisedBalance -= _totalLosses; if (ledgerShares[msg.sender] > 0) { // SWC-Integer Overflow and Underflow: L609 ledgerStake[msg.sender] -= _totalLosses; } emit Losses(msg.sender, _totalLosses, ledgerBalance); } /** * @notice Flush stakes, allowed to call only by oracle master * @dev This method distributes buffered stakes between ledgers by soft manner */ function flushStakes() external { require(msg.sender == ORACLE_MASTER, "LIDO: NOT_FROM_ORACLE_MASTER"); _softRebalanceStakes(); } /** * @notice Force rebalance stake accross ledgers, allowed to call only by ROLE_STAKE_MANAGER * @dev In some cases(due to rewards distribution) real ledger stakes can become different from stakes calculated around ledger shares, so that method fixes that lag. */ function forceRebalanceStake() external auth(ROLE_STAKE_MANAGER) { _forceRebalanceStakes(); bufferedDeposits = 0; bufferedRedeems = 0; } /** * @notice Refresh allowance for each ledger, allowed to call only by ROLE_LEDGER_MANAGER */ function refreshAllowances() external auth(ROLE_LEDGER_MANAGER) { uint _length = ledgers.length; for (uint i = 0; i < _length; i++) { vKSM.approve(ledgers[i], type(uint256).max); } } /** * @notice Rebalance stake accross ledgers according their shares. */ function _forceRebalanceStakes() internal { uint256 totalStake = getTotalPooledKSM(); uint256 stakesSum = 0; address nonZeroLedged = address(0); uint _length = ledgers.length; uint256 _ledgerSharesTotal = ledgerSharesTotal; for (uint i = 0; i < _length; i++) { uint256 share = ledgerShares[ledgers[i]]; uint256 stake = totalStake * share / _ledgerSharesTotal; stakesSum += stake; ledgerStake[ledgers[i]] = stake; if (share > 0 && nonZeroLedged == address(0)) { nonZeroLedged = ledgers[i]; } } // need to compensate remainder of integer division // if we have at least one non zero ledger uint256 remainingDust = totalStake - stakesSum; if (remainingDust > 0 && nonZeroLedged != address(0)) { ledgerStake[nonZeroLedged] += remainingDust; } } /** * @notice Rebalance stake accross ledgers according their shares. */ function _softRebalanceStakes() internal { if (bufferedDeposits > 0 || bufferedRedeems > 0) { _distribute(bufferedDeposits.toInt256() - bufferedRedeems.toInt256()); bufferedDeposits = 0; bufferedRedeems = 0; } } function _distribute(int256 _stake) internal { uint256 ledgersLength = ledgers.length; int256[] memory diffs = new int256[](ledgersLength); address[] memory ledgersCache = new address[](ledgersLength); int256[] memory ledgerStakesCache = new int256[](ledgersLength); uint256[] memory ledgerSharesCache = new uint256[](ledgersLength); int256 activeDiffsSum = 0; int256 totalChange = 0; { uint256 totalStake = getTotalPooledKSM(); uint256 _ledgerSharesTotal = ledgerSharesTotal; int256 diff = 0; for (uint256 i = 0; i < ledgersLength; ++i) { ledgersCache[i] = ledgers[i]; ledgerStakesCache[i] = int256(ledgerStake[ledgersCache[i]]); ledgerSharesCache[i] = ledgerShares[ledgersCache[i]]; uint256 targetStake = totalStake * ledgerSharesCache[i] / _ledgerSharesTotal; diff = int256(targetStake) - int256(ledgerStakesCache[i]); if (_stake * diff > 0) { activeDiffsSum += diff; } diffs[i] = diff; } } if (activeDiffsSum != 0) { int8 direction = 1; if (activeDiffsSum < 0) { direction = -1; activeDiffsSum = -activeDiffsSum; } for (uint256 i = 0; i < ledgersLength; ++i) { diffs[i] *= direction; if (diffs[i] > 0 && (direction < 0 || ledgerSharesCache[i] > 0)) { int256 change = diffs[i] * _stake / activeDiffsSum; int256 newStake = ledgerStakesCache[i] + change; // SWC-Integer Overflow and Underflow: L732 ledgerStake[ledgersCache[i]] = uint256(newStake); ledgerStakesCache[i] = newStake; totalChange += change; } } } { int256 remaining = _stake - totalChange; if (remaining > 0) { for (uint256 i = 0; i < ledgersLength; ++i) { if (ledgerSharesCache[i] > 0) { ledgerStake[ledgersCache[i]] += uint256(remaining); break; } } } else if (remaining < 0) { for (uint256 i = 0; i < ledgersLength || remaining < 0; ++i) { uint256 stake = uint256(ledgerStakesCache[i]); if (stake > 0) { uint256 decrement = stake > uint256(-remaining) ? uint256(-remaining) : stake; ledgerStake[ledgersCache[i]] -= decrement; remaining += int256(decrement); } } } } } /** * @notice Process user deposit, mints stKSM and increase the pool buffer * @return amount of stKSM shares generated */ function _submit(uint256 _deposit) internal returns (uint256) { address sender = msg.sender; require(_deposit != 0, "LIDO: ZERO_DEPOSIT"); uint256 sharesAmount = getSharesByPooledKSM(_deposit); if (sharesAmount == 0) { // totalPooledKSM is 0: either the first-ever deposit or complete slashing // assume that shares correspond to KSM as 1-to-1 sharesAmount = _deposit; } fundRaisedBalance += _deposit; bufferedDeposits += _deposit; _mintShares(sender, sharesAmount); _emitTransferAfterMintingShares(sender, sharesAmount); return sharesAmount; } /** * @notice Emits an {Transfer} event where from is 0 address. Indicates mint events. */ function _emitTransferAfterMintingShares(address _to, uint256 _sharesAmount) internal { emit Transfer(address(0), _to, getPooledKSMByShares(_sharesAmount)); } /** * @notice Returns amount of total pooled tokens by contract. * @return amount of pooled vKSM in contract */ function _getTotalPooledKSM() internal view override returns (uint256) { return fundRaisedBalance; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "../interfaces/Types.sol"; import "../interfaces/ILedger.sol"; import "../interfaces/IOracleMaster.sol"; import "./utils/ReportUtils.sol"; contract Oracle { using ReportUtils for uint256; event Completed(uint256); // Current era report hashes uint256[] internal currentReportVariants; // Current era reports Types.OracleData[] private currentReports; // Then oracle member push report, its bit is set uint256 internal currentReportBitmask; // oracle master contract address address public ORACLE_MASTER; // linked ledger contract address address public LEDGER; // is already pushed flag bool public isPushed; modifier onlyOracleMaster() { require(msg.sender == ORACLE_MASTER); _; } /** * @notice Initialize oracle contract * @param _oracleMaster oracle master address * @param _ledger linked ledger address */ function initialize(address _oracleMaster, address _ledger) external { require(ORACLE_MASTER == address(0), "ORACLE: ALREADY_INITIALIZED"); ORACLE_MASTER = _oracleMaster; LEDGER = _ledger; } /** * @notice Returns true if member is already reported * @param _index oracle member index * @return is reported indicator */ function isReported(uint256 _index) external view returns (bool) { return (currentReportBitmask & (1 << _index)) != 0; } /** * @notice Returns report by given index * @param _index oracle member index * @return staking report data */ function getStakeReport(uint256 _index) internal view returns (Types.OracleData storage staking) { assert(_index < currentReports.length); return currentReports[_index]; } /** * @notice Accept oracle report data, allowed to call only by oracle master contract * @param _index oracle member index * @param _quorum the minimum number of voted oracle members to accept a variant * @param _eraId current era id * @param _staking report data */ function reportRelay(uint256 _index, uint256 _quorum, uint64 _eraId, Types.OracleData calldata _staking) external onlyOracleMaster { { uint256 mask = 1 << _index; uint256 reportBitmask = currentReportBitmask; require(reportBitmask & mask == 0, "ORACLE: ALREADY_SUBMITTED"); currentReportBitmask = (reportBitmask | mask); } // return instantly if already got quorum and pushed data if (isPushed) { return; } // convert staking report into 31 byte hash. The last byte is used for vote counting uint256 variant = uint256(keccak256(abi.encode(_staking))) & ReportUtils.COUNT_OUTMASK; uint256 i = 0; uint256 _length = currentReportVariants.length; // iterate on all report variants we already have, limited by the oracle members maximum while (i < _length && currentReportVariants[i].isDifferent(variant)) ++i; if (i < _length) { if (currentReportVariants[i].getCount() + 1 >= _quorum) { _push(_eraId, _staking); } else { ++currentReportVariants[i]; // increment variant counter, see ReportUtils for details } } else { if (_quorum == 1) { _push(_eraId, _staking); } else { currentReportVariants.push(variant + 1); currentReports.push(_staking); } } } /** * @notice Change quorum threshold, allowed to call only by oracle master contract * @dev Method can trigger to pushing data to ledger if quorum threshold decreased and now for contract already reached new threshold. * @param _quorum new quorum threshold * @param _eraId current era id */ function softenQuorum(uint8 _quorum, uint64 _eraId) external onlyOracleMaster { (bool isQuorum, uint256 reportIndex) = _getQuorumReport(_quorum); if (isQuorum) { Types.OracleData memory report = getStakeReport(reportIndex); _push( _eraId, report ); } } /** * @notice Clear data about current reporting, allowed to call only by oracle master contract */ function clearReporting() external onlyOracleMaster { _clearReporting(); } /** * @notice Clear data about current reporting */ function _clearReporting() internal { currentReportBitmask = 0; isPushed = false; delete currentReportVariants; delete currentReports; } /** * @notice Push data to ledger */ function _push(uint64 _eraId, Types.OracleData memory report) internal { ILedger(LEDGER).pushData(_eraId, report); isPushed = true; } /** * @notice Return whether the `_quorum` is reached and the final report can be pushed */ function _getQuorumReport(uint256 _quorum) internal view returns (bool, uint256) { // check most frequent cases first: all reports are the same or no reports yet uint256 _length = currentReportVariants.length; if (_length == 1) { return (currentReportVariants[0].getCount() >= _quorum, 0); } else if (_length == 0) { return (false, type(uint256).max); } // if more than 2 kind of reports exist, choose the most frequent uint256 maxind = 0; uint256 repeat = 0; uint16 maxval = 0; uint16 cur = 0; for (uint256 i = 0; i < _length; ++i) { cur = currentReportVariants[i].getCount(); if (cur >= maxval) { if (cur == maxval) { ++repeat; } else { maxind = i; maxval = cur; repeat = 0; } } } return (maxval >= _quorum && repeat == 0, maxind); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../interfaces/IAuthManager.sol"; contract AuthManager is IAuthManager, Initializable { mapping(address => bytes32[]) internal members; uint256 internal constant NOTFOUND = type(uint256).max; bytes32 public constant SUPER_ROLE = keccak256("SUPER_ROLE"); event AddMember(address member, bytes32 role); event RemoveMember(address member, bytes32 role); function initialize(address superior) external initializer { if (superior == address(0)) { members[msg.sender] = [SUPER_ROLE]; emit AddMember(msg.sender, SUPER_ROLE); } else { members[superior] = [SUPER_ROLE]; emit AddMember(msg.sender, SUPER_ROLE); } } function roles(address _member) external view returns (bytes32[] memory) { return members[_member]; } function has(bytes32 role, address _member) external override view returns (bool) { return _find(members[_member], role) != NOTFOUND; } function add(bytes32 role, address member) external override { require(_find(members[msg.sender], SUPER_ROLE) != NOTFOUND, "FORBIDDEN"); bytes32[] storage _roles = members[member]; require(_find(_roles, role) == NOTFOUND, "ALREADY_MEMBER"); _roles.push(role); emit AddMember(member, role); } function addByString(string calldata roleString, address member) external { require(_find(members[msg.sender], SUPER_ROLE) != NOTFOUND, "FORBIDDEN"); bytes32[] storage _roles = members[member]; bytes32 role = keccak256(bytes(roleString)); require(_find(_roles, role) == NOTFOUND, "ALREADY_MEMBER"); _roles.push(role); emit AddMember(member, role); } function remove(bytes32 role, address member) external override { require(_find(members[msg.sender], SUPER_ROLE) != NOTFOUND, "FORBIDDEN"); require(msg.sender != member || role != SUPER_ROLE, "INVALID"); bytes32[] storage _roles = members[member]; uint256 i = _find(_roles, role); require(i != NOTFOUND, "MEMBER_NOT_FOUND"); if (_roles.length == 1) { delete members[member]; } else { if (i < _roles.length - 1) { _roles[i] = _roles[_roles.length - 1]; } _roles.pop(); } emit RemoveMember(member, role); } function _find(bytes32[] storage _roles, bytes32 _role) internal view returns (uint256) { for (uint256 i = 0; i < _roles.length; ++i) { if (_role == _roles[i]) { return i; } } return NOTFOUND; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "../interfaces/IOracle.sol"; import "../interfaces/ILido.sol"; import "../interfaces/ILedger.sol"; import "../interfaces/IAuthManager.sol"; import "./utils/LedgerUtils.sol"; contract OracleMaster is Pausable { using Clones for address; using LedgerUtils for Types.OracleData; event MemberAdded(address member); event MemberRemoved(address member); event QuorumChanged(uint8 QUORUM); // current era id uint64 public eraId; // Oracle members address[] public members; // ledger -> oracle pairing mapping(address => address) private oracleForLedger; // address of oracle clone template contract address public ORACLE_CLONE; // Lido smart contract address public LIDO; // Quorum threshold uint8 public QUORUM; // Relay genesis timestamp uint64 public RELAY_GENESIS_TIMESTAMP; // Relay seconds per era uint64 public RELAY_SECONDS_PER_ERA; /// Maximum number of oracle committee members uint256 public constant MAX_MEMBERS = 255; // Missing member index uint256 internal constant MEMBER_NOT_FOUND = type(uint256).max; // General oracle manager role bytes32 internal constant ROLE_ORACLE_MANAGER = keccak256("ROLE_ORACLE_MANAGER"); // Oracle members manager role bytes32 internal constant ROLE_ORACLE_MEMBERS_MANAGER = keccak256("ROLE_ORACLE_MEMBERS_MANAGER"); // Oracle members manager role bytes32 internal constant ROLE_ORACLE_QUORUM_MANAGER = keccak256("ROLE_ORACLE_QUORUM_MANAGER"); modifier auth(bytes32 role) { require(IAuthManager(ILido(LIDO).AUTH_MANAGER()).has(role, msg.sender), "OM: UNAUTHOROZED"); _; } modifier onlyLido() { require(msg.sender == LIDO, "OM: CALLER_NOT_LIDO"); _; } /** * @notice Initialize oracle master contract, allowed to call only once * @param _oracleClone oracle clone contract address * @param _quorum inital quorum threshold */ function initialize( address _oracleClone, uint8 _quorum ) external { require(ORACLE_CLONE == address(0), "OM: ALREADY_INITIALIZED"); ORACLE_CLONE = _oracleClone; QUORUM = _quorum; } /** * @notice Set lido contract address, allowed to only once * @param _lido lido contract address */ function setLido(address _lido) external { require(LIDO == address(0), "OM: LIDO_ALREADY_DEFINED"); LIDO = _lido; } /** * @notice Set relaychain params required for oracles, allowed to call only by lido contract * @param _relayGenesisTs relaychain genesis timestamp * @param _relaySecondsPerEra relaychain era duratation in seconds */ function setRelayParams(uint64 _relayGenesisTs, uint64 _relaySecondsPerEra) external onlyLido { RELAY_GENESIS_TIMESTAMP = _relayGenesisTs; RELAY_SECONDS_PER_ERA = _relaySecondsPerEra; } /** * @notice Set the number of exactly the same reports needed to finalize the era allowed to call only by ROLE_ORACLE_QUORUM_MANAGER * @param _quorum new value of quorum threshold */ function setQuorum(uint8 _quorum) external auth(ROLE_ORACLE_QUORUM_MANAGER) { require(0 != _quorum, "OM: QUORUM_WONT_BE_MADE"); uint8 oldQuorum = QUORUM; QUORUM = _quorum; // If the QUORUM value lowered, check existing reports whether it is time to push if (oldQuorum > _quorum) { address[] memory ledgers = ILido(LIDO).getLedgerAddresses(); uint256 _length = ledgers.length; for (uint256 i = 0; i < _length; ++i) { address oracle = oracleForLedger[ledgers[i]]; if (oracle != address(0)) { IOracle(oracle).softenQuorum(_quorum, eraId); } } } emit QuorumChanged(_quorum); } /** * @notice Return oracle contract for the given ledger * @param _ledger ledger contract address * @return linked oracle address */ function getOracle(address _ledger) external view returns (address) { return oracleForLedger[_ledger]; } /** * @notice Return current Era according to relay chain spec * @return current era id */ function getCurrentEraId() public view returns (uint64) { return _getCurrentEraId(); } /** * @notice Return relay chain stash account addresses * @return Array of bytes32 relaychain stash accounts */ function getStashAccounts() external view returns (bytes32[] memory) { return ILido(LIDO).getStashAccounts(); } /** * @notice Return last reported era and oracle is already reported indicator * @param _oracleMember - oracle member address * @param _stash - stash account id * @return lastEra - last reported era * @return isReported - true if oracle member already reported for given stash, else false */ function isReportedLastEra(address _oracleMember, bytes32 _stash) external view returns ( uint64 lastEra, bool isReported ) { uint64 lastEra = eraId; uint256 memberIdx = _getMemberId(_oracleMember); if (memberIdx == MEMBER_NOT_FOUND) { return (lastEra, false); } address ledger = ILido(LIDO).findLedger(_stash); if (ledger == address(0)) { return (lastEra, false); } return (lastEra, IOracle(oracleForLedger[ledger]).isReported(memberIdx)); } /** * @notice Stop pool routine operations (reportRelay), allowed to call only by ROLE_ORACLE_MANAGER */ function pause() external auth(ROLE_ORACLE_MANAGER) { _pause(); } /** * @notice Resume pool routine operations (reportRelay), allowed to call only by ROLE_ORACLE_MANAGER */ function resume() external auth(ROLE_ORACLE_MANAGER) { _unpause(); } /** * @notice Add new member to the oracle member committee list, allowed to call only by ROLE_ORACLE_MEMBERS_MANAGER * @param _member proposed member address */ function addOracleMember(address _member) external auth(ROLE_ORACLE_MEMBERS_MANAGER) { require(address(0) != _member, "OM: BAD_ARGUMENT"); require(MEMBER_NOT_FOUND == _getMemberId(_member), "OM: MEMBER_EXISTS"); require(members.length < 254, "OM: MEMBERS_TOO_MANY"); members.push(_member); require(members.length < MAX_MEMBERS, "OM: TOO_MANY_MEMBERS"); emit MemberAdded(_member); } /** * @notice Remove `_member` from the oracle member committee list, allowed to call only by ROLE_ORACLE_MEMBERS_MANAGER */ function removeOracleMember(address _member) external auth(ROLE_ORACLE_MEMBERS_MANAGER) { uint256 index = _getMemberId(_member); require(index != MEMBER_NOT_FOUND, "OM: MEMBER_NOT_FOUND"); uint256 last = members.length - 1; if (index != last) members[index] = members[last]; members.pop(); emit MemberRemoved(_member); // delete the data for the last eraId, let remained oracles report it again _clearReporting(); } /** * @notice Add ledger to oracle set, allowed to call only by lido contract * @param _ledger Ledger contract */ function addLedger(address _ledger) external onlyLido { require(ORACLE_CLONE != address(0), "OM: ORACLE_CLONE_UNINITIALIZED"); IOracle newOracle = IOracle(ORACLE_CLONE.cloneDeterministic(bytes32(uint256(uint160(_ledger)) << 96))); newOracle.initialize(address(this), _ledger); oracleForLedger[_ledger] = address(newOracle); } /** * @notice Remove ledger from oracle set, allowed to call only by lido contract * @param _ledger ledger contract */ function removeLedger(address _ledger) external onlyLido { oracleForLedger[_ledger] = address(0); } /** * @notice Accept oracle committee member reports from the relay side * @param _eraId relaychain era * @param _report relaychain data report */ function reportRelay(uint64 _eraId, Types.OracleData calldata _report) external whenNotPaused { require(_report.isConsistent(), "OM: INCORRECT_REPORT"); uint256 memberIndex = _getMemberId(msg.sender); require(memberIndex != MEMBER_NOT_FOUND, "OM: MEMBER_NOT_FOUND"); address ledger = ILido(LIDO).findLedger(_report.stashAccount); address oracle = oracleForLedger[ledger]; require(oracle != address(0), "OM: ORACLE_FOR_LEDGER_NOT_FOUND"); require(_eraId >= eraId, "OM: ERA_TOO_OLD"); // new era if (_eraId > eraId) { require(_eraId <= _getCurrentEraId(), "OM: UNEXPECTED_NEW_ERA"); eraId = _eraId; _clearReporting(); ILido(LIDO).flushStakes(); } IOracle(oracle).reportRelay(memberIndex, QUORUM, _eraId, _report); } /** * @notice Return oracle instance index in the member array * @param _member member address * @return member index */ function _getMemberId(address _member) internal view returns (uint256) { uint256 length = members.length; for (uint256 i = 0; i < length; ++i) { if (members[i] == _member) { return i; } } return MEMBER_NOT_FOUND; } /** * @notice Calculate current expected era id * @dev Calculation based on relaychain genesis timestamp and era duratation * @return current era id */ function _getCurrentEraId() internal view returns (uint64) { return (uint64(block.timestamp) - RELAY_GENESIS_TIMESTAMP ) / RELAY_SECONDS_PER_ERA; } /** * @notice Delete interim data for current Era, free storage memory for each oracle */ function _clearReporting() internal { address[] memory ledgers = ILido(LIDO).getLedgerAddresses(); uint256 _length = ledgers.length; for (uint256 i = 0; i < _length; ++i) { address oracle = oracleForLedger[ledgers[i]]; if (oracle != address(0)) { IOracle(oracle).clearReporting(); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; abstract contract stKSM is IERC20, Pausable { /** * @dev stKSM balances are dynamic and are calculated based on the accounts' shares * and the total amount of KSM controlled by the protocol. Account shares aren't * normalized, so the contract also stores the sum of all shares to calculate * each account's token balance which equals to: * * shares[account] * _getTotalPooledKSM() / _getTotalShares() */ mapping (address => uint256) private shares; /** * @dev Allowances are nominated in tokens, not token shares. */ mapping (address => mapping (address => uint256)) private allowances; /** * @dev Storage position used for holding the total amount of shares in existence. * * The Lido protocol is built on top of Aragon and uses the Unstructured Storage pattern * for value types: * * https://blog.openzeppelin.com/upgradeability-using-unstructured-storage * https://blog.8bitzen.com/posts/20-02-2020-understanding-how-solidity-upgradeable-unstructured-proxies-work * * For reference types, conventional storage variables are used since it's non-trivial * and error-prone to implement reference-type unstructured storage using Solidity v0.4; * see https://github.com/lidofinance/lido-dao/issues/181#issuecomment-736098834 */ uint256 internal totalShares; /** * @return the name of the token. */ function name() public pure returns (string memory) { return "Liquid staked KSM"; } /** * @return the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return "stKSM"; } /** * @return the number of decimals for getting user representation of a token amount. */ function decimals() public pure returns (uint8) { return 12; } /** * @return the amount of tokens in existence. * * @dev Always equals to `_getTotalPooledKSM()` since token amount * is pegged to the total amount of KSM controlled by the protocol. */ function totalSupply() public view override returns (uint256) { return _getTotalPooledKSM(); } /** * @return the entire amount of KSMs controlled by the protocol. * * @dev The sum of all KSM balances in the protocol. */ function getTotalPooledKSM() public view returns (uint256) { return _getTotalPooledKSM(); } /** * @return the amount of tokens owned by the `_account`. * * @dev Balances are dynamic and equal the `_account`'s share in the amount of the * total KSM controlled by the protocol. See `sharesOf`. */ function balanceOf(address _account) public view override returns (uint256) { return getPooledKSMByShares(_sharesOf(_account)); } /** * @notice Moves `_amount` tokens from the caller's account to the `_recipient` account. * * @return a boolean value indicating whether the operation succeeded. * Emits a `Transfer` event. * * Requirements: * * - `_recipient` cannot be the zero address. * - the caller must have a balance of at least `_amount`. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function transfer(address _recipient, uint256 _amount) public override returns (bool) { _transfer(msg.sender, _recipient, _amount); return true; } /** * @return the remaining number of tokens that `_spender` is allowed to spend * on behalf of `_owner` through `transferFrom`. This is zero by default. * * @dev This value changes when `approve` or `transferFrom` is called. */ function allowance(address _owner, address _spender) public view override returns (uint256) { return allowances[_owner][_spender]; } /** * @notice Sets `_amount` as the allowance of `_spender` over the caller's tokens. * * @return a boolean value indicating whether the operation succeeded. * Emits an `Approval` event. * * Requirements: * * - `_spender` cannot be the zero address. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function approve(address _spender, uint256 _amount) public override returns (bool) { _approve(msg.sender, _spender, _amount); return true; } /** * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the * allowance mechanism. `_amount` is then deducted from the caller's * allowance. * * @return a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `_sender` and `_recipient` cannot be the zero addresses. * - `_sender` must have a balance of at least `_amount`. * - the caller must have allowance for `_sender`'s tokens of at least `_amount`. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) { uint256 currentAllowance = allowances[_sender][msg.sender]; require(currentAllowance >= _amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE"); _transfer(_sender, _recipient, _amount); _approve(_sender, msg.sender, currentAllowance -_amount); return true; } /** * @notice Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42 * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `_spender` cannot be the the zero address. * - the contract must not be paused. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { _approve(msg.sender, _spender, allowances[msg.sender][_spender] + _addedValue); return true; } /** * @notice Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42 * 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`. * - the contract must not be paused. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require(currentAllowance >= _subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO"); _approve(msg.sender, _spender, currentAllowance-_subtractedValue); return true; } /** * @return the total amount of shares in existence. * * @dev The sum of all accounts' shares can be an arbitrary number, therefore * it is necessary to store it in order to calculate each account's relative share. */ function getTotalShares() public view returns (uint256) { return _getTotalShares(); } /** * @return the amount of shares owned by `_account`. */ function sharesOf(address _account) public view returns (uint256) { return _sharesOf(_account); } /** * @return the amount of shares that corresponds to `_ethAmount` protocol-controlled KSM. */ function getSharesByPooledKSM(uint256 _amount) public view returns (uint256) { uint256 totalPooledKSM = _getTotalPooledKSM(); if (totalPooledKSM == 0) { return 0; } else { return _amount * _getTotalShares() / totalPooledKSM; } } /** * @return the amount of KSM that corresponds to `_sharesAmount` token shares. */ function getPooledKSMByShares(uint256 _sharesAmount) public view returns (uint256) { uint256 _totalShares = _getTotalShares(); if (totalShares == 0) { return 0; } else { return _sharesAmount * _getTotalPooledKSM() / _totalShares; } } /** * @return the total amount (in wei) of KSM controlled by the protocol. * @dev This is used for calaulating tokens from shares and vice versa. * @dev This function is required to be implemented in a derived contract. */ function _getTotalPooledKSM() internal view virtual returns (uint256); /** * @notice Moves `_amount` tokens from `_sender` to `_recipient`. * Emits a `Transfer` event. */ function _transfer(address _sender, address _recipient, uint256 _amount) internal { uint256 _sharesToTransfer = getSharesByPooledKSM(_amount); _transferShares(_sender, _recipient, _sharesToTransfer); emit Transfer(_sender, _recipient, _amount); } /** * @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens. * * Emits an `Approval` event. * * Requirements: * * - `_owner` cannot be the zero address. * - `_spender` cannot be the zero address. * - the contract must not be paused. */ function _approve(address _owner, address _spender, uint256 _amount) internal whenNotPaused { require(_owner != address(0), "APPROVE_FROM_ZERO_ADDRESS"); require(_spender != address(0), "APPROVE_TO_ZERO_ADDRESS"); allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /** * @return the total amount of shares in existence. */ function _getTotalShares() internal view returns (uint256) { return totalShares; } /** * @return the amount of shares owned by `_account`. */ function _sharesOf(address _account) internal view returns (uint256) { return shares[_account]; } /** * @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`. * * Requirements: * * - `_sender` cannot be the zero address. * - `_recipient` cannot be the zero address. * - `_sender` must hold at least `_sharesAmount` shares. * - the contract must not be paused. */ function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal whenNotPaused { require(_sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS"); require(_recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS"); uint256 currentSenderShares = shares[_sender]; require(_sharesAmount <= currentSenderShares, "TRANSFER_AMOUNT_EXCEEDS_BALANCE"); shares[_sender] = currentSenderShares - _sharesAmount; shares[_recipient] = shares[_recipient] + _sharesAmount; } /** * @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares. * @dev This doesn't increase the token total supply. * * Requirements: * * - `_recipient` cannot be the zero address. * - the contract must not be paused. */ function _mintShares(address _recipient, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) { require(_recipient != address(0), "MINT_TO_THE_ZERO_ADDRESS"); newTotalShares = _getTotalShares() + _sharesAmount; totalShares = newTotalShares; shares[_recipient] = shares[_recipient] + _sharesAmount; // Notice: we're not emitting a Transfer event from the zero address here since shares mint // works by taking the amount of tokens corresponding to the minted shares from all other // token holders, proportionally to their share. The total supply of the token doesn't change // as the result. This is equivalent to performing a send from each other token holder's // address to `address`, but we cannot reflect this as it would require sending an unbounded // number of events. } /** * @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares. * @dev This doesn't decrease the token total supply. * * Requirements: * * - `_account` cannot be the zero address. * - `_account` must hold at least `_sharesAmount` shares. * - the contract must not be paused. */ function _burnShares(address _account, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) { require(_account != address(0), "BURN_FROM_THE_ZERO_ADDRESS"); uint256 accountShares = shares[_account]; require(_sharesAmount <= accountShares, "BURN_AMOUNT_EXCEEDS_BALANCE"); newTotalShares = _getTotalShares() - _sharesAmount; totalShares = newTotalShares; shares[_account] = accountShares - _sharesAmount; // Notice: we're not emitting a Transfer event to the zero address here since shares burn // works by redistributing the amount of tokens corresponding to the burned shares between // all other token holders. The total supply of the token doesn't change as the result. // This is equivalent to performing a send from `address` to each other token holder address, // but we cannot reflect this as it would require sending an unbounded number of events. } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../interfaces/IOracleMaster.sol"; import "../interfaces/ILido.sol"; import "../interfaces/IRelayEncoder.sol"; import "../interfaces/IXcmTransactor.sol"; import "../interfaces/IController.sol"; import "../interfaces/Types.sol"; import "./utils/LedgerUtils.sol"; import "./utils/ReportUtils.sol"; contract Ledger { using LedgerUtils for Types.OracleData; using SafeCast for uint256; event DownwardComplete(uint128 amount); event UpwardComplete(uint128 amount); event Rewards(uint128 amount, uint128 balance); event Slash(uint128 amount, uint128 balance); // ledger stash account bytes32 public stashAccount; // ledger controller account bytes32 public controllerAccount; // Stash balance that includes locked (bounded in stake) and free to transfer balance uint128 public totalBalance; // Locked, or bonded in stake module, balance uint128 public lockedBalance; // last reported active ledger balance uint128 public activeBalance; // last reported ledger status Types.LedgerStatus public status; // Cached stash balance. Need to calculate rewards between successfull up/down transfers uint128 public cachedTotalBalance; // Pending transfers uint128 public transferUpwardBalance; uint128 public transferDownwardBalance; // vKSM precompile IERC20 internal vKSM; IController internal controller; // Lido main contract address ILido public LIDO; // Minimal allowed balance to being a nominator uint128 public MIN_NOMINATOR_BALANCE; // Who pay off relay chain transaction fees bytes32 internal constant GARANTOR = 0x00; modifier onlyLido() { require(msg.sender == address(LIDO), "LEDGED: NOT_LIDO"); _; } modifier onlyOracle() { address oracle = IOracleMaster(ILido(LIDO).ORACLE_MASTER()).getOracle(address(this)); require(msg.sender == oracle, "LEDGED: NOT_ORACLE"); _; } /** * @notice Initialize ledger contract. * @param _stashAccount - stash account id * @param _controllerAccount - controller account id * @param _vKSM - vKSM contract address * @param _controller - xcmTransactor(relaychain calls relayer) contract address * @param _minNominatorBalance - minimal allowed nominator balance */ function initialize( bytes32 _stashAccount, bytes32 _controllerAccount, address _vKSM, address _controller, uint128 _minNominatorBalance ) external { require(address(vKSM) == address(0), "LEDGED: ALREADY_INITIALIZED"); // The owner of the funds stashAccount = _stashAccount; // The account which handles bounded part of stash funds (unbond, rebond, withdraw, nominate) controllerAccount = _controllerAccount; status = Types.LedgerStatus.None; LIDO = ILido(msg.sender); vKSM = IERC20(_vKSM); controller = IController(_controller); MIN_NOMINATOR_BALANCE = _minNominatorBalance; // vKSM.approve(_controller, type(uint256).max); } /** * @notice Set new minimal allowed nominator balance, allowed to call only by lido contract * @dev That method designed to be called by lido contract when relay spec is changed * @param _minNominatorBalance - minimal allowed nominator balance */ function setMinNominatorBalance(uint128 _minNominatorBalance) external onlyLido { MIN_NOMINATOR_BALANCE = _minNominatorBalance; } function refreshAllowances() external { vKSM.approve(address(controller), type(uint256).max); } /** * @notice Return target stake amount for this ledger * @return target stake amount */ function ledgerStake() public view returns (uint256) { return LIDO.ledgerStake(address(this)); } /** * @notice Return true if ledger doesn't have any funds */ function isEmpty() external view returns (bool) { return totalBalance == 0 && transferUpwardBalance == 0 && transferDownwardBalance == 0; } /** * @notice Nominate on behalf of this ledger, allowed to call only by lido contract * @dev Method spawns xcm call to relaychain. * @param _validators - array of choosen validator to be nominated */ function nominate(bytes32[] calldata _validators) external onlyLido { require(activeBalance >= MIN_NOMINATOR_BALANCE, "LEDGED: NOT_ENOUGH_STAKE"); controller.nominate(_validators); } /** * @notice Provide portion of relaychain data about current ledger, allowed to call only by oracle contract * @dev Basically, ledger can obtain data from any source, but for now it allowed to recieve only from oracle. Method perform calculation of current state based on report data and saved state and expose required instructions(relaychain pallet calls) via xcm to adjust bonded amount to required target stake. * @param _eraId - reporting era id * @param _report - data that represent state of ledger on relaychain for `_eraId` */ function pushData(uint64 _eraId, Types.OracleData memory _report) external onlyOracle { require(stashAccount == _report.stashAccount, "LEDGED: STASH_ACCOUNT_MISMATCH"); status = _report.stakeStatus; activeBalance = _report.activeBalance; (uint128 unlockingBalance, uint128 withdrawableBalance) = _report.getTotalUnlocking(_eraId); uint128 nonWithdrawableBalance = unlockingBalance - withdrawableBalance; if (!_processRelayTransfers(_report)) { return; } uint128 _cachedTotalBalance = cachedTotalBalance; if (_cachedTotalBalance < _report.stashBalance) { // if cached balance > real => we have reward uint128 reward = _report.stashBalance - _cachedTotalBalance; LIDO.distributeRewards(reward, _report.stashBalance); emit Rewards(reward, _report.stashBalance); } else if (_cachedTotalBalance > _report.stashBalance) { uint128 slash = _cachedTotalBalance - _report.stashBalance; LIDO.distributeLosses(slash, _report.stashBalance); emit Slash(slash, _report.stashBalance); } uint128 _ledgerStake = ledgerStake().toUint128(); // relay deficit or bonding if (_report.stashBalance <= _ledgerStake) { // Staking strategy: // - upward transfer deficit tokens // - rebond all unlocking tokens // - bond_extra all free balance uint128 deficit = _ledgerStake - _report.stashBalance; // just upward transfer if we have deficit if (deficit > 0) { uint128 lidoBalance = uint128(LIDO.avaliableForStake()); uint128 forTransfer = lidoBalance > deficit ? deficit : lidoBalance; if (forTransfer > 0) { vKSM.transferFrom(address(LIDO), address(this), forTransfer); controller.transferToRelaychain(forTransfer); transferUpwardBalance += forTransfer; } } // rebond all always if (unlockingBalance > 0) { controller.rebond(unlockingBalance); } uint128 relayFreeBalance = _report.getFreeBalance(); if (relayFreeBalance > 0 && (_report.stakeStatus == Types.LedgerStatus.Nominator || _report.stakeStatus == Types.LedgerStatus.Idle)) { controller.bondExtra(relayFreeBalance); } else if (_report.stakeStatus == Types.LedgerStatus.None && relayFreeBalance >= MIN_NOMINATOR_BALANCE) { controller.bond(controllerAccount, relayFreeBalance); } } else if (_report.stashBalance > _ledgerStake) { // parachain deficit // Unstaking strategy: // - try to downward transfer already free balance // - if we still have deficit try to withdraw already unlocked tokens // - if we still have deficit initiate unbond for remain deficit // if ledger is in the deadpool we need to put it to chill if (_ledgerStake < MIN_NOMINATOR_BALANCE && status != Types.LedgerStatus.Idle) { controller.chill(); } uint128 deficit = _report.stashBalance - _ledgerStake; uint128 relayFreeBalance = _report.getFreeBalance(); // need to downward transfer if we have some free if (relayFreeBalance > 0) { uint128 forTransfer = relayFreeBalance > deficit ? deficit : relayFreeBalance; controller.transferToParachain(forTransfer); transferDownwardBalance += forTransfer; deficit -= forTransfer; relayFreeBalance -= forTransfer; } // withdraw if we have some unlocked if (deficit > 0 && withdrawableBalance > 0) { controller.withdrawUnbonded(); deficit -= withdrawableBalance > deficit ? deficit : withdrawableBalance; } // need to unbond if we still have deficit if (nonWithdrawableBalance < deficit) { // todo drain stake if remaining balance is less than MIN_NOMINATOR_BALANCE uint128 forUnbond = deficit - nonWithdrawableBalance; controller.unbond(forUnbond); // notice. // deficit -= forUnbond; } // bond all remain free balance if (relayFreeBalance > 0) { controller.bondExtra(relayFreeBalance); } } cachedTotalBalance = _report.stashBalance; } function _processRelayTransfers(Types.OracleData memory _report) internal returns(bool) { // wait for the downward transfer to complete uint128 _transferDownwardBalance = transferDownwardBalance; if (_transferDownwardBalance > 0) { uint128 totalDownwardTransferred = uint128(vKSM.balanceOf(address(this))); if (totalDownwardTransferred >= _transferDownwardBalance ) { // take transferred funds into buffered balance vKSM.transfer(address(LIDO), _transferDownwardBalance); // Clear transfer flag cachedTotalBalance -= _transferDownwardBalance; transferDownwardBalance = 0; emit DownwardComplete(_transferDownwardBalance); _transferDownwardBalance = 0; } } // wait for the upward transfer to complete uint128 _transferUpwardBalance = transferUpwardBalance; if (_transferUpwardBalance > 0) { uint128 ledgerFreeBalance = (totalBalance - lockedBalance); // SWC-Integer Overflow and Underflow: L298 uint128 freeBalanceIncrement = _report.getFreeBalance() - ledgerFreeBalance; if (freeBalanceIncrement >= _transferUpwardBalance) { cachedTotalBalance += _transferUpwardBalance; transferUpwardBalance = 0; emit UpwardComplete(_transferUpwardBalance); _transferUpwardBalance = 0; } } if (_transferDownwardBalance == 0 && _transferUpwardBalance == 0) { // update ledger data from oracle report totalBalance = _report.stashBalance; lockedBalance = _report.totalBalance; return true; } return false; } }
LIDO KSM SMART CONTRACT AUDIT February 08, 2022 MixBytes()CONTENTS 1.INTRODUCTION 2 DISCLAIMER 2 SECURITY ASSESSMENT METHODOLOGY 3 PROJECT OVERVIEW 5 PROJECT DASHBOARD 5 2.FINDINGS REPORT 7 2.1.CRITICAL 7 CRT-1 Possible underflow 7 CRT-2 Possible overflow on cast to uint 8 2.2.MAJOR 9 MJR-1 Public access to all functions 9 MJR-2 Controller can be initialized several times 10 MJR-3 Incorrect condition 11 MJR-4 Possible burn of zero shares 12 MJR-5 Possible division by zero 13 MJR-6 Insufficient xcKSm balance on Lido 14 MJR-7 Possible zero balance on Lido 15 MJR-8 Possible underflow 16 2.3.WARNING 17 WRN-1 Possible free tokens on Ledger 17 WRN-2 Rewards can be lost 18 2.4.COMMENT 19 CMT-1 Unusable variable 19 3.ABOUT MIXBYTES 20 11.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 Lido KSM. 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. 21.2SECURITY ASSESSMENT METHODOLOGY A group of 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: 01Project architecture review: >Reviewing project documentation >General code review >Reverse research and study of the architecture of the code based on the source code only >Mockup prototyping Stage goal: Building an independent view of the project's architecture and identifying logical flaws in the code. 02Checking the code against the checklist of known vulnerabilities: >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 >Checking with static analyzers (i.e Slither, Mythril, etc.) Stage goal: Eliminate typical vulnerabilities (e.g. reentrancy, gas limit, flashloan attacks, etc.) 03Checking the code for compliance with the desired security model: >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 >Exploits PoC development using Brownie Stage goal: Detection of inconsistencies with the desired model 04Consolidation of interim auditor reports into a general one: >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 and 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. 3Findings 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. 41.3PROJECT OVERVIEW Lido KSM is a Liquid staking protocol on the Kusama network (Polkadot) deployed in the Moonriver parachain network. Its purpose is to let users receive income from KSM (DOT) staking without restrictions imposed by the Kusama network, such as blocking liquidity for a long time. Lido is a set of EVM-compatible smart contracts operating in the Moonriver/Moonbeam environment and relay-chain (Kusama/Polkadot) XCMP messages.Lido.sol contract is the core contract which acts as a liquid staking pool. The contract is responsible for xcKSM deposits and withdrawals, minting and burning stKSM, delegating funds to node operators, applying fees, and accepting updates from the oracle contract.The smart contracts reviewed in this audit are designed wherein Lido also acts as an ERC20 token which represents staked xcKSM,stKSM. Tokens are minted upon deposit and burned when redeemed.stKSM tokens are pegged 1:1 to the xcKSM ones that are held by Lido. stKSM tokens balances are updated when the oracle reports change in total stake every era. 1.4PROJECT DASHBOARD Client Lido KSM Audit nameLIDO KSM Initial version76a10efa5f223c4c613f26794802b8fb9bb188e1 130bdc416933cb57ff5bf279e74d3f48decf224e 30b1f028f7e73075845c07f69c70c1cd0926055b Final version2f2725faa0bc371e4d1ddfceacd8c45d8f0905f8 Date November 09, 2021 - February 08, 2022 Auditors engaged3 auditors FILES LISTING AuthManager.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/AuthManager.sol Controller.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/Controller.sol Ledger.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/Ledger.sol 5Lido.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/Lido.sol OracleMaster.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/OracleMaster.sol Oracle.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/Oracle.sol stKSM.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/stKSM.sol LedgerUtils.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/utils/LedgerUtils.s ol ReportUtils.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/contracts/utils/ReportUtils.s ol IAuthManager.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/IAuthManager.sol IController.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/IController.sol ILedger.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/ILedger.sol ILido.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/ILido.sol IOracleMaster.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/IOracleMaster.sol IOracle.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/IOracle.sol IRelayEncoder.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/IRelayEncoder.sol IXcmTransactor.solhttps://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/IXcmTransactor.sol IxTokens.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/IxTokens.sol Types.sol https://github.com/mixbytes/lido-dot-ksm/blob/76a10efa5f22 3c4c613f26794802b8fb9bb188e1/interfaces/Types.sol LedgerFactory.sol https://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/contracts/LedgerFactory.sol 6Withdrawal.sol https://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/contracts/Withdrawal.sol wstKSM.sol https://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/contracts/wstKSM.sol LedgerBeacon.sol https://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/contracts/proxy/LedgerBeacon. sol LedgerProxy.sol https://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/contracts/proxy/LedgerProxy.s ol WithdrawalQueue.solhttps://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/contracts/utils/WithdrawalQue ue.sol IWithdrawal.sol https://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/interfaces/IWithdrawal.sol ILedgerFactory.solhttps://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/interfaces/ILedgerFactory.sol IvKSM.sol https://github.com/mixbytes/lido-dot-ksm/blob/da1accb85e02 8b0d5e1e5ed1c10622e852d9b43b/interfaces/IvKSM.sol FINDINGS SUMMARY Level Amount Critical 2 Major 8 Warning 2 Comment 1 CONCLUSION The smart contracts have been audited and several suspicious places were found. During the audit 2 critical and 7 major issues were identified. Several issues were marked as warnings. Havig worked on the audit report, all issues were fixed by the client. Thus, the contracts are assumed as secure to use according to our security criteria.Final commit identifier with all fixes: 2f2725faa0bc371e4d1ddfceacd8c45d8f0905f8 72.FINDINGS REPORT 2.1CRITICAL CRT-1 Possible underflow File Lido.sol SeverityCritical Status Fixed at 130bdc41 DESCRIPTION If a ledger's stake drammaticaly decreases due to rebalance and after that the ledger receives a huge slash, then underflow can occur: Lido.sol#L608 RECOMMENDATION We recommend distributing slashes across all the ledgers. CLIENT'S COMMENTARY Fixed 8CRT-2 Possible overflow on cast to uint File Lido.sol SeverityCritical Status Fixed at 130bdc41 DESCRIPTION If newStake is a negative number, then overflow can occur: Lido.sol#L730 RECOMMENDATION We recommend checking overall diff in order to exclude such scenarios. CLIENT'S COMMENTARY Fixed 92.2MAJOR MJR-1 Public access to all functions File Controller.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION In contract Controller all functions have public access which can be exploited: Controller.sol RECOMMENDATION We recommend adding access modificators. CLIENT'S COMMENTARY Fixed 1 0MJR-2 Controller can be initialized several times File Controller.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION In contract Controller the initialize function can be called several times: Controller.sol#L140 RECOMMENDATION We recommend adding the initializer modifier. CLIENT'S COMMENTARY Fixed 1 1MJR-3 Incorrect condition File Lido.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION The condition is incorrect here that can lead to an infinite loop: Lido.sol#L748 RECOMMENDATION We recommend changing || into &&. CLIENT'S COMMENTARY Fixed 1 2MJR-4 Possible burn of zero shares File Lido.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION Due to rounding errors a user can burn zero shares: Lido.sol#L522 RECOMMENDATION We recommend adding a check so that a user couldn't burn zero shares. CLIENT'S COMMENTARY Fixed 1 3MJR-5 Possible division by zero File Lido.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION In some cases division by zero can take place here: Lido.sol#L658 Lido.sol#L708 RECOMMENDATION We recommend to set a stake to zero if the overall shares amount is equal to zero. CLIENT'S COMMENTARY Fixed 1 4MJR-6 Insufficient xcKSm balance on Lido File Lido.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION It is possible that Lido can have less than _readyToClaim : Lido.sol#L563 RECOMMENDATION We recommend to add a requirement that Lido would have enough tokens to transfer. CLIENT'S COMMENTARY Fixed 1 5MJR-7 Possible zero balance on Lido File Lido.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION It is possible that Lido can have zero balance on reward distribution: Lido.sol#L588 RECOMMENDATION We recommend to add a check for the case when Lido has zero balance on reward distribution. CLIENT'S COMMENTARY Fixed 1 6MJR-8 Possible underflow File Ledger.sol SeverityMajor Status Fixed at 130bdc41 DESCRIPTION It is possible that free balance from the report can be less than free balance from the previous era: Ledger.sol#L297 RECOMMENDATION We recommend to add a variable to control which amount should be bonded on the next era. CLIENT'S COMMENTARY Fixed 1 72.3WARNING WRN-1 Possible free tokens on Ledger File Ledger.sol SeverityWarning Status Fixed at 130bdc41 DESCRIPTION If someone sends xcKSM to Ledger: Ledger.sol#L282 RECOMMENDATION We recommend sendig excess in funds to treasury. CLIENT'S COMMENTARY Fixed 1 8WRN-2 Rewards can be lost File Lido.sol SeverityWarning Status Fixed at 130bdc41 DESCRIPTION If these addresses have been set to 0, then the rewards can be lost: Lido.sol#L218 Lido.sol#L225 Lido.sol#L318 Lido.sol#L328 RECOMMENDATION We recommend adding a zero address check. CLIENT'S COMMENTARY Fixed 1 92.4COMMENT CMT-1 Unusable variable File Lido.sol SeverityComment Status Fixed at 130bdc41 DESCRIPTION The variable is defined and initialized, but not used in the smart contract: Lido.sol#L201 RECOMMENDATION We recommend removing this variable. CLIENT'S COMMENTARY Fixed 2 03.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 1
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 3 - Major: 8 - Critical: 2 Minor Issues 2.a Problem (one line with code reference): CMT-1 Unusable variable 2.b Fix (one line with code reference): Remove the unused variable Moderate 3.a Problem (one line with code reference): MJR-3 Incorrect condition 3.b Fix (one line with code reference): Change the condition to the correct one Major 4.a Problem (one line with code reference): MJR-1 Public access to all functions 4.b Fix (one line with code reference): Restrict access to certain functions Critical 5.a Problem (one line with code reference): CRT-1 Possible underflow 5.b Fix (one line with code reference): Add a check to prevent underflow Observations - The code was checked against the company's internal checklist of known vulnerabilities - Static analyzers were used to check for vulnerabilities Conclusion The audit found 10 issues, 2 of which were critical, 8 of which were major. All issues were addressed and fixed. 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 567) 2.b Fix: Remove unused variables (line 567) Major None Critical None Observations The code of the project is well-structured and commented. Conclusion The audit of the Lido KSM project revealed no critical, major or moderate issues. Two minor issues were identified and fixed. The code of the project is well-structured and commented. Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 2.a Problem: The stKSM token is not ERC20 compliant (Line 28) 2.b Fix: Make the stKSM token ERC20 compliant Observations: - The Lido smart contracts are designed to act as a liquid staking pool and an ERC20 token - The stKSM token is not ERC20 compliant Conclusion: The Lido smart contracts are designed to act as a liquid staking pool and an ERC20 token. There are two minor issues identified in the audit, which can be fixed by making the stKSM token ERC20 compliant.
pragma solidity >=0.4.21 <0.6.0; import "../utils/Ownable.sol"; import "./IPDispatcher.sol"; import "./IPriceOracle.sol"; import "./IPMBParams.sol"; import "../assets/TokenBankInterface.sol"; import "../erc20/TokenInterface.sol"; import "./IPLiquidate.sol"; import "../utils/SafeMath.sol"; import "../erc20/SafeERC20.sol"; import "../erc20/ERC20Impl.sol"; contract PMintBurn is Ownable{ using SafeMath for uint256; using SafeERC20 for IERC20; struct mbinfo{ address from; uint256 target_token_amount; uint256 stable_token_amount; bool exist; } mapping (bytes32 => mbinfo) public deposits; IPDispatcher public dispatcher; address public target_token; address public stable_token; address public pool; //this is to hold target_token, and should be TokenBank bytes32 public param_key; bytes32 public price_key; bytes32 public liquidate_key; constructor(address _target_token, address _stable_token, address _pool, address _dispatcher) public{ dispatcher = IPDispatcher(_dispatcher); target_token = _target_token; stable_token = _stable_token; pool = _pool; param_key = keccak256(abi.encodePacked(target_token, stable_token, "param")); price_key = keccak256(abi.encodePacked(target_token, stable_token, "price")); liquidate_key = keccak256(abi.encodePacked(target_token, stable_token, "liquidate")); } event PDeposit(address addr, bytes32 hash, uint256 amount, uint256 total); //SWC-Reentrancy: L48-L63 function deposit(uint256 _amount) public returns(bytes32){ bytes32 hash = hash_from_address(msg.sender); IPMBParams param = IPMBParams(dispatcher.getTarget(param_key)); require(_amount >= param.minimum_deposit_amount(), "need to be more than minimum amount"); uint256 prev = IERC20(target_token).balanceOf(pool); IERC20(target_token).safeTransferFrom(msg.sender, pool, _amount); uint256 amount = IERC20(target_token).balanceOf(pool).safeSub(prev); deposits[hash].from = msg.sender; deposits[hash].exist = true; deposits[hash].target_token_amount = deposits[hash].target_token_amount.safeAdd(amount); emit PDeposit(msg.sender, hash, amount, deposits[hash].target_token_amount); return hash; } event PBorrow(address addr, bytes32 hash, uint256 amount); function borrow(uint256 _amount) public returns(bytes32){ bytes32 hash = hash_from_address(msg.sender); IPMBParams param = IPMBParams(dispatcher.getTarget(param_key)); IPriceOracle price = IPriceOracle(dispatcher.getTarget(price_key)); require(price.getPrice() > 0, "price not set"); uint256 m = price.getPrice().safeMul(deposits[hash].target_token_amount).safeMul(param.ratio_base()).safeDiv(uint(10)**ERC20Base(target_token).decimals()).safeDiv(param.mortgage_ratio()); require(_amount <= m.safeSub(deposits[hash].stable_token_amount), "no left quota"); deposits[hash].stable_token_amount = deposits[hash].stable_token_amount.safeAdd(_amount); TokenInterface(stable_token).generateTokens(msg.sender, _amount); emit PBorrow(msg.sender, hash, _amount); return hash; } event PRepay(address addr, bytes32 hash, uint256 amount); function repay(uint256 _amount) public returns(bytes32){ require(IERC20(stable_token).balanceOf(msg.sender) >= _amount, "no enough stable coin"); bytes32 hash = hash_from_address(msg.sender); require(_amount <= deposits[hash].stable_token_amount, "repay too much"); deposits[hash].stable_token_amount = deposits[hash].stable_token_amount.safeSub(_amount); TokenInterface(stable_token).destroyTokens(msg.sender, _amount); emit PRepay(msg.sender, hash, _amount); return hash; } event PWithdraw(address addr, bytes32 hash, uint256 amount, uint256 fee); function withdraw(uint256 _amount) public returns(bytes32){ bytes32 hash = hash_from_address(msg.sender); IPMBParams param = IPMBParams(dispatcher.getTarget(param_key)); IPriceOracle price = IPriceOracle(dispatcher.getTarget(price_key)); uint256 m = deposits[hash].stable_token_amount.safeMul(uint256(10)**ERC20Base(target_token).decimals()).safeMul(param.mortgage_ratio()).safeDiv(price.getPrice()).safeDiv(param.ratio_base()); require(m + _amount <= deposits[hash].target_token_amount, "claim too much"); deposits[hash].target_token_amount = deposits[hash].target_token_amount.safeSub(_amount); if(param.withdraw_fee_ratio() != 0 && param.plut_fee_pool() != address(0x0)){ uint256 t = _amount.safeMul(param.withdraw_fee_ratio()).safeDiv(param.ratio_base()); TokenBankInterface(pool).issue(target_token, msg.sender, _amount.safeSub(t)); TokenBankInterface(pool).issue(target_token, param.plut_fee_pool(), t); emit PWithdraw(msg.sender, hash, _amount.safeSub(t), t); }else{ TokenBankInterface(pool).issue(target_token, msg.sender, _amount); emit PWithdraw(msg.sender, hash, _amount, 0); } return hash; } event PLiquidate(address addr, bytes32 hash, uint256 target_amount, uint256 stable_amount); function liquidate(bytes32 _hash, uint256 _target_amount) public returns(bytes32){ IPMBParams param = IPMBParams(dispatcher.getTarget(param_key)); IPriceOracle price = IPriceOracle(dispatcher.getTarget(price_key)); IPLiquidate lq = IPLiquidate(dispatcher.getTarget(liquidate_key)); bytes32 hash = _hash; require(deposits[hash].exist, "hash not exist"); require(_target_amount <= deposits[hash].target_token_amount, "too much target token"); uint256 m = price.getPrice().safeMul(deposits[hash].target_token_amount).safeMul(param.ratio_base()).safeDiv(uint(10)**ERC20Base(target_token).decimals()).safeDiv(param.mortgage_ratio()); require(m < deposits[hash].stable_token_amount, "mortgage ratio is high, cannot liquidate"); uint256 stable_amount = deposits[hash].stable_token_amount.safeMul(_target_amount).safeDiv(deposits[hash].target_token_amount); require(stable_amount > 0, "nothing to liquidate"); lq.liquidate_asset(msg.sender,_target_amount, stable_amount); deposits[hash].target_token_amount = deposits[hash].target_token_amount.safeSub(_target_amount); deposits[hash].stable_token_amount = deposits[hash].stable_token_amount.safeSub(stable_amount); emit PLiquidate(msg.sender, hash, _target_amount, stable_amount); return hash; } function get_liquidate_stable_amount(bytes32 _hash, uint256 _target_amount) public view returns(uint256){ bytes32 hash = _hash; if(!deposits[hash].exist) { return 0; } require(_target_amount <= deposits[hash].target_token_amount, "too much target token"); uint256 stable_amount = deposits[hash].stable_token_amount.safeMul(_target_amount).safeDiv(deposits[hash].target_token_amount); return stable_amount; } function is_liquidatable(bytes32 _hash) public view returns(bool){ bytes32 hash = _hash; IPMBParams param = IPMBParams(dispatcher.getTarget(param_key)); IPriceOracle price = IPriceOracle(dispatcher.getTarget(price_key)); if(!deposits[hash].exist){ return false; } uint256 m = price.getPrice().safeMul(deposits[hash].target_token_amount).safeMul(param.ratio_base()).safeDiv(uint(10)**ERC20Base(target_token).decimals()).safeDiv(param.mortgage_ratio()); if(m < deposits[hash].stable_token_amount){ return true; } return false; } function hash_from_address(address _addr) public pure returns(bytes32){ return keccak256(abi.encodePacked("plutos", _addr)); } } pragma solidity >=0.4.21 <0.6.0; import "../utils/Ownable.sol"; contract PDispatcher is Ownable{ mapping (bytes32 => address ) public targets; constructor() public{} event TargetChanged(bytes32 key, address old_target, address new_target); function resetTarget(bytes32 _key, address _target) public onlyOwner{ address old = address(targets[_key]); targets[_key] = _target; emit TargetChanged(_key, old, _target); } function getTarget(bytes32 _key) public view returns (address){ return targets[_key]; } } contract PDispatcherFactory{ event NewPDispatcher(address addr); function createHDispatcher() public returns(address){ PDispatcher dis = new PDispatcher(); dis.transferOwnership(msg.sender); emit NewPDispatcher(address(dis)); return address(dis); } } pragma solidity >=0.4.21 <0.6.0; import "../utils/Ownable.sol"; contract PNaivePriceOracle is Ownable{ //price of per 10**decimals() uint256 public price; function setPrice(uint256 _price) public onlyOwner{ price = _price; } function getPrice() public view returns(uint256){ return price; } } pragma solidity >=0.4.21 <0.6.0; contract IPMBParams{ uint256 public ratio_base; uint256 public withdraw_fee_ratio; uint256 public mortgage_ratio; uint256 public liquidate_fee_ratio; uint256 public minimum_deposit_amount; address payable public plut_fee_pool; } pragma solidity >=0.4.21 <0.6.0; import "../utils/Ownable.sol"; contract PMBParams is Ownable{ uint256 public ratio_base; uint256 public withdraw_fee_ratio; uint256 public mortgage_ratio; uint256 public liquidate_fee_ratio; uint256 public minimum_deposit_amount; address payable public plut_fee_pool; constructor() public{ ratio_base = 1000000; minimum_deposit_amount = 0; } function changeWithdrawFeeRatio(uint256 _ratio) public onlyOwner{ require(_ratio < ratio_base, "too large"); withdraw_fee_ratio = _ratio; } function changeMortgageRatio(uint256 _ratio) public onlyOwner{ require(_ratio > ratio_base, "too small"); mortgage_ratio = _ratio; } function changeLiquidateFeeRatio(uint256 _ratio) public onlyOwner{ require(_ratio < ratio_base, "too large"); liquidate_fee_ratio = _ratio; } function changeMinimumDepositAmount(uint256 _amount) public onlyOwner{ minimum_deposit_amount = _amount; } function changePlutFeePool(address payable _pool) public onlyOwner{ plut_fee_pool = _pool; } } pragma solidity >=0.4.21 <0.6.0; contract IPriceOracle{ //price of per 10**decimals() function getPrice() public view returns(uint256); } pragma solidity >=0.4.21 <0.6.0; contract IPDispatcher{ function getTarget(bytes32 _key) public view returns (address); } pragma solidity >=0.4.21 <0.6.0; contract IPLiquidate{ function liquidate_asset(address payable _sender, uint256 _target_amount, uint256 _stable_amount) public ; } pragma solidity >=0.4.21 <0.6.0; import "../utils/Ownable.sol"; import "./IPDispatcher.sol"; import "./IPLiquidate.sol"; import "./IPMBParams.sol"; import "../assets/TokenBankInterface.sol"; import "../erc20/TokenInterface.sol"; import "../utils/SafeMath.sol"; import "../erc20/IERC20.sol"; //SWC-Code With No Effects: L11-L12 contract PLiquidateAgent is Ownable{ using SafeMath for uint256; address public target_token; address public target_token_pool; address public stable_token; address public target_fee_pool; IPDispatcher public dispatcher; address public caller; bytes32 public param_key; constructor(address _target_token, address _target_token_pool, address _stable_token, address _dispatcher) public{ target_token = _target_token; target_token_pool = _target_token_pool; stable_token = _stable_token; dispatcher = IPDispatcher(_dispatcher); param_key = keccak256(abi.encodePacked(target_token, stable_token, "param")); } modifier onlyCaller{ require(msg.sender == caller, "not caller"); _; } function liquidate_asset(address payable _sender, uint256 _target_amount, uint256 _stable_amount) public onlyCaller{ IPMBParams param = IPMBParams(dispatcher.getTarget(param_key)); require(IERC20(stable_token).balanceOf(_sender) >= _stable_amount, "insufficient stable token"); TokenInterface(stable_token).destroyTokens(_sender, _stable_amount); if(param.liquidate_fee_ratio() != 0 && param.plut_fee_pool() != address(0x0)){ uint256 t = param.liquidate_fee_ratio().safeMul(_target_amount).safeDiv(param.ratio_base()); TokenBankInterface(target_token_pool).issue(target_token, param.plut_fee_pool(), t); TokenBankInterface(target_token_pool).issue(target_token, _sender, _target_amount.safeSub(t)); }else{ TokenBankInterface(target_token_pool).issue(target_token, _sender, _target_amount); } } function changeCaller(address _caller) public onlyOwner{ caller = _caller; } } pragma solidity >=0.4.21 <0.6.0; import "../utils/Ownable.sol"; import "../assets/TokenBankInterface.sol"; import "../erc20/TokenInterface.sol"; import "../erc20/IERC20.sol"; import "../erc20/SafeERC20.sol"; import "../utils/SafeMath.sol"; import "../erc20/ERC20Impl.sol"; contract ERC20StakingCallbackInterface{ function onStake(address addr, uint256 target_amount, uint256 lp_amount) public returns(bool); function onClaim(address addr, uint256 target_amount, uint256 lp_amount) public returns(bool); } contract ERC20Staking is Ownable{ using SafeMath for uint256; using SafeERC20 for IERC20; address public target_token; address public lp_token; ERC20StakingCallbackInterface public callback; constructor(address _target_token, address _lp_token) public{ target_token = _target_token; lp_token = _lp_token; callback = ERC20StakingCallbackInterface(0x0); } event ERC20StakingChangeCallback(address _old, address _new); function changeCallback(address addr) public onlyOwner returns(bool){ address old = address(callback); callback = ERC20StakingCallbackInterface(addr); emit ERC20StakingChangeCallback(old, addr); return true; } event ERC20Stake(address addr, uint256 target_amount, uint256 lp_amount); function stake(uint256 _amount) public returns(uint256){ uint256 amount = 0; uint256 prev = IERC20(target_token).balanceOf(address(this)); IERC20(target_token).safeTransferFrom(msg.sender, address(this), _amount); amount = IERC20(target_token).balanceOf(address(this)).safeSub(prev); if(amount == 0){ return 0; } uint256 lp_amount = 0; { if(IERC20(lp_token).totalSupply() == 0){ lp_amount = amount.safeMul(uint256(10)**ERC20Base(lp_token).decimals()).safeDiv(uint256(10)**ERC20Base(target_token).decimals()); }else{ uint256 t2 = IERC20(lp_token).totalSupply(); lp_amount = amount.safeMul(t2).safeDiv(prev); } } if(lp_amount == 0){ return 0; } TokenInterface(lp_token).generateTokens(msg.sender, lp_amount); if(address(callback) != address(0x0)){ callback.onStake(msg.sender, amount, lp_amount); } emit ERC20Stake(msg.sender, amount, lp_amount); return lp_amount; } event ERC20Claim(address addr, uint256 target_amount, uint256 lp_amount); function claim(uint256 _amount) public returns(uint256){ uint256 total = IERC20(lp_token).totalSupply(); require(IERC20(lp_token).balanceOf(msg.sender) >= _amount, "not enough lp token to claim"); TokenInterface(lp_token).destroyTokens(msg.sender, _amount); uint256 amount = 0; { if(IERC20(lp_token).totalSupply() == 0){ amount = IERC20(target_token).balanceOf(address(this)); }else{ amount = _amount.safeMul(IERC20(target_token).balanceOf(address(this))).safeDiv(total); } } IERC20(target_token).safeTransfer(msg.sender, amount); if(address(callback) != address(0x0)){ callback.onClaim(msg.sender, amount, _amount); } emit ERC20Claim(msg.sender, amount, _amount); return amount; } event ERC20IncreaseTargetToken(address addr, uint256 amount); //We add this method to keep interface clean function increase_target_token(uint256 _amount) public returns(bool){ IERC20(target_token).safeTransferFrom(msg.sender, address(this), _amount); emit ERC20IncreaseTargetToken(msg.sender, _amount); return true; } function getPricePerFullShare() public view returns(uint256){ return IERC20(target_token).balanceOf(address(this)).safeMul(1e18).safeMul(uint256(10)**ERC20Base(lp_token).decimals()).safeDiv(IERC20(lp_token).totalSupply()).safeDiv(uint256(10)**ERC20Base(target_token).decimals()); } } contract ERC20StakingFactory{ event NewERC20Staking(address addr); function createERC20Staking(address _target_token, address _lp_token) public returns(address){ ERC20Staking s = new ERC20Staking(_target_token, _lp_token); emit NewERC20Staking(address(s)); s.transferOwnership(msg.sender); return address(s); } }
Public SMART CONTRACT AUDIT REPORT for Plutos V1 Prepared By: Yiqun Chen PeckShield September 20, 2021 1/19 PeckShield Audit Report #: 2021-282Public Document Properties Client Plutos Network Title Smart Contract Audit Report Target Plutos V1 Version 1.0 Author Shulin Bie Auditors Shulin Bie, Xuxian Jiang Reviewed by Yiqun Chen Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 September 20, 2021 Shulin Bie 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/19 PeckShield Audit Report #: 2021-282Public Contents 1 Introduction 4 1.1 About Plutos V1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Possible Costly lp_token From Improper Staking Initialization . . . . . . . . . . . . . 11 3.2 Redundant State/Code Removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.3 Trust Issue Of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3.4 Potential Reentrancy Risk In Plutos Implementation . . . . . . . . . . . . . . . . . . 15 4 Conclusion 17 References 18 3/19 PeckShield Audit Report #: 2021-282Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the Plutos V1 , 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 Plutos V1 Plutos Network is a multi-chain synthetic issuance & derivative trading platform, which introduces mining incentives and staking rewards to users. The Plutos V1 protocol is an important feature of Plutos Network , which provides decentralized PLUT/pUSD mortgage and lending service. The Plutos V1 protocol enriches the Plutos Network ecosystem and also presents a unique contribution to current DeFi ecosystem. The basic information of Plutos V1 is as follows: Table 1.1: Basic Information of Plutos V1 ItemDescription Target Plutos V1 TypeSmart Contract Language Solidity Audit Method Whitebox Latest Audit Report September 20, 2021 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit. •https://gitlab.com/asresearch/plutos-eth-contract.git (0777815) 4/19 PeckShield Audit Report #: 2021-282Public And this is the commit ID after all fixes for the issues found in the audit have been checked in: •https://gitlab.com/asresearch/plutos-eth-contract.git (5a5601d) 1.2 About PeckShield PeckShield Inc. [11] 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 [10]: •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/19 PeckShield Audit Report #: 2021-282Public 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/19 PeckShield Audit Report #: 2021-282Public 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) [9], 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/19 PeckShield Audit Report #: 2021-282Public 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/19 PeckShield Audit Report #: 2021-282Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the Plutos V1 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 1 Low 2 Informational 1 Undetermined 0 Total 4 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/19 PeckShield Audit Report #: 2021-282Public 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, 2low-severity vulnerabilities, and 1informational recommendation. Table 2.1: Key Plutos V1 Audit Findings ID Severity Title Category Status PVE-001 Medium Possible Costly lp_token From Improper StakingInitializationTime and State Mitigated PVE-002 Informational Redundant State/Code Removal Coding Practices Fixed PVE-003 Low TrustIssueOfAdminKeys Security Features Confirmed PVE-004 Low Potential Reentrancy RiskInPlutos ImplementationTime and State Fixed 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/19 PeckShield Audit Report #: 2021-282Public 3 | Detailed Results 3.1 Possible Costly lp_token From Improper Staking Initialization •ID: PVE-001 •Severity: Medium •Likelihood: Low •Impact: High•Target: ERC20Staking •Category: Time and State [6] •CWE subcategory: CWE-362 [3] Description The ERC20Staking contract allows users to stake the supported target_token tokens and get in return lp_token tokens to represent the pool shares. While examining the share calculation with the given stakes, we notice an issue that may unnecessarily make the pool token extremely expensive and bring hurdles (or even causes loss) for later stakers. To elaborate, we show below the related code snippet of the ERC20Staking contract. The stake() routine is used for participating users to stake the supported asset and get respective lp_token in return. The issue occurs when the pool is being initialized under the assumption that the current pool is empty. 39 function stake ( uint256 _amount ) public returns ( uint256 ){ 40 uint256 amount = 0; 41 uint256 prev = IERC20 ( target_token ). balanceOf ( address ( this )); 42 IERC20 ( target_token ). safeTransferFrom ( msg . sender , address ( this ), _amount ); 43 amount = IERC20 ( target_token ). balanceOf ( address ( this )). safeSub ( prev ); 45 if( amount == 0){ 46 return 0; 47 } 49 uint256 lp_amount = 0; 50 { 51 if( IERC20 ( lp_token ). totalSupply () == 0){ 11/19 PeckShield Audit Report #: 2021-282Public 52 lp_amount = amount . safeMul ( uint256 (10) ** ERC20Base ( lp_token ). decimals ()). safeDiv ( uint256 (10) ** ERC20Base ( target_token ). decimals ()); 53 } else { 54 uint256 t2 = IERC20 ( lp_token ). totalSupply (); 55 lp_amount = amount . safeMul (t2). safeDiv ( prev ); 56 } 57 } 58 if( lp_amount == 0){ 59 return 0; 60 } 62 TokenInterface ( lp_token ). generateTokens (msg .sender , lp_amount ); 64 if( address ( callback ) != address (0 x0)){ 65 callback . onStake (msg .sender , amount , lp_amount ); 66 } 68 emit ERC20Stake ( msg . sender , amount , lp_amount ); 69 return lp_amount ; 70 } Listing 3.1: ERC20Staking::stake() Specifically, when the pool is being initialized, the lp_amount share value directly takes the value ofamount(line 52), which is under control by the malicious actor. As this is the first stake, the cur- rent total supply equals the calculated lp_amount = amount.safeMul(uint256(10)**ERC20Base(lp_token) .decimals()).safeDiv(uint256(10)**ERC20Base(target_token).decimals())= 1WEI . With that, the actor can further transfer a huge amount of target_token tokens to ERC20Staking contract with the goal of making the lp_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 staked assets. If truncated to be zero, the staked 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 stake()to defensively calculate the share amount when the pool is being initialized. An alternative solution is to ensure guarded launch that safeguards the first stake to avoid being manipulated. Status The issue has been addressed by the following commit: 5a5601d. 12/19 PeckShield Audit Report #: 2021-282Public 3.2 Redundant State/Code Removal •ID: PVE-002 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: PLiquidateAgent •Category: Coding Practices [7] •CWE subcategory: CWE-1041 [1] Description In the Plutosimplementation, the PLiquidateAgent contract is designed to provide the interface used to liquidate assets for the PMintBurn contract. While examining the logics of it, we observe the inclusion of certain unused code or the presence of unnecessary redundancies that can be safely removed. To elaborate, we show below the related code snippet of the PLiquidateAgent contract. The public target_fee_pool storage variable is declared (line 17), but is not used in the contract. We suggest to remove it safely to keep the Plutosimplementation clean. 11 contract PLiquidateAgent is Ownable { 13 using SafeMath for uint256 ; 14 address public target_token ; 15 address public target_token_pool ; 16 address public stable_token ; 17 address public target_fee_pool ; 19 ... 21 } Listing 3.2: PLiquidateAgent Recommendation Consider the removal of the redundant state. Status The issue has been addressed by the following commit: 5a5601d. 13/19 PeckShield Audit Report #: 2021-282Public 3.3 Trust Issue Of Admin Keys •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Security Features [5] •CWE subcategory: CWE-287 [2] Description In the Plutosimplementation, there is a privileged owneraccount that plays a critical role in governing and regulating the protocol-wide operations (e.g., configuring various system parameters). In the following, we show the representative functions potentially affected by the privilege of the account. 31 function changeCallback ( address addr ) public onlyOwner returns ( bool ){ 32 address old = address ( callback ); 33 callback = ERC20StakingCallbackInterface ( addr ); 34 emit ERC20StakingChangeCallback (old , addr ); 35 return true ; 36 } Listing 3.3: ERC20Staking::changeCallback() 11 function resetTarget ( bytes32 _key , address _target ) public onlyOwner { 12 address old = address ( targets [ _key ]); 13 targets [ _key ] = _target ; 14 emit TargetChanged (_key , old , _target ); 15 } Listing 3.4: PDispatcher::resetTarget() We emphasize that the privilege assignment may be necessary and consistent with the protocol design. However, itisworrisomeiftheprivileged owneraccountisnotgovernedbya DAO-likestructure. Note that a compromised account would allow the attacker to modify a number of sensitive system parameters, which directly undermines the assumption of the Plutosdesign. Recommendation Promptly transfer the privileged owneraccount 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 intended trustless nature and high-quality distributed governance. Status This issue has been confirmed by the team. The privileged owneraccount will be managed by a multi-sig account. 14/19 PeckShield Audit Report #: 2021-282Public 3.4 Potential Reentrancy Risk In Plutos Implementation •ID: PVE-004 •Severity: Low •Likelihood: Low •Impact:Medium•Target: Multiple Contracts •Category: Time and State [8] •CWE subcategory: CWE-682 [4] 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 invoking functions that should only be executed once. This attack was part of several most prominent hacks in Ethereum history, including the DAO[13] exploit, and the recent Uniswap/Lendf.Me hack [12]. In the Plutosimplementation, we notice there are several functions that have potential reentrancy risk. In the following, we take the PMintBurn::deposit() routine as an example. To elaborate, we show below the code snippet of the deposit() routine in the PMintBurn contract. In the function, the IERC20(target_token).safeTransferFrom(msg.sender, pool, _amount) is called (line 54) to transfer the target_token to the pool. If the target_token faithfully implements the ERC777-like standard, then the PMintBurn::deposit() routine is vulnerable to reentrancy and this risk needs to be properly mitigated. 47 function deposit ( uint256 _amount ) public returns ( bytes32 ){ 48 bytes32 hash = hash_from_address ( msg. sender ); 49 IPMBParams param = IPMBParams ( dispatcher . getTarget ( param_key )); 50 51 require ( _amount >= param . minimum_deposit_amount () , " need to be more than minimum amount "); 52 53 uint256 prev = IERC20 ( target_token ). balanceOf ( pool ); 54 IERC20 ( target_token ). safeTransferFrom ( msg . sender , pool , _amount ); 55 uint256 amount = IERC20 ( target_token ). balanceOf ( pool ). safeSub ( prev ); 56 57 deposits [ hash ]. from = msg . sender ; 58 deposits [ hash ]. exist = true ; 59 deposits [ hash ]. target_token_amount = deposits [ hash ]. target_token_amount . safeAdd ( amount ); 60 emit PDeposit (msg. sender , hash , amount , deposits [ hash ]. target_token_amount ); 61 return hash ; 62 } Listing 3.5: PMintBurn::deposit() 15/19 PeckShield Audit Report #: 2021-282Public 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 IERC20(target_token).safeTransferFrom(msg.sender , pool, _amount) (line 54). By doing so, we can effectively keep previntact (used for the calculation of actual target_token amount transferred to the poolat line 55). With a lower prev, the re-entered PMintBurn::deposit() is able to obtain more deposit credits. It can be repeated to exploit this vulnerability for gains, just like earlier Uniswap/imBTC hack [12]. Note the ERC20Staking::stake()/claim() routines share the same issue. Moreover, we also suggest to add necessary reentrancy guards for other public functions, i.e., PMintBurn::borrow()/repay()/withdraw()/liquidate() asUniswapV2 does. Recommendation Add necessary reentrancy guards to prevent unwanted reentrancy risks. Status The issue has been addressed by the following commit: 5a5601d. 16/19 PeckShield Audit Report #: 2021-282Public 4 | Conclusion In this audit, we have analyzed the Plutos V1 design and implementation. Plutos Network is a multi- chainsyntheticissuance&derivativetradingplatform, whichintroducesminingincentivesandstaking rewards to users. The Plutos V1 protocol is an important feature of Plutos Network , which provides decentralized PLUT/pUSD mortgage and lending service. The Plutos V1 protocol enriches the Plutos Networkecosystem and also presents a unique contribution to current DeFi ecosystem. 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. 17/19 PeckShield Audit Report #: 2021-282Public 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-362: ConcurrentExecutionusingSharedResourcewithImproperSynchronization (’Race Condition’). https://cwe.mitre.org/data/definitions/362.html. [4] MITRE. CWE-682: Incorrect Calculation. https://cwe.mitre.org/data/definitions/682.html. [5] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.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: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html. [9] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. 18/19 PeckShield Audit Report #: 2021-282Public [10] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [11] PeckShield. PeckShield Inc. https://www.peckshield.com. [12] PeckShield. Uniswap/Lendf.Me Hacks: Root Cause and Loss Analysis. https://medium.com/ @peckshield/uniswap-lendf-me-hacks-root-cause-and-loss-analysis-50f3263dcc09. [13] David Siegel. Understanding The DAO Attack. https://www.coindesk.com/ understanding-dao-hack-journalists. 19/19 PeckShield Audit Report #: 2021-282
Issues Count of Minor/Moderate/Major/Critical: - Minor: 1 - Moderate: 1 - Major: 1 - Critical: 1 Minor Issues: - Problem: Possible costly lp_token from improper staking initialization (line 11) - Fix: Add a check to ensure that the lp_token is not initialized with a value greater than 0 (line 11) Moderate Issues: - Problem: Redundant state/code removal (line 13) - Fix: Remove the redundant state/code (line 13) Major Issues: - Problem: Trust issue of admin keys (line 14) - Fix: Add a check to ensure that the admin keys are not used for any malicious activities (line 14) Critical Issues: - Problem: Potential reentrancy risk in Plutos implementation (line 15) - Fix: Add a check to ensure that the Plutos implementation is not vulnerable to reentrancy attacks (line 15) Observations: - The Plutos V1 protocol is an important feature of Plutos Network, which provides decentralized PLUT/pUSD mortgage and lending service. Conclusion 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): Lack of checks for overflow and underflow conditions (Lines 5-7, 10-12, 15-17, 20-22, 25-27, 30-32, 35-37, 40-42, 45-47, 50-52, 55-57, 60-62, 65-67, 70-72, 75-77, 80-82, 85-87, 90-92, 95-97, 100-102, 105-107, 110-112, 115-117, 120-122, 125-127, 130-132, 135-137, 140-142, 145-147, 150-152, 155-157, 160-162, 165-167, 170-172, 175-177, 180-182, 185-187, 190-192, 195-197, 200-202, 205-207, 210-212, 215-217, 220-222, 225-227, 230-232, 235-237, 240-242, 245-247 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): Constructor Mismatch (CWE-699) 2.b Fix (one line with code reference): Ensure that the constructor is properly defined and called. Observations: - We statically analyze given smart contracts with our proprietary static code analyzer for known coding bugs. - We manually check the logic of implemented smart contracts and compare with the description in the white paper. - We review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. - We provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. Conclusion: No issues of Minor/Moderate/Major/Critical were found in the given smart contracts.
//SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./DYTokenBase.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IDepositVault.sol"; contract DYTokenERC20 is DYTokenBase { using SafeERC20 for IERC20; constructor(address _underlying, string memory _symbol, address _controller) DYTokenBase(_underlying, _symbol, _controller) { } function depositCoin(address _to, address _toVault) public override payable { revert("DO_NOT_DEPOSIT_COIN"); } function deposit(uint _amount, address _toVault) external override { depositTo(msg.sender, _amount, _toVault); } //SWC-Transaction Order Dependence: L29-L57 function depositTo(address _to, uint _amount, address _toVault) public override { uint total = underlyingTotal(); IERC20 underlyingToken = IERC20(underlying); uint before = underlyingToken.balanceOf(address(this)); underlyingToken.safeTransferFrom(msg.sender, address(this), _amount); uint realAmount = underlyingToken.balanceOf(address(this)) - before; // Additional check for deflationary tokens require(realAmount >= _amount, "illegal amount"); uint shares = 0; if (totalSupply() == 0) { require(_amount >= 10000, "too small"); shares = _amount; } else { shares = _amount * totalSupply() / total; } require(shares > 0, "ZERO_SHARE"); if(_toVault != address(0)) { require(_toVault == IController(controller).dyTokenVaults(address(this)), "mismatch dToken vault"); _mint(_toVault, shares); IDepositVault(_toVault).syncDeposit(address(this), shares, _to); } else { _mint(_to, shares); } earn(); } function withdraw(address _to, uint _shares, bool ) public override { require(_shares > 0, "shares need > 0"); require(totalSupply() > 0, "no deposit"); uint r = underlyingTotal() * _shares / totalSupply(); _burn(msg.sender, _shares); uint b = IERC20(underlying).balanceOf(address(this)); // need withdraw from strategy if (b < r) { uint withdrawAmount = r - b; address strategy = IController(controller).strategies(underlying); if (strategy!= address(0)) { IStrategy(strategy).withdraw(withdrawAmount); } uint withdrawed = IERC20(underlying).balanceOf(address(this)) - b; if (withdrawed < withdrawAmount) { r = b + withdrawed; } } IERC20(underlying).safeTransfer(_to, r); } function earn() public override { uint b = IERC20(underlying).balanceOf(address(this)); address strategy = IController(controller).strategies(underlying); if (strategy != address(0)) { IERC20(underlying).safeTransfer(strategy, b); IStrategy(strategy).deposit(); } } }// SPDX-License-Identifier: MIT pragma solidity >= 0.8.0; import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/IPair.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IRouter02.sol"; import "./interfaces/IPancakeFactory.sol"; import "./interfaces/IController.sol"; import "./interfaces/IDYToken.sol"; contract DuetZap is OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; IRouter02 private router; IPancakeFactory private factory; address private wbnb; IController public controller; event ZapToLP(address token, uint amount, address lp, uint liquidity); /* ========== STATE VARIABLES ========== */ mapping(address => address) private routePairAddresses; /* ========== INITIALIZER ========== */ function initialize(address _controller, address _factory, address _router, address _wbnb) external initializer { __Ownable_init(); require(owner() != address(0), "Zap: owner must be set"); controller = IController(_controller); factory = IPancakeFactory(_factory); router = IRouter02(_router); wbnb = _wbnb; } receive() external payable {} /* ========== View Functions ========== */ function routePair(address _address) external view returns(address) { return routePairAddresses[_address]; } /* ========== External Functions ========== */ function tokenToLp(address _token, uint amount, address _lp, bool needDeposit) external { address receiver = msg.sender; if (needDeposit) { receiver = address(this); } IERC20Upgradeable(_token).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_token, address(router), amount); IPair pair = IPair(_lp); address token0 = pair.token0(); address token1 = pair.token1(); require(factory.getPair(token0, token1) == _lp, "NO_PAIR"); uint liquidity; if (_token == token0 || _token == token1) { // swap half amount for other address other = _token == token0 ? token1 : token0; _approveTokenIfNeeded(other, address(router), amount); uint sellAmount = amount / 2; uint otherAmount = _swap(_token, sellAmount, other, address(this)); pair.skim(address(this)); (, , liquidity) = router.addLiquidity(_token, other, amount - sellAmount, otherAmount, 0, 0, receiver, block.timestamp); } else { uint bnbAmount = _token == wbnb ? _safeSwapToBNB(amount) : _swapTokenForBNB(_token, amount, address(this)); liquidity = _swapBNBToLp(_lp, bnbAmount, receiver); } emit ZapToLP(_token, amount, _lp, liquidity); if (needDeposit) { deposit(_lp, liquidity, msg.sender); } } function coinToLp(address _lp, bool needDeposit) external payable returns (uint liquidity){ if (!needDeposit) { liquidity = _swapBNBToLp(_lp, msg.value, msg.sender); emit ZapToLP(address(0), msg.value, _lp, liquidity); } else { liquidity = _swapBNBToLp(_lp, msg.value, address(this)); emit ZapToLP(address(0), msg.value, _lp, liquidity); deposit(_lp, liquidity, msg.sender); } } function tokenToToken(address _token, uint _amount, address _to, bool needDeposit) external returns (uint amountOut){ IERC20Upgradeable(_token).safeTransferFrom(msg.sender, address(this), _amount); _approveTokenIfNeeded(_token, address(router), _amount); if (needDeposit) { amountOut = _swap(_token, _amount, _to, address(this)); deposit(_to, amountOut, msg.sender); } else { amountOut = _swap(_token, _amount, _to, msg.sender); } } // unpack lp function zapOut(address _from, uint _amount) external { IERC20Upgradeable(_from).safeTransferFrom(msg.sender, address(this), _amount); _approveTokenIfNeeded(_from, address(router), _amount); IPair pair = IPair(_from); address token0 = pair.token0(); address token1 = pair.token1(); if (pair.balanceOf(_from) > 0) { pair.burn(address(this)); } if (token0 == wbnb || token1 == wbnb) { router.removeLiquidityETH(token0 != wbnb ? token0 : token1, _amount, 0, 0, msg.sender, block.timestamp); } else { router.removeLiquidity(token0, token1, _amount, 0, 0, msg.sender, block.timestamp); } } /* ========== Private Functions ========== */ function deposit(address token, uint amount, address toUser) private { address dytoken = controller.dyTokens(token); require(dytoken != address(0), "NO_DYTOKEN"); address vault = controller.dyTokenVaults(dytoken); require(vault != address(0), "NO_VAULT"); _approveTokenIfNeeded(token, dytoken, amount); IDYToken(dytoken).depositTo(toUser, amount, vault); } function _approveTokenIfNeeded(address token, address spender, uint amount) private { uint allowed = IERC20Upgradeable(token).allowance(address(this), spender); if (allowed == 0) { IERC20Upgradeable(token).safeApprove(spender, type(uint).max); } else if (allowed < amount) { IERC20Upgradeable(token).safeApprove(spender, 0); IERC20Upgradeable(token).safeApprove(spender, type(uint).max); } } function _swapBNBToLp(address lp, uint amount, address receiver) private returns (uint liquidity) { IPair pair = IPair(lp); address token0 = pair.token0(); address token1 = pair.token1(); if (token0 == wbnb || token1 == wbnb) { address token = token0 == wbnb ? token1 : token0; uint swapValue = amount / 2; uint tokenAmount = _swapBNBForToken(token, swapValue, address(this)); _approveTokenIfNeeded(token, address(router), tokenAmount); pair.skim(address(this)); (, , liquidity) = router.addLiquidityETH{value : amount -swapValue }(token, tokenAmount, 0, 0, receiver, block.timestamp); } else { uint swapValue = amount / 2; uint token0Amount = _swapBNBForToken(token0, swapValue, address(this)); uint token1Amount = _swapBNBForToken(token1, amount - swapValue, address(this)); _approveTokenIfNeeded(token0, address(router), token0Amount); _approveTokenIfNeeded(token1, address(router), token1Amount); pair.skim(address(this)); (, , liquidity) = router.addLiquidity(token0, token1, token0Amount, token1Amount, 0, 0, receiver, block.timestamp); } } function _swapBNBForToken(address token, uint value, address receiver) private returns (uint) { address[] memory path; if (routePairAddresses[token] != address(0)) { path = new address[](3); path[0] = wbnb; path[1] = routePairAddresses[token]; path[2] = token; } else { path = new address[](2); path[0] = wbnb; path[1] = token; } uint[] memory amounts = router.swapExactETHForTokens{value : value}(0, path, receiver, block.timestamp); return amounts[amounts.length - 1]; } function _swapTokenForBNB(address token, uint amount, address receiver) private returns (uint) { address[] memory path; if (routePairAddresses[token] != address(0)) { path = new address[](3); path[0] = token; path[1] = routePairAddresses[token]; path[2] = wbnb; } else { path = new address[](2); path[0] = token; path[1] = wbnb; } uint[] memory amounts = router.swapExactTokensForETH(amount, 0, path, receiver, block.timestamp); return amounts[amounts.length - 1]; } function _swap(address _from, uint amount, address _to, address receiver) private returns (uint) { address intermediate = routePairAddresses[_from]; if (intermediate == address(0)) { intermediate = routePairAddresses[_to]; } address[] memory path; if (intermediate == address(0) || _from == intermediate || _to == intermediate ) { // [DUET, BUSD] or [BUSD, DUET] path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = intermediate; path[2] = _to; } uint[] memory amounts = router.swapExactTokensForTokens(amount, 0, path, receiver, block.timestamp); return amounts[amounts.length - 1]; } function _safeSwapToBNB(uint amount) private returns (uint) { require(IERC20Upgradeable(wbnb).balanceOf(address(this)) >= amount, "Zap: Not enough wbnb balance"); uint beforeBNB = address(this).balance; IWETH(wbnb).withdraw(amount); return address(this).balance - beforeBNB; } /* ========== RESTRICTED FUNCTIONS ========== */ function setRoutePairAddress(address asset, address route) public onlyOwner { routePairAddresses[asset] = route; } function sweep(address[] memory tokens) external onlyOwner { for (uint i = 0; i < tokens.length; i++) { address token = tokens[i]; if (token == address(0)) continue; uint amount = IERC20Upgradeable(token).balanceOf(address(this)); if (amount > 0) { _swapTokenForBNB(token, amount, owner()); } } } function withdraw(address token) external onlyOwner { if (token == address(0)) { payable(owner()).transfer(address(this).balance); return; } IERC20Upgradeable(token).transfer(owner(), IERC20Upgradeable(token).balanceOf(address(this))); } }//SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // fee for protocol contract FeeConf is Constants, Ownable { struct ReceiverRate { address receiver; uint16 rate; } mapping(bytes32 => ReceiverRate) configs; event SetConfig(bytes32 key, address receiver, uint16 rate); constructor(address receiver) { setConfig("yield_fee", receiver, 2000); // 20% setConfig("borrow_fee", receiver, 50); // 0.5% setConfig("repay_fee", receiver, 100); // 1% // setConfig("liq_fee", receiver, 100); // 0% } function setConfig(bytes32 _key, address _receiver, uint16 _rate) public onlyOwner { require(_receiver != address(0), "INVALID_RECEIVE"); ReceiverRate storage conf = configs[_key]; conf.receiver = _receiver; conf.rate = _rate; emit SetConfig(_key, _receiver, _rate); } function getConfig(bytes32 _key) external view returns (address, uint) { ReceiverRate memory conf = configs[_key]; return (conf.receiver, conf.rate); } }//SPDX-License-Identifier: MIT pragma solidity 0.8.9; contract Constants { uint public constant PercentBase = 10000; }//SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IMintVault.sol"; import "./interfaces/IController.sol"; import "./interfaces/IStrategy.sol"; import "./Constants.sol"; contract AppController is Constants, IController, OwnableUpgradeable { using EnumerableSet for EnumerableSet.AddressSet; uint constant JOINED_VAULT_LIMIT = 20; // underlying => dToken mapping(address => address) public override dyTokens; // underlying => IStratege mapping(address => address) public strategies; struct ValueConf { address oracle; uint16 dr; // discount rate uint16 pr; // premium rate } // underlying => orcale mapping(address => ValueConf ) internal valueConfs; // dyToken => vault mapping(address => address) public override dyTokenVaults; // 用户已进入的Vault // user => vaults mapping(address => EnumerableSet.AddressSet) internal userJoinedDepositVaults; mapping(address => EnumerableSet.AddressSet) internal userJoinedBorrowVaults; // 处于风控需要,管理 Vault 状态 struct VaultState { bool enabled; bool enableDeposit; bool enableWithdraw; bool enableBorrow; bool enableRepay; bool enableLiquidate; } // Vault => VaultStatus mapping(address => VaultState) public vaultStates; // depost value / borrow value >= liquidateRate uint public liquidateRate; uint public collateralRate; // is anyone can call Liquidate. bool public isOpenLiquidate; mapping(address => bool) public allowedLiquidator; // EVENT event UnderlyingDTokenChanged(address indexed underlying, address oldDToken, address newDToken); event UnderlyingStrategyChanged(address indexed underlying, address oldStrage, address newDToken, uint stype); event DTokenVaultChanged(address indexed dToken, address oldVault, address newVault, uint vtype); event ValueConfChanged(address indexed underlying, address oracle, uint discount, uint premium); event LiquidateRateChanged(uint liquidateRate); event CollateralRateChanged(uint collateralRate); event OpenLiquidateChanged(bool open); event AllowedLiquidatorChanged(address liquidator, bool allowed); event SetVaultStates(address vault, VaultState state); constructor() { } function initialize() external initializer { OwnableUpgradeable.__Ownable_init(); liquidateRate = 11000; // PercentBase * 1.1; collateralRate = 13000; // PercentBase * 1.3; isOpenLiquidate = true; } // ====== yield ======= function setDYToken(address _underlying, address _dToken) external onlyOwner { require(_dToken != address(0), "INVALID_DTOKEN"); address oldDToken = dyTokens[_underlying]; dyTokens[_underlying] = _dToken; emit UnderlyingDTokenChanged(_underlying, oldDToken, _dToken); } // set or update strategy // stype: 1: pancakeswap function setStrategy(address _underlying, address _strategy, uint stype) external onlyOwner { require(_strategy != address(0), "Strategies Disabled"); address _current = strategies[_underlying]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_underlying] = _strategy; emit UnderlyingStrategyChanged(_underlying, _current, _strategy, stype); } function emergencyWithdrawAll(address _underlying) public onlyOwner { IStrategy(strategies[_underlying]).withdrawAll(); } // ====== vault ======= function setOpenLiquidate(bool _open) external onlyOwner { isOpenLiquidate = _open; emit OpenLiquidateChanged(_open); } function updateAllowedLiquidator(address liquidator, bool allowed) external onlyOwner { allowedLiquidator[liquidator] = allowed; emit AllowedLiquidatorChanged(liquidator, allowed); } function setLiquidateRate(uint _liquidateRate) external onlyOwner { liquidateRate = _liquidateRate; emit LiquidateRateChanged(liquidateRate); } function setCollateralRate(uint _collateralRate) external onlyOwner { collateralRate = _collateralRate; emit CollateralRateChanged(collateralRate); } // @dev 允许为每个底层资产设置不同的价格预言机 折扣率、溢价率 function setOracles(address _underlying, address _oracle, uint16 _discount, uint16 _premium) external onlyOwner { require(_oracle != address(0), "INVALID_ORACLE"); require(_discount <= PercentBase, "DISCOUT_TOO_BIG"); require(_premium >= PercentBase, "PREMIUM_TOO_SMALL"); ValueConf storage conf = valueConfs[_underlying]; conf.oracle = _oracle; conf.dr = _discount; conf.pr = _premium; emit ValueConfChanged(_underlying, _oracle, _discount, _premium); } function getValueConfs(address token0, address token1) external view returns ( address oracle0, uint16 dr0, uint16 pr0, address oracle1, uint16 dr1, uint16 pr1) { (oracle0, dr0, pr0) = getValueConf(token0); (oracle1, dr1, pr1) = getValueConf(token1); } // get DiscountRate and PremiumRate function getValueConf(address _underlying) public view returns (address oracle, uint16 dr, uint16 pr) { ValueConf memory conf = valueConfs[_underlying]; oracle = conf.oracle; dr = conf.dr; pr = conf.pr; } // vtype 1 : for deposit vault 2: for mint vault function setVault(address _dyToken, address _vault, uint vtype) external onlyOwner { require(IVault(_vault).isDuetVault(), "INVALIE_VALUT"); address old = dyTokenVaults[_dyToken]; dyTokenVaults[_dyToken] = _vault; emit DTokenVaultChanged(_dyToken, old, _vault, vtype); } function joinVault(address _user, bool isDepositVault) external { address vault = msg.sender; require(vaultStates[vault].enabled, "INVALID_CALLER"); EnumerableSet.AddressSet storage set = isDepositVault ? userJoinedDepositVaults[_user] : userJoinedBorrowVaults[_user]; require(set.length() < JOINED_VAULT_LIMIT, "JOIN_TOO_MUCH"); set.add(vault); } function exitVault(address _user, bool isDepositVault) external { address vault = msg.sender; require(vaultStates[vault].enabled, "INVALID_CALLER"); EnumerableSet.AddressSet storage set = isDepositVault ? userJoinedDepositVaults[_user] : userJoinedBorrowVaults[_user]; set.remove(vault); } function setVaultStates(address _vault, VaultState memory _state) external onlyOwner { vaultStates[_vault] = _state; emit SetVaultStates(_vault, _state); } function userJoinedVaultInfoAt(address _user, bool isDepositVault, uint256 index) external view returns (address vault, VaultState memory state) { EnumerableSet.AddressSet storage set = isDepositVault ? userJoinedDepositVaults[_user] : userJoinedBorrowVaults[_user]; vault = set.at(index); state = vaultStates[vault]; } function userJoinedVaultCount(address _user, bool isDepositVault) external view returns (uint256) { return isDepositVault ? userJoinedDepositVaults[_user].length() : userJoinedBorrowVaults[_user].length(); } /** * @notice 用户最大可借某 Vault 的资产数量 */ function maxBorrow(address _user, address vault) public view returns(uint) { uint totalDepositValue = accVaultVaule(_user, userJoinedDepositVaults[_user], true); uint totalBorrowValue = accVaultVaule( _user, userJoinedBorrowVaults[_user], true); uint validValue = totalDepositValue * PercentBase / collateralRate; if (validValue > totalBorrowValue) { uint canBorrowValue = validValue - totalBorrowValue; return IMintVault(vault).valueToAmount(canBorrowValue, true); } else { return 0; } } /** * @notice 获取用户Vault价值 * @param _user 存款人 * @param _dp 是否折价(Discount) 和 溢价(Premium) */ function userValues(address _user, bool _dp) public view override returns(uint totalDepositValue, uint totalBorrowValue) { totalDepositValue = accVaultVaule(_user, userJoinedDepositVaults[_user], _dp); totalBorrowValue = accVaultVaule( _user, userJoinedBorrowVaults[_user], _dp); } /** * @notice 预测用户更改Vault后的价值 * @param _user 存款人 * @param _vault 拟修改的Vault * @param _amount 拟修改的数量 * @param _dp 是否折价(Discount) 和 溢价(Premium) */ function userPendingValues(address _user, IVault _vault, int _amount, bool _dp) public view returns(uint pendingDepositValue, uint pendingBrorowValue) { pendingDepositValue = accPendingValue(_user, userJoinedDepositVaults[_user], IVault(_vault), _amount, _dp); pendingBrorowValue = accPendingValue(_user, userJoinedBorrowVaults[_user], IVault(_vault), _amount, _dp); } /** * @notice 判断该用户是否需要清算 */ function isNeedLiquidate(address _borrower) public view returns(bool) { (uint totalDepositValue, uint totalBorrowValue) = userValues(_borrower, true); return totalDepositValue * PercentBase < totalBorrowValue * liquidateRate; } function accVaultVaule(address _user, EnumerableSet.AddressSet storage set, bool _dp) internal view returns(uint totalValue) { uint len = set.length(); for (uint256 i = 0; i < len; i++) { address vault = set.at(i); totalValue += IVault(vault).userValue(_user, _dp); } } function accPendingValue(address _user, EnumerableSet.AddressSet storage set, IVault vault, int amount, bool _dp) internal view returns(uint totalValue) { uint len = set.length(); bool existVault = false; for (uint256 i = 0; i < len; i++) { IVault v = IVault(set.at(i)); if (vault == v) { totalValue += v.pendingValue(_user, amount); existVault = true; } else { totalValue += v.userValue(_user, _dp); } } if (!existVault) { totalValue += vault.pendingValue(_user, amount); } } /** * @notice 存款前风控检查 * param user 存款人 * @param _vault Vault地址 * param amount 存入的标的资产数量 */ function beforeDeposit(address , address _vault, uint) external view { VaultState memory state = vaultStates[_vault]; require(state.enabled && state.enableDeposit, "DEPOSITE_DISABLE"); } /** @notice 借款前风控检查 @param _user 借款人 @param _vault 借贷市场地址 @param _amount 待借标的资产数量 */ function beforeBorrow(address _user, address _vault, uint256 _amount) external view { VaultState memory state = vaultStates[_vault]; require(state.enabled && state.enableBorrow, "BORROW_DISABLED"); uint totalDepositValue = accVaultVaule(_user, userJoinedDepositVaults[_user], true); uint pendingBrorowValue = accPendingValue(_user, userJoinedBorrowVaults[_user], IVault(_vault), int(_amount), true); require(totalDepositValue * PercentBase >= pendingBrorowValue * collateralRate, "LOW_COLLATERAL"); } function beforeWithdraw(address _user, address _vault, uint256 _amount) external view { VaultState memory state = vaultStates[_vault]; require(state.enabled && state.enableWithdraw, "WITHDRAW_DISABLED"); uint pendingDepositValue = accPendingValue(_user, userJoinedDepositVaults[_user], IVault(_vault), int(0) - int(_amount), true); uint totalBorrowValue = accVaultVaule(_user, userJoinedBorrowVaults[_user], true); require(pendingDepositValue * PercentBase >= totalBorrowValue * collateralRate, "LOW_COLLATERAL"); } function beforeRepay(address _repayer, address _vault, uint256 _amount) external view { VaultState memory state = vaultStates[_vault]; require(state.enabled && state.enableRepay, "REPAY_DISABLED"); } function liquidate(address _borrower, bytes calldata data) external { address liquidator = msg.sender; require(isOpenLiquidate || allowedLiquidator[liquidator], "INVALID_LIQUIDATOR"); require(isNeedLiquidate(_borrower), "COLLATERAL_ENOUGH"); EnumerableSet.AddressSet storage set = userJoinedDepositVaults[_borrower]; uint len = set.length(); for (uint256 i = 0; i < len; i++) { IVault v = IVault(set.at(i)); beforeLiquidate(_borrower, address(v)); v.liquidate(liquidator, _borrower, data); } EnumerableSet.AddressSet storage set2 = userJoinedBorrowVaults[_borrower]; uint len2 = set2.length(); for (uint256 i = 0; i < len2; i++) { IVault v = IVault(set2.at(i)); beforeLiquidate(_borrower, address(v)); v.liquidate(liquidator, _borrower, data); } } function beforeLiquidate(address _borrower, address _vault) internal view { VaultState memory state = vaultStates[_vault]; require(state.enabled && state.enableLiquidate, "LIQ_DISABLED"); } // ====== vault end ======= }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; contract Duet is Initializable, OwnableUpgradeable, ERC20Upgradeable { function initialize() public initializer { __Context_init_unchained(); __Ownable_init_unchained(); __ERC20_init_unchained("Duet Governance Token", "DUET"); } function mint(address account, uint256 amount) public onlyOwner { _mint(account, amount); } function burn(address account, uint256 amount) public onlyOwner { _burn(account, amount); } function burnme(uint256 amount) public { _burn(msg.sender, amount); } }//SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import './libs/TransferHelper.sol'; import "./DYTokenBase.sol"; import "./interfaces/IVault.sol"; import "./interfaces/IDepositVault.sol"; import "./interfaces/IWETH.sol"; contract DYTokenNative is DYTokenBase { using SafeERC20 for IERC20; // _underlying is WETH WBNB constructor(address _underlying, string memory _symbol, address _controller) DYTokenBase(_underlying, _symbol, _controller) { } receive() external payable { assert(msg.sender == underlying); // only accept ETH via fallback from the WETH contract } function depositCoin(address _to, address _toVault) public override payable { uint total = underlyingTotal(); uint amount = msg.value; IWETH(underlying).deposit{value: amount}(); uint shares = 0; if (totalSupply() == 0) { require(amount >= 10000, "too small"); shares = amount; } else { shares = amount * totalSupply() / total; } require(shares > 0, "ZERO_SHARE"); if(_toVault != address(0)) { require(_toVault == IController(controller).dyTokenVaults(address(this)), "mismatch dToken vault"); _mint(_toVault, shares); IDepositVault(_toVault).syncDeposit(address(this), shares, _to); } else { _mint(_to, shares); } earn(); } function deposit(uint _amount, address _toVault) external override { depositTo(msg.sender, _amount, _toVault); } function depositTo(address _to, uint _amount, address _toVault) public override { uint total = underlyingTotal(); IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount); uint shares = 0; if (totalSupply() == 0) { require(_amount >= 10000, "too small"); shares = _amount; } else { shares = _amount * totalSupply() / total; } require(shares > 0, "ZERO_SHARE"); // if(_toVault != address(0)) { require(_toVault == IController(controller).dyTokenVaults(address(this)), "mismatch dToken vault"); _mint(_toVault, shares); IDepositVault(_toVault).syncDeposit(address(this), shares, _to); } else { _mint(_to, shares); } earn(); } function withdraw(address _to, uint _shares, bool needWETH) public override { require(_shares > 0, "shares need > 0"); require(totalSupply() > 0, "no deposit"); uint r = underlyingTotal() * _shares / totalSupply(); _burn(msg.sender, _shares); uint b = IERC20(underlying).balanceOf(address(this)); // need withdraw from strategy if (b < r) { uint withdrawAmount = r - b; address strategy = IController(controller).strategies(underlying); if (strategy != address(0)) { IStrategy(strategy).withdraw(withdrawAmount); } uint withdrawed = IERC20(underlying).balanceOf(address(this)) - b; if (withdrawed < withdrawAmount) { r = b + withdrawed; } } if (needWETH) { IWETH(underlying).withdraw(r); TransferHelper.safeTransferETH(_to, r); } else { IERC20(underlying).safeTransfer(_to, r); } } function earn() public override { uint b = IERC20(underlying).balanceOf(address(this)); address strategy = IController(controller).strategies(underlying); if (strategy != address(0)) { IERC20(underlying).safeTransfer(strategy, b); IStrategy(strategy).deposit(); } } }//SPDX-License-Identifier: MIT pragma solidity 0.8.9; import { ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/TokenRecipient.sol"; import "./interfaces/IStrategy.sol"; import "./interfaces/IDYToken.sol"; import "./interfaces/IController.sol"; abstract contract DYTokenBase is IDYToken, ERC20, ERC20Permit, Ownable { using Address for address; address public immutable override underlying; uint8 internal dec; address public controller; event SetController(address controller); constructor(address _underlying, string memory _symbol, address _controller) ERC20( "DYToken", string(abi.encodePacked("DY-", _symbol))) ERC20Permit("DYToken") { underlying = _underlying; dec = ERC20(_underlying).decimals(); controller = _controller; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override { } function decimals() public view virtual override returns (uint8) { return dec; } function burn(uint256 amount) public { _burn(msg.sender, amount); } function send(address recipient, uint256 amount, bytes calldata exData) external returns (bool) { _transfer(msg.sender, recipient, amount); if (recipient.isContract()) { bool rv = TokenRecipient(recipient).tokensReceived(msg.sender, amount, exData); require(rv, "No tokensReceived"); } return true; } // ====== Controller ====== function setController(address _controller) public onlyOwner { require(_controller != address(0), "INVALID_CONTROLLER"); controller = _controller; emit SetController(_controller); } // ====== yield functions ===== // total hold function underlyingTotal() public virtual view returns (uint) { address strategy = IController(controller).strategies(underlying); if (strategy != address(0)) { return IERC20(underlying).balanceOf(address(this)) + IStrategy(strategy).balanceOf(); } else { return IERC20(underlying).balanceOf(address(this)); } } function underlyingAmount(uint amount) public virtual override view returns (uint) { if (totalSupply() == 0) { return 0; } return underlyingTotal() * amount / totalSupply(); } function balanceOfUnderlying(address _user) public virtual override view returns (uint) { if (balanceOf(_user) > 0) { return underlyingTotal() * balanceOf(_user) / totalSupply(); } else { return 0; } } // 单位净值 function pricePerShare() public view returns (uint price) { if (totalSupply() > 0) { return underlyingTotal() * 1e18 / totalSupply(); } } function depositTo(address _to, uint _amount, address _toVault) public virtual; // for native coin function depositCoin(address _to, address _toVault) public virtual payable { } function depositAll(address _toVault) external { address user = msg.sender; depositTo(user, IERC20(underlying).balanceOf(user), _toVault); } // withdraw underlying asset, brun dyTokens function withdraw(address _to, uint _shares, bool needWETH) public virtual; function withdrawAll() external { withdraw(msg.sender, balanceOf(msg.sender), true); } // transfer all underlying asset to yield strategy function earn() public virtual; }
Public SMART CONTRACT AUDIT REPORT for Duet Prepared By: Yiqun Chen PeckShield January 29, 2022 1/21 PeckShield Audit Report #: 2022-022Public Document Properties Client Duet Finance Title Smart Contract Audit Report Target Duet 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 January 29, 2022 Xiaotao Wu Final Release 1.0-rc January 28, 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/21 PeckShield Audit Report #: 2022-022Public Contents 1 Introduction 4 1.1 About Duet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Possible Costly DYToken From Improper Pool Initialization . . . . . . . . . . . . . . 11 3.2 Meaningful Events For Important State Changes . . . . . . . . . . . . . . . . . . . . 13 3.3 Lack of BNB Handling In DYTokenBase::inCaseTokensGetStuck() . . . . . . . . . . 14 3.4 Possible Sandwich/MEV Attacks In Duet . . . . . . . . . . . . . . . . . . . . . . . . 14 3.5 Potential Lockup Of Tokens Leftover In DuetZap::tokenToLp() . . . . . . . . . . . . 16 3.6 Trust Issue of Admin Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 4 Conclusion 19 References 20 3/21 PeckShield Audit Report #: 2022-022Public 1 | Introduction Given the opportunity to review the design document and related source code of the Duetprotocol, 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 Duet Duetis a multi-chain synthetic asset protocol with a hybrid mechanism (overcollateralization + algorithm-pegged) that sharpens assets to be traded on the blockchain. A duet in music refers to a piece of music where two people play different parts or melodies. Similarly, the Duetprotocol allows traders to replicate the real-world tradable assets in a decentralized finance ecosystem. The basic information of audited contracts is as follows: Table 1.1: Basic Information of Duet ItemDescription NameDuet Finance Website https://duet.finance/ TypeSmart Contract Platform Solidity Audit Method Whitebox Latest Audit Report January 29, 2022 In the following, we show the Git repository of reviewed files and the commit hash value used in this audit: •https://github.com/duet-protocol/Duet-Over-Collateralization-us.git (ffd1a9a) And this is the commit ID after all fixes for the issues found in the audit have been checked in: 4/21 PeckShield Audit Report #: 2022-022Public •https://github.com/duet-protocol/duet-collateral-contracts.git (92452da) 1.2 About PeckShield PeckShield Inc. [14] 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 [13]: •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. 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/21 PeckShield Audit Report #: 2022-022Public 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/21 PeckShield Audit Report #: 2022-022Public 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) [12], 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/21 PeckShield Audit Report #: 2022-022Public 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/21 PeckShield Audit Report #: 2022-022Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the Duetprotocol 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 4 Informational 1 Total 6 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/21 PeckShield Audit Report #: 2022-022Public 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, 4low-severity vulnerabilities, and 1informational recommendation. Table 2.1: Key Audit Findings ID Severity Title Category Status PVE-001 Low PossibleCostlyDYTokenFromImproper Pool InitializationTime and State Fixed PVE-002 Informational Meaningful Events For Important State ChangesCoding Practices Fixed PVE-003 Low Lack of BNB Handling In DYToken- Base::inCaseTokensGetStuck()Business Logics Fixed PVE-004 Low Possible Sandwich/MEV Attacks In DuetTime and State Confirmed PVE-005 Low Potential Lockup Of Tokens Leftover In DuetZap::tokenToLp()Business Logics Confirmed PVE-006 Medium Trust Issue of Admin Keys Security Features 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/21 PeckShield Audit Report #: 2022-022Public 3 | Detailed Results 3.1 Possible Costly DYToken From Improper Pool Initialization •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: High•Target: DYTokenERC20/DYTokenNative •Category: Time and State [8] •CWE subcategory: CWE-362 [2] Description The DYTokenERC20 contract of the Duetprotocol provides a public depositTo() function for users to deposit the underlying token to the DYTokencontract and mint the corresponding shares of DYToken to the users. While examining the DYTokenshare calculation with the given underlying token amount, we notice an issue that may unnecessarily make the underlying token extremely expensive and bring hurdles (or even causes loss) for later depositors. To elaborate, we show below the depositTo() routine. The issue occurs when the depositpool is being initialized under the assumption that the current pool is empty. 29 function depositTo ( address _to , uint _amount , address _toVault ) public override { 30 uint total = underlyingTotal (); 31 IERC20 underlyingToken = IERC20 ( underlying ); 32 33 uint before = underlyingToken . balanceOf ( address ( this )); 34 underlyingToken . safeTransferFrom ( msg. sender , address ( this ), _amount ); 35 uint realAmount = underlyingToken . balanceOf ( address ( this )) - before ; // Additional check for deflationary tokens 36 require ( realAmount >= _amount , " illegal amount "); 37 38 uint shares = 0; 39 if ( totalSupply () == 0) { 40 shares = _amount ; 41 } else { 42 shares = _amount * totalSupply () / total ; 43 } 11/21 PeckShield Audit Report #: 2022-022Public 44 45 // 46 if( _toVault != address (0) ) { 47 require ( _toVault == IController ( controller ). dyTokenVaults ( address ( this )), " mismatch dToken vault "); 48 _mint ( _toVault , shares ); 49 IDepositVault ( _toVault ). syncDeposit ( address ( this ), shares , _to ); 50 } else { 51 _mint (_to , shares ); 52 } 53 54 earn (); 55 } Listing 3.1: DYTokenERC20::depositTo() Specifically, when the depositpool is being initialized, the sharesvalue directly takes the value of _amount(line 40), which is manipulatable by the malicious actor. As this is the first time to deposit, the totalSupply() equals the given input amount, i.e., _amount = 1 WEI . With that, the actor can further donate a huge amount of underlying toDYTokenERC20 contract with the goal of making the DYTokenextremely expensive. An extremely expensive DYTokencan be very inconvenient to use as a small number of 1𝑊 𝐸𝐼 may denote a large value. Furthermore, it can lead to precision issue in truncating the computed sharesfor deposited assets (line 42). If truncated to be zero, the deposited assets are essentially considered dust and kept by the contract without returning any DYToken. Note the DYTokenNative::depositCoin()/depositTo() routines share a similar issue. Recommendation Revise current execution logic of above mentioned functions to defensively calculate the mint amount when the deposit pool is being initialized. An alternative solution is to ensure guarded launch that safeguards the first deposit to avoid being manipulated. Status This issue has been fixed in the following commit: e6f1a47. 12/21 PeckShield Audit Report #: 2022-022Public 3.2 Meaningful Events For Important State Changes •ID: PVE-002 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Multiple contracts •Category: Coding Practices [9] •CWE subcategory: CWE-563 [3] 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. In the following, we use the FeeConfcontract as an example. While examining the event that reflect the FeeConfdynamics, we notice there is a lack of emitting related event to reflect important state change. Specifically, when the setConfig() is being called, there is no corresponding event being emitted to reflect the occurrence of setConfig() . 24 function setConfig ( bytes32 _key , address _receiver , uint16 _rate ) public onlyOwner { 25 require ( _receiver != address (0) , " INVALID_RECEIVE "); 26 ReceiverRate storage conf = configs [ _key ]; 27 conf . receiver = _receiver ; 28 conf . rate = _rate ; 29 } Listing 3.2: FeeConf::setConfig Note a number of routines in the Duetprotocol contracts can be similarly improved, includ- ingDYTokenBase::setController() ,DuetZap::setRoutePairAddress() ,AppController::setVaultStates() , BaseStrategy::setMinHarvestAmount()/setController()/setFeeConf() ,and StrategyForPancakeLP::setToken0Path ()/setToken2Path() . Recommendation Properly emit the related events when the above-mentioned functions are being invoked. Status This issue has been fixed in the following commit: e169a53. 13/21 PeckShield Audit Report #: 2022-022Public 3.3 Lack of BNB Handling In DYTokenBase::inCaseTokensGetStuck() •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Medium•Target: DYTokenBase •Category: Business Logics [10] •CWE subcategory: CWE-708 [5] Description The DYTokenBase contract provides the inCaseTokensGetStuck() function for the ownerto withdraw the ERC20tokens from the contract in case these tokens got stuck. The DYTokenBase contract can also receive BNBvia the depositCoin() function which is defined as payable. However, the current implementation logic of the inCaseTokensGetStuck() function only considers the case of ERC20tokens. Therefore, the ownercan not recover BNBif there are BNBsgot stuck in the contract. 43 function inCaseTokensGetStuck ( address _token , uint _amount ) public onlyOwner { 44 IERC20 ( _token ). transfer ( owner () , _amount ); 45 } Listing 3.3: DYTokenBase::inCaseTokensGetStuck() Recommendation Consider the scenario that BNBmay also got stuck in the contract. Status This issue has been fixed. The Duetteam has removed the inCaseTokensGetStuck() function from the DYTokenBase contract. 3.4 Possible Sandwich/MEV Attacks In Duet •ID: PVE-004 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Time and State [11] •CWE subcategory: CWE-682 [4] Description The DuetZapcontract has a helper routine, i.e., _swap(), that is designed to swap one token for another. It has a rather straightforward logic in allowing routerto transfer the funds by calling swapExactTokensForTokens() to actually perform the intended token swap. 14/21 PeckShield Audit Report #: 2022-022Public 200 function _swap ( address _from , uint amount , address _to , address receiver ) private returns ( uint ) { 201 address intermediate = routePairAddresses [ _from ]; 202 if ( intermediate == address (0) ) { 203 intermediate = routePairAddresses [ _to ]; 204 } 206 address [] memory path ; 208 if ( intermediate == address (0) _from == intermediate _to == intermediate ) { 209 // [DUET , BUSD ] or [BUSD , DUET ] 210 path = new address [](2) ; 211 path [0] = _from ; 212 path [1] = _to ; 213 } else { 214 path = new address [](3) ; 215 path [0] = _from ; 216 path [1] = intermediate ; 217 path [2] = _to ; 218 } 220 uint [] memory amounts = router . swapExactTokensForTokens ( amount , 0, path , receiver , block . timestamp ); 221 return amounts [ amounts . length - 1]; 222 } Listing 3.4: DuetZap::_swap() To elaborate, we show above the _swap()routine. We notice the token swap is routed to router and the actual swap operation swapExactTokensForTokens() essentially does not specify any restric- tion (with amountOutMin=0 ) on possible slippage 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. Notethe DuetZap::_swapTokenForBNB()/_swapBNBForToken()/_swapBNBToLp()/zapOut() and StrategyForPancakeLP ::doHarvest() routines share a similar issue. 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. And the team clarifies that, MEVattacks are acceptable 15/21 PeckShield Audit Report #: 2022-022Public for the above mentioned scenarios. 3.5 Potential Lockup Of Tokens Leftover In DuetZap::tokenToLp() •ID: PVE-005 •Severity: Low •Likelihood: Low •Impact: Low•Target: DuetZap •Category: Business Logics [10] •CWE subcategory: CWE-754 [6] Description In the DuetZapcontract, the tokenToLp() function is designed to get UniswapV2 LP tokens via a single ERC20asset. While examining its logics, we notice there may have leftover tokens locked in the DuetZapcontract. To elaborate, we show below the related code snippet of the DuetZapcontract. In the tokenToLp() function, it comes to our attention with the following action sequences: The _swap()function is firstly called (line 65) to swap half the number of the _token(specified by the function input parameter) to otherand then the addLiquidity() function is called (line 68) to add the remaining half of the _token and the exchanged otherto the UniswapV2 _token + other pair to provide liquidity. This is reasonable under the assumption that those tokens approved to the UniswapV2 router contract happen to be used entirely to provide liquidity. Otherwise, the leftover tokens will be locked in the contract. We suggest to calculate the actual amount of tokens before transferring them into the contract. 1755 function tokenToLp ( address _token , uint amount , address _lp , bool needDeposit ) external { 1756 address receiver = msg . sender ; 1757 if ( needDeposit ) { 1758 receiver = address ( this ); 1759 } 1760 IERC20Upgradeable ( _token ). safeTransferFrom ( msg . sender , address ( this ), amount ); 1761 _approveTokenIfNeeded ( _token , address ( router )); 1762 1763 IPair pair = IPair ( _lp); 1764 address token0 = pair . token0 (); 1765 address token1 = pair . token1 (); 1766 1767 uint liquidity ; 1768 1769 if ( _token == token0 _token == token1 ) { 1770 // swap half amount for other 1771 address other = _token == token0 ? token1 : token0 ; 1772 _approveTokenIfNeeded (other , address ( router )); 16/21 PeckShield Audit Report #: 2022-022Public 1773 uint sellAmount = amount / 2; 1774 1775 uint otherAmount = _swap ( _token , sellAmount , other , address ( this )); 1776 pair . skim ( address ( this )); 1777 1778 (, , liquidity ) = router . addLiquidity (_token , other , amount - sellAmount , otherAmount , 0, 0, receiver , block . timestamp ); 1779 } else { 1780 uint bnbAmount = _token == wbnb ? _safeSwapToBNB ( amount ) : _swapTokenForBNB ( _token , amount , address ( this )); 1781 liquidity = _swapBNBToLp (_lp , bnbAmount , receiver ); 1782 } 1783 1784 emit ZapToLP ( _token , amount , _lp , liquidity ); 1785 if ( needDeposit ) { 1786 deposit (_lp , liquidity , msg . sender ); 1787 } 1788 1789 } Listing 3.5: DuetZap::tokenToLp() Note the _swapBNBToLp() routine in the same contract can be similarly improved. Recommendation Add additional handling logic for the above mentioned functions to return the leftover assets to the user (if any). Status The issue has been confirmed. 3.6 Trust Issue of Admin Keys •ID: PVE-006 •Severity: Medium •Likelihood: Low •Impact: High•Target: Multiple Contracts •Category: Security Features [7] •CWE subcategory: CWE-287 [1] Description In the Duetprotocol, there is a privileged owneraccount that plays a critical role in governing and regulating the protocol-wide operations (e.g., mint/burn Duettokens, withdraw assets from Duet contracts, set the key parameters, etc.). In the following, we use the Duetcontract as an example and show the representative functions potentially affected by the privilege of the owneraccount. The owneris privileged to mint more Duet tokens into circulation or burn Duettokens from circulation. 17/21 PeckShield Audit Report #: 2022-022Public 15 function mint ( address account , uint256 amount ) public onlyOwner { 16 _mint ( account , amount ); 17 } 18 19 function burn ( address account , uint256 amount ) public onlyOwner { 20 _burn ( account , amount ); 21 } Listing 3.6: Duet::mint()/burn() We understand the need of the privileged functions for proper contract operations, but at the same time the extra power to the ownermay 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 ownerexplicit to Duetprotocol users. Status The issue has been confirmed. 18/21 PeckShield Audit Report #: 2022-022Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the Duetprotocol. Duetis a multi- chain synthetic asset protocol with a hybrid mechanism (overcollateralization + algorithm-pegged) that sharpens assets to be traded on the blockchain. 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. 19/21 PeckShield Audit Report #: 2022-022Public References [1] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [2] MITRE. CWE-362: ConcurrentExecutionusingSharedResourcewithImproperSynchronization (’Race Condition’). https://cwe.mitre.org/data/definitions/362.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-708: Incorrect Ownership Assignment. https://cwe.mitre.org/data/definitions/ 708.html. [6] MITRE. CWE-754: Improper Check for Unusual or Exceptional Conditions. https://cwe.mitre. org/data/definitions/754.html. [7] MITRE. CWE CATEGORY: 7PK - Security Features. https://cwe.mitre.org/data/definitions/ 254.html. [8] MITRE. CWE CATEGORY: 7PK - Time and State. https://cwe.mitre.org/data/definitions/ 361.html. [9] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. 20/21 PeckShield Audit Report #: 2022-022Public [10] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [11] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html. [12] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [13] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [14] PeckShield. PeckShield Inc. https://www.peckshield.com. 21/21 PeckShield Audit Report #: 2022-022
Issues Count of Minor/Moderate/Major/Critical - Minor: 2 - Moderate: 2 - Major: 1 - Critical: 0 Minor Issues 2.a Problem: Possible Costly DYToken From Improper Pool Initialization (line 11) 2.b Fix: Add a check to ensure that the pool is initialized properly (line 12) Moderate Issues 3.a Problem: Meaningful Events For Important State Changes (line 13) 3.b Fix: Add meaningful events for important state changes (line 14) Major Issue 4.a Problem: Lack of BNB Handling In DYTokenBase::inCaseTokensGetStuck() (line 15) 4.b Fix: Add BNB handling in DYTokenBase::inCaseTokensGetStuck() (line 16) Critical Issue None Observations The audit report found that the given version of smart contracts can be further improved due to the presence of several issues related to either security or performance. Conclusion The audit report concluded that the Duet protocol can be further improved due to the presence of several issues related to either security or performance. It is recommended that the developers Issues Count of Minor/Moderate/Major/Critical - Minor: 0 - Moderate: 0 - Major: 0 - Critical: 0 Observations - No issues were found in the audit. Conclusion - The Duet protocol is secure and safe to use. Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 3 Major: 2 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 that the constructor is properly defined and called. Moderate: 3.a Problem (one line with code reference): Unchecked External Call (CWE-699) 3.b Fix (one line with code reference): Ensure that all external calls are checked for validity. Major: 4.a Problem (one line with code reference): Reentrancy (CWE-699) 4.b Fix (one line with code reference): Ensure that all external calls are checked for reentrancy. Critical: None Observations: We observed that the smart contracts were generally well-written and secure. Conclusion: Overall, the smart contracts were found to be secure and free of any critical issues. Minor and moderate issues were identified and recommendations were provided to address them.
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface StakingInterface { function approve ( address spender, uint256 amount ) external returns ( bool ); function balanceOf ( address account ) external view returns ( uint256 ); function deposit ( uint256 _amount ) external; function depositAll ( ) external; function withdraw ( uint256 _shares ) external; function withdrawAll ( ) external; } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Tier2FarmController{ using SafeMath for uint256; address payable public owner; address public platformToken = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; address public tokenStakingContract = 0x09FC573c502037B149ba87782ACC81cF093EC6ef; address ETH_TOKEN_ADDRESS = address(0x0); mapping (string => address) public stakingContracts; mapping (address => address) public tokenToFarmMapping; mapping (string => address) public stakingContractsStakingToken; mapping (address => mapping (address => uint256)) public depositBalances; uint256 public commission = 400; // Default is 4 percent string public farmName = 'Pickle.Finance'; mapping (address => uint256) public totalAmountStaked; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } constructor() public payable { stakingContracts["USDTPICKLEJAR"] = 0x09FC573c502037B149ba87782ACC81cF093EC6ef; stakingContractsStakingToken ["USDTPICKLEJAR"] = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; tokenToFarmMapping[stakingContractsStakingToken ["USDTPICKLEJAR"]] = stakingContracts["USDTPICKLEJAR"]; owner= msg.sender; } fallback() external payable { } function addOrEditStakingContract(string memory name, address stakingAddress, address stakingToken ) public onlyOwner returns (bool){ stakingContracts[name] = stakingAddress; stakingContractsStakingToken[name] = stakingToken; tokenToFarmMapping[stakingToken] = stakingAddress; return true; } function updateCommission(uint amount) public onlyOwner returns(bool){ commission = amount; return true; } function deposit(address tokenAddress, uint256 amount, address onBehalfOf) payable onlyOwner public returns (bool){ if(tokenAddress == 0x0000000000000000000000000000000000000000){ depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] + msg.value; stake(amount, onBehalfOf, tokenAddress ); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].add(amount); emit Deposit(onBehalfOf, amount, tokenAddress); return true; } ERC20 thisToken = ERC20(tokenAddress); require(thisToken.transferFrom(msg.sender, address(this), amount), "Not enough tokens to transferFrom or no approval"); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] + amount; uint256 approvedAmount = thisToken.allowance(address(this), tokenToFarmMapping[tokenAddress]); if(approvedAmount < amount ){ thisToken.approve(tokenToFarmMapping[tokenAddress], amount.mul(10000000)); } stake(amount, onBehalfOf, tokenAddress ); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].add(amount); emit Deposit(onBehalfOf, amount, tokenAddress); return true; } function stake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.deposit(amount); return true; } function unstake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.approve(tokenToFarmMapping[tokenAddress], 1000000000000000000000000000000); staker.withdrawAll(); return true; } function getStakedPoolBalanceByUser(address _owner, address tokenAddress) public view returns(uint256){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); uint256 numberTokens = staker.balanceOf(address(this)); uint256 usersBalancePercentage = (depositBalances[_owner][tokenAddress].mul(1000000)).div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser= (numberTokens.mul(1000).mul(usersBalancePercentage)).div(1000000000); return numberTokensPlusRewardsForUser; } function withdraw(address tokenAddress, uint256 amount, address payable onBehalfOf) onlyOwner payable public returns(bool){ ERC20 thisToken = ERC20(tokenAddress); //uint256 numberTokensPreWithdrawal = getStakedBalance(address(this), tokenAddress); if(tokenAddress == 0x0000000000000000000000000000000000000000){ require(depositBalances[msg.sender][tokenAddress] >= amount, "You didnt deposit enough eth"); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] - amount; onBehalfOf.send(amount); return true; } require(depositBalances[onBehalfOf][tokenAddress] > 0, "You dont have any tokens deposited"); //uint256 numberTokensPostWithdrawal = thisToken.balanceOf(address(this)); //uint256 usersBalancePercentage = depositBalances[onBehalfOf][tokenAddress].div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser1 = getStakedPoolBalanceByUser(onBehalfOf, tokenAddress); uint256 commissionForDAO1 = calculateCommission(numberTokensPlusRewardsForUser1); uint256 numberTokensPlusRewardsForUserMinusCommission = numberTokensPlusRewardsForUser1-commissionForDAO1; unstake(amount, onBehalfOf, tokenAddress); //staking platforms only withdraw all for the most part, and for security sticking to this totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = 0; require(numberTokensPlusRewardsForUserMinusCommission >0, "For some reason numberTokensPlusRewardsForUserMinusCommission is zero"); require(thisToken.transfer(onBehalfOf, numberTokensPlusRewardsForUserMinusCommission), "You dont have enough tokens inside this contract to withdraw from deposits"); if(numberTokensPlusRewardsForUserMinusCommission >0){ thisToken.transfer(owner, commissionForDAO1); } uint256 remainingBalance = thisToken.balanceOf(address(this)); if(remainingBalance>0){ stake(remainingBalance, address(this), tokenAddress); } emit Withdrawal(onBehalfOf, amount, tokenAddress); return true; } function calculateCommission(uint256 amount) view public returns(uint256){ uint256 commissionForDAO = (amount.mul(1000).mul(commission)).div(10000000); return commissionForDAO; } function changeOwner(address payable newOwner) onlyOwner public returns (bool){ owner = newOwner; return true; } function getStakedBalance(address _owner, address tokenAddress) public view returns(uint256){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); return staker.balanceOf(_owner); } function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } function kill() virtual public onlyOwner { selfdestruct(owner); } event Deposit(address indexed user, uint256 amount, address token); event Withdrawal(address indexed user, uint256 amount, address token); } // SPDX-License-Identifier: MIT //contract address mainnet: 0x618fDCFF3Cca243c12E6b508D9d8a6fF9018325c pragma solidity >=0.4.22 <0.8.0; interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface StakingInterface { function balanceOf ( address who ) external view returns ( uint256 ); //function controller ( ) external view returns ( address ); function exit ( ) external; //function lpToken ( ) external view returns ( address ); function stake ( uint256 amount ) external; //function valuePerShare ( ) external view returns ( uint256 ); } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } //SWC-Removal Of Unused Variables And Code: L67-L93 contract Tier2FarmController{ using SafeMath for uint256; address payable public owner; address public platformToken = 0xa0246c9032bC3A600820415aE600c6388619A14D; address public tokenStakingContract = 0x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50; address ETH_TOKEN_ADDRESS = address(0x0); mapping (string => address) public stakingContracts; mapping (address => address) public tokenToFarmMapping; mapping (string => address) public stakingContractsStakingToken; mapping (address => mapping (address => uint256)) public depositBalances; uint256 public commission = 400; // Default is 4 percent string public farmName = 'Harvest.Finance'; mapping (address => uint256) public totalAmountStaked; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } constructor() public payable { stakingContracts["FARM"] = 0x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50; stakingContractsStakingToken ["FARM"] = 0xa0246c9032bC3A600820415aE600c6388619A14D; tokenToFarmMapping[stakingContractsStakingToken ["FARM"]] = stakingContracts["FARM"]; owner= msg.sender; } fallback() external payable { } function addOrEditStakingContract(string memory name, address stakingAddress, address stakingToken ) public onlyOwner returns (bool){ stakingContracts[name] = stakingAddress; stakingContractsStakingToken[name] = stakingToken; tokenToFarmMapping[stakingToken] = stakingAddress; return true; } function updateCommission(uint amount) public onlyOwner returns(bool){ commission = amount; return true; } function deposit(address tokenAddress, uint256 amount, address onBehalfOf) payable onlyOwner public returns (bool){ if(tokenAddress == 0x0000000000000000000000000000000000000000){ depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] + msg.value; stake(amount, onBehalfOf, tokenAddress ); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].add(amount); emit Deposit(onBehalfOf, amount, tokenAddress); return true; } ERC20 thisToken = ERC20(tokenAddress); require(thisToken.transferFrom(msg.sender, address(this), amount), "Not enough tokens to transferFrom or no approval"); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] + amount; uint256 approvedAmount = thisToken.allowance(address(this), tokenToFarmMapping[tokenAddress]); if(approvedAmount < amount ){ thisToken.approve(tokenToFarmMapping[tokenAddress], amount.mul(10000000)); } stake(amount, onBehalfOf, tokenAddress ); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].add(amount); emit Deposit(onBehalfOf, amount, tokenAddress); return true; } function stake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.stake(amount); return true; } function unstake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.exit(); return true; } function getStakedPoolBalanceByUser(address _owner, address tokenAddress) public view returns(uint256){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); uint256 numberTokens = staker.balanceOf(address(this)); uint256 usersBalancePercentage = (depositBalances[_owner][tokenAddress].mul(1000000)).div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser= (numberTokens.mul(1000).mul(usersBalancePercentage)).div(1000000000); return numberTokensPlusRewardsForUser; } function withdraw(address tokenAddress, uint256 amount, address payable onBehalfOf) onlyOwner payable public returns(bool){ ERC20 thisToken = ERC20(tokenAddress); //uint256 numberTokensPreWithdrawal = getStakedBalance(address(this), tokenAddress); if(tokenAddress == 0x0000000000000000000000000000000000000000){ require(depositBalances[msg.sender][tokenAddress] >= amount, "You didnt deposit enough eth"); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] - amount; onBehalfOf.send(amount); return true; } require(depositBalances[onBehalfOf][tokenAddress] > 0, "You dont have any tokens deposited"); //uint256 numberTokensPostWithdrawal = thisToken.balanceOf(address(this)); //uint256 usersBalancePercentage = depositBalances[onBehalfOf][tokenAddress].div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser1 = getStakedPoolBalanceByUser(onBehalfOf, tokenAddress); uint256 commissionForDAO1 = calculateCommission(numberTokensPlusRewardsForUser1); uint256 numberTokensPlusRewardsForUserMinusCommission = numberTokensPlusRewardsForUser1-commissionForDAO1; unstake(amount, onBehalfOf, tokenAddress); //staking platforms only withdraw all for the most part, and for security sticking to this totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = 0; require(numberTokensPlusRewardsForUserMinusCommission >0, "For some reason numberTokensPlusRewardsForUserMinusCommission is zero"); require(thisToken.transfer(onBehalfOf, numberTokensPlusRewardsForUserMinusCommission), "You dont have enough tokens inside this contract to withdraw from deposits"); if(numberTokensPlusRewardsForUserMinusCommission >0){ thisToken.transfer(owner, commissionForDAO1); } uint256 remainingBalance = thisToken.balanceOf(address(this)); if(remainingBalance>0){ stake(remainingBalance, address(this), tokenAddress); } emit Withdrawal(onBehalfOf, amount, tokenAddress); return true; } function calculateCommission(uint256 amount) view public returns(uint256){ uint256 commissionForDAO = (amount.mul(1000).mul(commission)).div(10000000); return commissionForDAO; } function changeOwner(address payable newOwner) onlyOwner public returns (bool){ owner = newOwner; return true; } function getStakedBalance(address _owner, address tokenAddress) public view returns(uint256){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); return staker.balanceOf(_owner); } function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } function kill() virtual public onlyOwner { selfdestruct(owner); } event Deposit(address indexed user, uint256 amount, address token); event Withdrawal(address indexed user, uint256 amount, address token); } // SPDX-License-Identifier: MIT //Mainnet: 0x97b00db19bAe93389ba652845150CAdc597C6B2F pragma solidity >=0.4.22 <0.8.0; interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface Tier2StakingInterface { //staked balance info function depositBalances(address _owner, address token) external view returns(uint256 balance); function getStakedBalances(address _owner, address token) external view returns(uint256 balance); function getStakedPoolBalanceByUser(address _owner, address tokenAddress) external view returns(uint256); //basic info function tokenToFarmMapping(address tokenAddress) external view returns(address stakingContractAddress); function stakingContracts(string calldata platformName) external view returns(address stakingAddress); function stakingContractsStakingToken(string calldata platformName) external view returns(address tokenAddress); function platformToken() external view returns(address tokenAddress); function owner() external view returns(address ownerAddress); //actions function deposit(address tokenAddress, uint256 amount, address onBehalfOf) payable external returns (bool); function withdraw(address tokenAddress, uint256 amount, address payable onBehalfOf) payable external returns(bool); function addOrEditStakingContract(string calldata name, address stakingAddress, address stakingToken ) external returns (bool); function updateCommission(uint amount) external returns(bool); function changeOwner(address payable newOwner) external returns (bool); function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) external returns(bool); function kill() virtual external; } interface Oracle { function getAddress(string memory) view external returns (address); } interface Rewards { function unstakeAndClaimDelegated(uint256 amount, address onBehalfOf, address tokenAddress, address recipient) external returns (uint256); function stakeDelegated(uint256 amount, address tokenAddress, address onBehalfOf) external returns(bool); } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Tier1FarmController{ using SafeMath for uint256; address payable public owner; address payable public admin; address ETH_TOKEN_ADDRESS = address(0x0); mapping (string => address) public tier2StakingContracts; uint256 public commission = 400; // Default is 4 percent Oracle oracle; address oracleAddress; string public farmName = 'Tier1Aggregator'; mapping (address => uint256) totalAmountStaked; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } modifier onlyAdmin { require( msg.sender == oracle.getAddress("CORE"), "Only owner can call this function." ); _; } constructor() public payable { tier2StakingContracts["FARM"] = 0x618fDCFF3Cca243c12E6b508D9d8a6fF9018325c; owner= msg.sender; updateOracleAddress(0xBDfF00110c97D0FE7Fefbb78CE254B12B9A7f41f); } fallback() external payable { } function updateOracleAddress(address newOracleAddress ) public onlyOwner returns (bool){ oracleAddress= newOracleAddress; oracle = Oracle(newOracleAddress); return true; } function addOrEditTier2ChildStakingContract(string memory name, address stakingAddress ) public onlyOwner returns (bool){ tier2StakingContracts[name] = stakingAddress; return true; } function addOrEditTier2ChildsChildStakingContract(address tier2Contract, string memory name, address stakingAddress, address stakingToken ) public onlyOwner returns (bool){ Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); tier2Con.addOrEditStakingContract(name, stakingAddress, stakingToken); return true; } function updateCommissionTier2(address tier2Contract, uint amount) public onlyOwner returns(bool){ Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); tier2Con.updateCommission(amount); return true; } function deposit(string memory tier2ContractName, address tokenAddress, uint256 amount, address payable onBehalfOf) onlyAdmin payable public returns (bool){ address tier2Contract = tier2StakingContracts[tier2ContractName]; ERC20 thisToken = ERC20(tokenAddress); require(thisToken.transferFrom(msg.sender, address(this), amount), "Not enough tokens to transferFrom or no approval"); //approve the tier2 contract to handle tokens from this account thisToken.approve(tier2Contract, amount.mul(100)); Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); tier2Con.deposit(tokenAddress, amount, onBehalfOf); address rewardsContract = oracle.getAddress("REWARDS"); if(rewardsContract != address(0x0)){ Rewards rewards = Rewards(rewardsContract); try rewards.stakeDelegated(amount, tokenAddress, onBehalfOf) { } catch{ } } return true; } function withdraw(string memory tier2ContractName, address tokenAddress, uint256 amount, address payable onBehalfOf) onlyAdmin payable public returns(bool){ address tier2Contract = tier2StakingContracts[tier2ContractName]; ERC20 thisToken = ERC20(tokenAddress); Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); tier2Con.withdraw(tokenAddress, amount, onBehalfOf); address rewardsContract = oracle.getAddress("REWARDS"); if(rewardsContract != address(0x0)){ Rewards rewards = Rewards(rewardsContract); try rewards.unstakeAndClaimDelegated(amount, onBehalfOf, tokenAddress, onBehalfOf){ } catch{ } } return true; } function changeTier2Owner(address payable tier2Contract, address payable newOwner) onlyOwner public returns (bool){ Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); tier2Con.changeOwner(newOwner); return true; } function changeOwner(address payable newOwner) onlyOwner public returns (bool){ owner = newOwner; return true; } //admin can deposit and withdraw and should be the core contract /* function changeAdmin(address payable newAdmin) onlyAdmin public returns (bool){ admin = newAdmin; return true; } */ function adminEmergencyWithdrawTokensTier2(address payable tier2Contract, address token, uint amount, address payable destination) public onlyOwner returns(bool) { Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); tier2Con.adminEmergencyWithdrawTokens(token, amount, destination); return true; } function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } function getStakedPoolBalanceByUser(string memory tier2ContractName, address _owner, address tokenAddress) public view returns(uint256){ address tier2Contract = tier2StakingContracts[tier2ContractName]; ERC20 thisToken = ERC20(tokenAddress); Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); uint balance = tier2Con.getStakedPoolBalanceByUser(_owner, tokenAddress); return balance; } function getDepositBalanceByUser(string calldata tier2ContractName, address _owner, address token) external view returns(uint256 ){ address tier2Contract = tier2StakingContracts[tier2ContractName]; ERC20 thisToken = ERC20(token); Tier2StakingInterface tier2Con = Tier2StakingInterface(tier2Contract); uint balance = tier2Con.depositBalances(_owner, token); return balance; } function kill() virtual public onlyOwner { selfdestruct(owner); } } // 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; } } /** *Submitted for verification at Etherscan.io on 2020-12-11 */ // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; pragma experimental ABIEncoderV2; interface ERC20 { function balanceOf(address _owner) external view returns(uint balance); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); } interface externalPlatformContract{ function getAPR(address _farmAddress, address _tokenAddress) external view returns(uint apy); function getStakedPoolBalanceByUser(address _owner, address tokenAddress) external view returns(uint256); function commission() external view returns(uint256); function totalAmountStaked(address tokenAddress) external view returns(uint256); function depositBalances(address userAddress, address tokenAddress) external view returns(uint256); } interface IUniswapV2RouterLite { function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts); } interface Reward{ function addTokenToWhitelist ( address newTokenAddress ) external returns ( bool ); function calculateRewards ( uint256 timestampStart, uint256 timestampEnd, uint256 principalAmount, uint256 apr ) external view returns ( uint256 ); function depositBalances ( address, address, uint256 ) external view returns ( uint256 ); function depositBalancesDelegated ( address, address, uint256 ) external view returns ( uint256 ); function lpTokensInRewardsReserve ( ) external view returns ( uint256 ); function owner ( ) external view returns ( address ); function removeTokenFromWhitelist ( address tokenAddress ) external returns ( bool ); function stake ( uint256 amount, address tokenAddress, address onBehalfOf ) external returns ( bool ); function stakeDelegated ( uint256 amount, address tokenAddress, address onBehalfOf ) external returns ( bool ); function stakingLPTokensAddress ( ) external view returns ( address ); function stakingTokenWhitelist ( address ) external view returns ( bool ); function stakingTokensAddress ( ) external view returns ( address ); function tokenAPRs ( address ) external view returns ( uint256 ); function tokenDeposits ( address, address ) external view returns ( uint256 ); function tokenDepositsDelegated ( address, address ) external view returns ( uint256 ); function tokensInRewardsReserve ( ) external view returns ( uint256 ); function unstakeAndClaim ( address onBehalfOf, address tokenAddress, address recipient ) external returns ( uint256 ); function unstakeAndClaimDelegated ( address onBehalfOf, address tokenAddress, address recipient ) external returns ( uint256 ); function updateAPR ( uint256 newAPR, address stakedToken ) external returns ( bool ); function updateLPStakingTokenAddress ( address newAddress ) external returns ( bool ); function updateStakingTokenAddress ( address newAddress ) external returns ( bool ); } interface TVLOracle{ function getTotalValueLockedInternalByToken(address tokenAddress, address tier2Address) external view returns (uint256); function getTotalValueLockedAggregated(uint256 optionIndex) external view returns (uint256); } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Oracle{ using SafeMath for uint256; address payable public owner; address burnaddress = address(0x0); mapping (string => address) farmDirectoryByName; mapping (address => mapping(address =>uint256)) farmManuallyEnteredAPYs; mapping (address => mapping (address => address )) farmOracleObtainedAPYs; string [] public farmTokenPlusFarmNames; address [] public farmAddresses; address [] public farmTokens; address uniswapAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; IUniswapV2RouterLite uniswap = IUniswapV2RouterLite(uniswapAddress); address usdcCoinAddress = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address rewardAddress; Reward reward; address tvlOracleAddress; TVLOracle tvlOracle; //core contract adress that users interact with address public coreAddress; mapping (string => address) public platformDirectory; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } constructor() public payable { owner= msg.sender; } function getTotalValueLockedInternalByToken(address tokenAddress, address tier2Address) external view returns (uint256){ uint256 result = tvlOracle.getTotalValueLockedInternalByToken(tokenAddress, tier2Address); return result; } function getTotalValueLockedAggregated(uint256 optionIndex) external view returns (uint256){ uint256 result = tvlOracle.getTotalValueLockedAggregated(optionIndex); return result; } function getStakableTokens() view external returns (address[] memory, string[] memory){ address[] memory stakableAddrs = farmAddresses; string[] memory stakableNames = farmTokenPlusFarmNames; return (stakableAddrs, stakableNames); } function getAPR(address farmAddress, address farmToken)public view returns(uint256){ uint obtainedAPY = farmManuallyEnteredAPYs[farmAddress][farmToken]; if(obtainedAPY ==0){ externalPlatformContract exContract = externalPlatformContract(farmOracleObtainedAPYs[farmAddress][farmToken]); try exContract.getAPR(farmAddress, farmToken) returns (uint apy) { return apy; } catch (bytes memory ) { return (0); } } else{ return obtainedAPY; } } function getAmountStakedByUser(address tokenAddress, address userAddress, address tier2Address) external view returns(uint256){ externalPlatformContract exContract = externalPlatformContract(tier2Address); return exContract.getStakedPoolBalanceByUser(userAddress, tokenAddress); } function getUserCurrentReward(address userAddress, address tokenAddress, address tier2FarmAddress) view external returns(uint256){ uint256 userStartTime = reward.depositBalancesDelegated(userAddress, tokenAddress,0); uint256 principalAmount = reward.depositBalancesDelegated(userAddress, tokenAddress,1); uint256 apr = reward.tokenAPRs(tokenAddress); uint256 result = reward.calculateRewards( userStartTime, block.timestamp, principalAmount, apr); return result; } function getTokenPrice(address tokenAddress, uint256 amount) view external returns(uint256){ address [] memory addresses = new address[](2); addresses[0] = tokenAddress; addresses[1] = usdcCoinAddress; uint256 [] memory amounts = getUniswapPrice(addresses, amount ); uint256 resultingTokens = amounts[1]; return resultingTokens; } function getUserWalletBalance(address userAddress, address tokenAddress) external view returns (uint256){ ERC20 token = ERC20(tokenAddress); return token.balanceOf(userAddress); } function getAddress(string memory component) public view returns (address){ return platformDirectory[component]; } //BELOW is other (admin and otherwise) function updateTVLAddress(address theAddress) onlyOwner public returns(bool){ tvlOracleAddress = theAddress; tvlOracle = TVLOracle(theAddress); updateDirectory("TVLORACLE", theAddress); return true; } function updatePriceOracleAddress(address theAddress) onlyOwner public returns(bool){ uniswapAddress = theAddress; uniswap = IUniswapV2RouterLite(theAddress); updateDirectory("UNISWAP", theAddress); return true; } function updateUSD(address theAddress) onlyOwner public returns(bool){ usdcCoinAddress = theAddress; updateDirectory("USD", theAddress); return true; } function updateRewardAddress(address theAddress) onlyOwner public returns(bool){ rewardAddress = theAddress; reward = Reward(theAddress); updateDirectory("REWARDS", theAddress); return true; } function updateCoreAddress(address theAddress) onlyOwner public returns(bool){ coreAddress = theAddress; updateDirectory("CORE", theAddress); return true; } function updateDirectory(string memory name, address theAddress) onlyOwner public returns(bool){ platformDirectory[name] = theAddress; return true; } function setPlatformContract(string memory name, address farmAddress, address farmToken, address platformAddress) public onlyOwner returns(bool){ farmTokenPlusFarmNames.push(name); farmAddresses.push(farmAddress); farmTokens.push(farmToken); farmOracleObtainedAPYs[farmAddress][farmToken] = platformAddress; farmDirectoryByName[name] = platformAddress; return true; } function calculateCommission(uint256 amount, uint256 commission) view public returns(uint256){ uint256 commissionForDAO = (amount.mul(1000).mul(commission)).div(10000000); return commissionForDAO; } function getCommissionByContract(address platformContract) public view returns (uint256){ externalPlatformContract exContract = externalPlatformContract(platformContract); return exContract.commission(); } function getTotalStakedByContract(address platformContract, address tokenAddress) public view returns (uint256){ externalPlatformContract exContract = externalPlatformContract(platformContract); return exContract.totalAmountStaked(tokenAddress); } function getAmountCurrentlyDepositedByContract(address platformContract, address tokenAddress, address userAddress) public view returns (uint256){ externalPlatformContract exContract = externalPlatformContract(platformContract); return exContract.depositBalances(userAddress, tokenAddress); } function replaceAllStakableDirectory (string [] memory theNames, address[] memory theFarmAddresses, address[] memory theFarmTokens) onlyOwner public returns (bool){ farmTokenPlusFarmNames = theNames; farmAddresses = theFarmAddresses; farmTokens = theFarmTokens; return true; } function getAmountCurrentlyFarmStakedByContract(address platformContract, address tokenAddress, address userAddress) public view returns (uint256){ externalPlatformContract exContract = externalPlatformContract(platformContract); return exContract.getStakedPoolBalanceByUser(userAddress, tokenAddress); } function getUserTokenBalance(address userAddress, address tokenAddress) public view returns (uint256){ ERC20 token = ERC20(tokenAddress); return token.balanceOf(userAddress); } function getUniswapPrice(address [] memory theAddresses, uint amount) internal view returns (uint256[] memory amounts1){ uint256 [] memory amounts = uniswap.getAmountsOut(amount,theAddresses ); return amounts; } } // Aave AToken Deposit (Converts from regular token to aToken, stores in this contract, and withdraws based on percentage of pool) pragma solidity >=0.4.22 <0.8.0; interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface StakingInterface { function deposit ( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function getReservesList ( ) external view returns ( address[] memory ); function getUserAccountData ( address user ) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function withdraw ( address asset, uint256 amount, address to ) external returns ( uint256 ); } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Tier2FarmController{ using SafeMath for uint256; address payable public owner; address payable public admin; address public platformToken = 0x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50; address public tokenStakingContract = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; address ETH_TOKEN_ADDRESS = address(0x0); mapping (string => address) public stakingContracts; mapping (address => address) public tokenToFarmMapping; mapping (string => address) public stakingContractsStakingToken; mapping (address => mapping (address => uint256)) public depositBalances; mapping (address => address) public tokenToAToken; mapping (address => address) public aTokenToToken; uint256 public commission = 400; // Default is 4 percent string public farmName = 'Aave'; mapping (address => uint256) public totalAmountStaked; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } modifier onlyAdmin { require( msg.sender == admin, "Only admin can call this function." ); _; } constructor() public payable { stakingContracts["DAI"] =0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9 ; stakingContracts["ALL"] =0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9 ; stakingContractsStakingToken ["DAI"] = 0x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50; tokenToAToken[0x6B175474E89094C44Da98b954EedeAC495271d0F]= 0x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50; aTokenToToken[0x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50]= 0x6B175474E89094C44Da98b954EedeAC495271d0F; tokenToFarmMapping[stakingContractsStakingToken ["DAI"]] = stakingContracts["DAI"]; owner= msg.sender; admin = msg.sender; } fallback() external payable { } function updateATokens(address tokenAddress, address aTokenAddress) public onlyAdmin returns (bool){ tokenToAToken[tokenAddress] = aTokenAddress; aTokenToToken[aTokenAddress] = tokenAddress; return true; } function addOrEditStakingContract(string memory name, address stakingAddress, address stakingToken ) public onlyOwner returns (bool){ stakingContracts[name] = stakingAddress; stakingContractsStakingToken[name] = stakingToken; tokenToFarmMapping[stakingToken] = stakingAddress; return true; } function updateCommission(uint amount) public onlyOwner returns(bool){ commission = amount; return true; } function deposit(address tokenAddress, uint256 amount, address onBehalfOf) payable onlyOwner public returns (bool){ ERC20 thisToken = ERC20(tokenAddress); require(thisToken.transferFrom(msg.sender, address(this), amount), "Not enough tokens to transferFrom or no approval"); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress].add(amount); uint256 approvedAmount = thisToken.allowance(address(this), tokenToFarmMapping[tokenAddress]); if(approvedAmount < amount ){ thisToken.approve(tokenToFarmMapping[tokenAddress], amount.mul(10000000)); } stake(amount, onBehalfOf, tokenAddress ); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].add(amount); emit Deposit(onBehalfOf, amount, tokenAddress); return true; } function stake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.deposit(tokenAddress, amount, address(this), 0); return true; } function unstake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ ERC20 aToken = ERC20(tokenToAToken[tokenAddress]); StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.withdraw(tokenAddress, aToken.balanceOf(address(this)), address(this)); return true; } function getStakedPoolBalanceByUser(address _owner, address tokenAddress) public view returns(uint256){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); ERC20 aToken = ERC20(tokenToAToken[tokenAddress]); uint256 numberTokens = aToken.balanceOf(address(this)); uint256 usersBalancePercentage = (depositBalances[_owner][tokenAddress].mul(1000000)).div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser= (numberTokens.mul(1000).mul(usersBalancePercentage)).div(1000000000); return numberTokensPlusRewardsForUser; } //SWC-Code With No Effects: 205-253 function withdraw(address tokenAddress, uint256 amount, address payable onBehalfOf) onlyOwner payable public returns(bool){ ERC20 thisToken = ERC20(tokenAddress); //uint256 numberTokensPreWithdrawal = getStakedBalance(address(this), tokenAddress); if(tokenAddress == 0x0000000000000000000000000000000000000000){ require(depositBalances[msg.sender][tokenAddress] >= amount, "You didnt deposit enough eth"); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] - amount; onBehalfOf.send(amount); return true; } require(depositBalances[onBehalfOf][tokenAddress] > 0, "You dont have any tokens deposited"); //uint256 numberTokensPostWithdrawal = thisToken.balanceOf(address(this)); //uint256 usersBalancePercentage = depositBalances[onBehalfOf][tokenAddress].div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser1 = getStakedPoolBalanceByUser(onBehalfOf, tokenAddress); uint256 commissionForDAO1 = calculateCommission(numberTokensPlusRewardsForUser1); uint256 numberTokensPlusRewardsForUserMinusCommission = numberTokensPlusRewardsForUser1-commissionForDAO1; unstake(amount, onBehalfOf, tokenAddress); //staking platforms only withdraw all for the most part, and for security sticking to this totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = 0; require(numberTokensPlusRewardsForUserMinusCommission >0, "For some reason numberTokensPlusRewardsForUserMinusCommission is zero"); require(thisToken.transfer(onBehalfOf, numberTokensPlusRewardsForUserMinusCommission), "You dont have enough tokens inside this contract to withdraw from deposits"); if(numberTokensPlusRewardsForUserMinusCommission >0){ thisToken.transfer(owner, commissionForDAO1); } uint256 remainingBalance = thisToken.balanceOf(address(this)); if(remainingBalance>0){ stake(remainingBalance, address(this), tokenAddress); } emit Withdrawal(onBehalfOf, amount, tokenAddress); return true; } function calculateCommission(uint256 amount) view public returns(uint256){ uint256 commissionForDAO = (amount.mul(1000).mul(commission)).div(10000000); return commissionForDAO; } function changeOwner(address payable newAdmin) onlyOwner public returns (bool){ owner = newAdmin; return true; } function changeAdmin(address payable newOwner) onlyAdmin public returns (bool){ admin = newOwner; return true; } function getStakedBalance(address _owner, address tokenAddress) public view returns(uint256){ ERC20 staker = ERC20(tokenToAToken[tokenAddress]); return staker.balanceOf(_owner); } function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } function kill() virtual public onlyOwner { selfdestruct(owner); } event Deposit(address indexed user, uint256 amount, address token); event Withdrawal(address indexed user, uint256 amount, address token); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; //Core contract on Mainnet: 0x7a72b2C51670a3D77d4205C2DB90F6ddb09E4303 interface Oracle { function getTotalValueLockedInternalByToken(address tokenAddress, address tier2Address) external view returns (uint256); function getTotalValueLockedAggregated(uint256 optionIndex) external view returns (uint256); function getStakableTokens() view external returns (address[] memory, string[] memory); function getAPR ( address tier2Address, address tokenAddress ) external view returns ( uint256 ); function getAmountStakedByUser(address tokenAddress, address userAddress, address tier2Address) external view returns(uint256); function getUserCurrentReward(address userAddress, address tokenAddress, address tier2FarmAddress) view external returns(uint256); function getTokenPrice(address tokenAddress) view external returns(uint256); function getUserWalletBalance(address userAddress, address tokenAddress) external view returns (uint256); } interface Tier1Staking { function deposit ( string memory tier2ContractName, address tokenAddress, uint256 amount, address onBehalfOf ) external payable returns ( bool ); function withdraw ( string memory tier2ContractName, address tokenAddress, uint256 amount, address onBehalfOf ) external payable returns ( bool ); } interface Converter { function unwrap ( address sourceToken, address destinationToken, uint256 amount ) external payable returns ( uint256 ); function wrap ( address sourceToken, address[] memory destinationTokens, uint256 amount ) external payable returns ( address, uint256 ); } interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); function deposit() external payable; function withdraw(uint256 wad) external; } contract Core{ //globals address public oracleAddress; address public converterAddress; address public stakingAddress; Oracle oracle; Tier1Staking staking; Converter converter; address public ETH_TOKEN_PLACEHOLDER_ADDRESS = address(0x0); address payable public owner; address public WETH_TOKEN_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; ERC20 wethToken = ERC20(WETH_TOKEN_ADDRESS); uint256 approvalAmount = 1000000000000000000000000000000; //Reeentrancy uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: 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; } constructor() public payable { owner= msg.sender; setConverterAddress(0x1d17F9007282F9388bc9037688ADE4344b2cC49B); _status = _NOT_ENTERED; } fallback() external payable { //for the converter to unwrap ETH when delegate calling. The contract has to be able to accept ETH for this reason. The emergency withdrawal call is to pick any change up for these conversions. } function setOracleAddress(address theAddress) public onlyOwner returns(bool){ oracleAddress = theAddress; oracle = Oracle(theAddress); return true; } function setStakingAddress(address theAddress) public onlyOwner returns(bool){ stakingAddress = theAddress; staking = Tier1Staking(theAddress); return true; } function setConverterAddress(address theAddress) public onlyOwner returns(bool){ converterAddress = theAddress; converter = Converter(theAddress); return true; } function changeOwner(address payable newOwner) onlyOwner public returns (bool){ owner = newOwner; return true; } function deposit(string memory tier2ContractName, address tokenAddress, uint256 amount) nonReentrant() payable public returns (bool){ ERC20 token; if(tokenAddress==ETH_TOKEN_PLACEHOLDER_ADDRESS){ wethToken.deposit{value:msg.value}(); tokenAddress=WETH_TOKEN_ADDRESS; token = ERC20(tokenAddress); } else{ token = ERC20(tokenAddress); token.transferFrom(msg.sender, address(this), amount); } token.approve(stakingAddress, approvalAmount); bool result = staking.deposit(tier2ContractName, tokenAddress, amount, msg.sender); require(result, "There was an issue in core with your deposit request. Please see logs"); return result; } function withdraw(string memory tier2ContractName, address tokenAddress, uint256 amount) nonReentrant() payable public returns(bool){ bool result = staking.withdraw(tier2ContractName, tokenAddress, amount, msg.sender); require(result, "There was an issue in core with your withdrawal request. Please see logs"); return result; } function convert(address sourceToken, address[] memory destinationTokens, uint256 amount) public payable returns(address, uint256){ if(sourceToken != ETH_TOKEN_PLACEHOLDER_ADDRESS){ ERC20 token = ERC20(sourceToken); require(token.transferFrom(msg.sender, address(this), amount), "You must approve this contract or have enough tokens to do this conversion"); } ( address destinationTokenAddress, uint256 _amount) = converter.wrap{value:msg.value}(sourceToken, destinationTokens, amount); ERC20 token = ERC20(destinationTokenAddress); token.transfer(msg.sender, _amount); return (destinationTokenAddress, _amount); } //deconverting is mostly for LP tokens back to another token, as these cant be simply swapped on uniswap function deconvert(address sourceToken, address destinationToken, uint256 amount) public payable returns(uint256){ uint256 _amount = converter.unwrap{value:msg.value}(sourceToken, destinationToken, amount); ERC20 token = ERC20(destinationToken); token.transfer(msg.sender, _amount); return _amount; } function getStakableTokens() view public returns (address[] memory, string[] memory){ (address [] memory stakableAddresses, string [] memory stakableTokenNames) = oracle.getStakableTokens(); return (stakableAddresses, stakableTokenNames); } function getAPR(address tier2Address, address tokenAddress) public view returns(uint256){ uint256 result = oracle.getAPR(tier2Address, tokenAddress); return result; } function getTotalValueLockedAggregated(uint256 optionIndex) public view returns (uint256){ uint256 result = oracle.getTotalValueLockedAggregated(optionIndex); return result; } function getTotalValueLockedInternalByToken(address tokenAddress, address tier2Address) public view returns (uint256){ uint256 result = oracle.getTotalValueLockedInternalByToken( tokenAddress, tier2Address); return result; } function getAmountStakedByUser(address tokenAddress, address userAddress, address tier2Address) public view returns(uint256){ uint256 result = oracle.getAmountStakedByUser(tokenAddress, userAddress, tier2Address); return result; } function getUserCurrentReward(address userAddress, address tokenAddress, address tier2FarmAddress) view public returns(uint256){ return oracle.getUserCurrentReward( userAddress, tokenAddress, tier2FarmAddress); } function getTokenPrice(address tokenAddress) view public returns(uint256){ uint256 result = oracle.getTokenPrice(tokenAddress); return result; } function getUserWalletBalance(address userAddress, address tokenAddress) public view returns (uint256){ uint256 result = oracle.getUserWalletBalance( userAddress, tokenAddress); return result; } function updateWETHAddress(address newAddress) onlyOwner public returns(bool){ WETH_TOKEN_ADDRESS = newAddress; wethToken= ERC20(newAddress); } function adminEmergencyWithdrawAccidentallyDepositedTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_PLACEHOLDER_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; //https://etherscan.io/address/0x2ae7b37ab144b5f8c803546b83e81ad297d8c2c4#code interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface externalPlatformContract{ function getAPR(address _farmAddress, address _tokenAddress) external view returns(uint apy); function getStakedPoolBalanceByUser(address _owner, address tokenAddress) external view returns(uint256); function commission() external view returns(uint256); function totalAmountStaked(address tokenAddress) external view returns(uint256); function depositBalances(address userAddress, address tokenAddress) external view returns(uint256); } interface Oracle { function getAddress(string memory) view external returns (address); } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract TokenRewards{ using SafeMath for uint256; address public stakingTokensAddress; address public stakingLPTokensAddress; uint256 public tokensInRewardsReserve = 0; uint256 public lpTokensInRewardsReserve = 0; //(100% APR = 100000), .01% APR = 10) mapping (address => uint256) public tokenAPRs; mapping (address => bool) public stakingTokenWhitelist; mapping (address => mapping(address => uint256[])) public depositBalances; mapping (address => mapping(address => uint256)) public tokenDeposits; mapping (address => mapping(address => uint256[])) public depositBalancesDelegated; mapping (address => mapping(address => uint256)) public tokenDepositsDelegated; address ETH_TOKEN_ADDRESS = address(0x0); Oracle oracle; address oracleAddress; address payable public owner; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } modifier onlyTier1 { require( msg.sender == oracle.getAddress("TIER1"), "Only oracles TIER1 can call this function." ); _; } constructor() public payable { owner= msg.sender; } function updateOracleAddress(address newOracleAddress ) public onlyOwner returns (bool){ oracleAddress= newOracleAddress; oracle = Oracle(newOracleAddress); return true; } function updateStakingTokenAddress(address newAddress) public onlyOwner returns(bool){ stakingTokensAddress = newAddress; return true; } function updateLPStakingTokenAddress(address newAddress) public onlyOwner returns(bool){ stakingLPTokensAddress= newAddress; return true; } function addTokenToWhitelist(address newTokenAddress) public onlyOwner returns(bool){ stakingTokenWhitelist[newTokenAddress] =true; return true; } function removeTokenFromWhitelist(address tokenAddress) public onlyOwner returns(bool){ stakingTokenWhitelist[tokenAddress] =false; return true; } //APR should have be in this format (uint representing decimals): (100% APR = 100000), .01% APR = 10) function updateAPR(uint256 newAPR, address stakedToken) public onlyOwner returns(bool){ tokenAPRs[stakedToken] = newAPR; return true; } function stake(uint256 amount, address tokenAddress, address onBehalfOf) public returns(bool){ require(stakingTokenWhitelist[tokenAddress] ==true, "The token you are staking is not whitelisted to earn rewards"); ERC20 token = ERC20(tokenAddress); require(token.transferFrom(msg.sender, address(this), amount), "The msg.sender does not have enough tokens or has not approved token transfers from this address"); bool redepositing=false; if(tokenDeposits[onBehalfOf][tokenAddress] !=0){ //uint256 originalUserBalance = depositBalances[onBehalfOf]; //uint256 amountAfterRewards = unstakeAndClaim(onBehalfOf, address(this)); redepositing = true; } if(redepositing == true){ depositBalances[onBehalfOf][tokenAddress] = [block.timestamp, (tokenDeposits[onBehalfOf][tokenAddress].add(amount))] ; tokenDeposits[onBehalfOf][tokenAddress]= tokenDeposits[onBehalfOf][tokenAddress].add(amount); } else{ depositBalances[onBehalfOf][tokenAddress] = [block.timestamp, amount]; tokenDeposits[onBehalfOf][tokenAddress]= amount; } return true; } function stakeDelegated(uint256 amount, address tokenAddress, address onBehalfOf) public onlyTier1 returns(bool){ require(stakingTokenWhitelist[tokenAddress] ==true, "The token you are staking is not whitelisted to earn rewards"); ERC20 token = ERC20(tokenAddress); bool redepositing=false; if(tokenDepositsDelegated[onBehalfOf][tokenAddress] !=0){ //uint256 originalUserBalance = depositBalances[onBehalfOf]; //uint256 amountAfterRewards = unstakeAndClaim(onBehalfOf, address(this)); redepositing = true; } if(redepositing == true){ depositBalancesDelegated[onBehalfOf][tokenAddress] = [block.timestamp, (tokenDepositsDelegated[onBehalfOf][tokenAddress].add(amount))] ; tokenDepositsDelegated[onBehalfOf][tokenAddress]= tokenDepositsDelegated[onBehalfOf][tokenAddress].add(amount); } else{ depositBalancesDelegated[onBehalfOf][tokenAddress] = [block.timestamp, amount]; tokenDepositsDelegated[onBehalfOf][tokenAddress]= amount; } return true; } //when standalone, this is called. It's brother (delegated version that does not deal with transfers is called in other instances) function unstakeAndClaim(address onBehalfOf, address tokenAddress, address recipient) public returns (uint256){ require(stakingTokenWhitelist[tokenAddress] ==true, "The token you are staking is not whitelisted"); require(tokenDeposits[onBehalfOf][tokenAddress] > 0, "This user address does not have a staked balance for the token"); uint256 rewards = calculateRewards(depositBalances[onBehalfOf][tokenAddress][0], block.timestamp, tokenDeposits[onBehalfOf][tokenAddress], tokenAPRs[tokenAddress]); uint256 principalPlusRewards = tokenDeposits[onBehalfOf][tokenAddress].add(rewards); ERC20 principalToken = ERC20(tokenAddress); ERC20 rewardToken = ERC20(stakingTokensAddress); uint256 principalTokenDecimals= principalToken.decimals(); uint256 rewardTokenDecimals = rewardToken.decimals(); //account for different token decimals places/denoms if(principalTokenDecimals < rewardToken.decimals()){ uint256 decimalDiff = rewardTokenDecimals.sub(principalTokenDecimals); rewards = rewards.mul(10**decimalDiff); } if(principalTokenDecimals > rewardTokenDecimals){ uint256 decimalDiff = principalTokenDecimals.sub(rewardTokenDecimals); rewards = rewards.div(10**decimalDiff); } require(principalToken.transfer(recipient, tokenDeposits[onBehalfOf][tokenAddress]), "There are not enough tokens in the pool to return principal. Contact the pool owner."); //not requiring this below, as we need to ensure at the very least the user gets their deposited tokens above back. rewardToken.transfer(recipient, rewards); tokenDeposits[onBehalfOf][tokenAddress] = 0; depositBalances[onBehalfOf][tokenAddress]= [block.timestamp, 0]; return rewards; } //when apart of ecosystem, delegated is called function unstakeAndClaimDelegated(address onBehalfOf, address tokenAddress, address recipient) public onlyTier1 returns (uint256) { require(stakingTokenWhitelist[tokenAddress] ==true, "The token you are staking is not whitelisted"); require(tokenDepositsDelegated[onBehalfOf][tokenAddress] > 0, "This user address does not have a staked balance for the token"); uint256 rewards = calculateRewards(depositBalancesDelegated[onBehalfOf][tokenAddress][0], block.timestamp, tokenDepositsDelegated[onBehalfOf][tokenAddress], tokenAPRs[tokenAddress]); uint256 principalPlusRewards = tokenDepositsDelegated[onBehalfOf][tokenAddress].add(rewards); ERC20 principalToken = ERC20(tokenAddress); ERC20 rewardToken = ERC20(stakingTokensAddress); uint256 principalTokenDecimals= principalToken.decimals(); uint256 rewardTokenDecimals = rewardToken.decimals(); //account for different token decimals places/denoms if(principalTokenDecimals < rewardToken.decimals()){ uint256 decimalDiff = rewardTokenDecimals.sub(principalTokenDecimals); rewards = rewards.mul(10**decimalDiff); } if(principalTokenDecimals > rewardTokenDecimals){ uint256 decimalDiff = principalTokenDecimals.sub(rewardTokenDecimals); rewards = rewards.div(10**decimalDiff); } rewardToken.transfer(recipient, rewards); tokenDepositsDelegated[onBehalfOf][tokenAddress] = 0; depositBalancesDelegated[onBehalfOf][tokenAddress]= [block.timestamp, 0]; return rewards; } function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } //APR should have 3 zeroes after decimal (100% APR = 100000), .01% APR = 10) function calculateRewards(uint256 timestampStart, uint256 timestampEnd, uint256 principalAmount, uint256 apr) public view returns(uint256){ uint256 timeDiff = timestampEnd.sub(timestampStart); if(timeDiff <= 0){ return 0; } apr = apr.mul(10000000); //365.25 days, accounting for leap years. We should just have 1/4 days at the end of each year and cause more mass confusion than daylight savings. "Please set your clocks back 6 hours on Jan 1st, Thank you"" //Imagine new years. You get to do it twice after 6hours. Or would it be recursive and end up in an infinite loop. Is that the secret to freezing time and staying young? Maybe because it's 2020. uint256 secondsInAvgYear = 31557600; uint256 rewardsPerSecond = (principalAmount.mul(apr)).div(secondsInAvgYear); uint256 rawRewards = timeDiff.mul(rewardsPerSecond); uint256 normalizedRewards = rawRewards.div(10000000000); return normalizedRewards; } } /* _____ _ | __ \| | | |__) | | _____ ___ _ ___ | ___/| |/ _ \ \/ / | | / __| | | | | __/> <| |_| \__ \ |_| _|_|\___/_/\_\\__,_|___/ _ _____ __ __ | | | | (_) | | | __ \ \ \ / / | | | |_ __ _ _____ ____ _ _ __ | | | |__) | \ \ /\ / / __ __ _ _ __ _ __ ___ _ __ | | | | '_ \| / __\ \ /\ / / _` | '_ \ | | | ___/ \ \/ \/ / '__/ _` | '_ \| '_ \ / _ \ '__| | |__| | | | | \__ \\ V V / (_| | |_) | | |____| | \ /\ /| | | (_| | |_) | |_) | __/ | \____/|_| |_|_|___/ \_/\_/ \__,_| .__/ |______|_| \/ \/ |_| \__,_| .__/| .__/ \___|_| | | | | | | |_| |_| |_| */ // 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.7.4; interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface WrappedETH { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); function deposit() external payable; function withdraw(uint256 wad) external; } interface UniswapFactory{ function getPair(address tokenA, address tokenB) external view returns (address pair); } interface UniswapV2{ function addLiquidity ( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH ( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidityETH ( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns ( uint256 amountToken, uint256 amountETH ); function removeLiquidity ( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB ); function swapExactTokensForTokens ( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns ( uint256[] memory amounts ); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract WrapAndUnWrap{ using SafeMath for uint256; address payable public owner; //placehodler token address for specifying eth tokens address public ETH_TOKEN_ADDRESS = address(0x0); address public WETH_TOKEN_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; WrappedETH wethToken = WrappedETH(WETH_TOKEN_ADDRESS); uint256 approvalAmount = 1000000000000000000000000000000; uint256 longTimeFromNow = 1000000000000000000000000000; address uniAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address uniFactoryAddress = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; UniswapV2 uniswapExchange = UniswapV2(uniAddress); UniswapFactory factory = UniswapFactory(uniFactoryAddress); mapping (address => address[]) public lpTokenAddressToPairs; mapping(string=>address) public stablecoins; mapping(address=>mapping(address=>address[])) public presetPaths; bool public changeRecpientIsOwner; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } fallback() external payable { } constructor() public payable { stablecoins["DAI"] = 0x6B175474E89094C44Da98b954EedeAC495271d0F; stablecoins["USDT"] = 0xdAC17F958D2ee523a2206206994597C13D831ec7; stablecoins["USDC"] = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; changeRecpientIsOwner = false; owner= msg.sender; } function wrap(address sourceToken, address[] memory destinationTokens, uint256 amount) public payable returns(address, uint256){ ERC20 sToken = ERC20(sourceToken); ERC20 dToken = ERC20(destinationTokens[0]); if(destinationTokens.length==1){ if(sourceToken != ETH_TOKEN_ADDRESS){ require(sToken.transferFrom(msg.sender, address(this), amount), "You have not approved this contract or do not have enough token for this transfer 1"); if(sToken.allowance(address(this), uniAddress) < amount.mul(2)){ sToken.approve(uniAddress, amount.mul(3)); } } conductUniswap(sourceToken, destinationTokens[0], amount); uint256 thisBalance = dToken.balanceOf(address(this)); dToken.transfer(msg.sender, thisBalance); return (destinationTokens[0], thisBalance); } else{ bool updatedweth =false; if(sourceToken == ETH_TOKEN_ADDRESS){ WrappedETH sToken1 = WrappedETH(WETH_TOKEN_ADDRESS); sToken1.deposit{value:msg.value}(); sToken = ERC20(WETH_TOKEN_ADDRESS); amount = msg.value; sourceToken = WETH_TOKEN_ADDRESS; updatedweth =true; } if(sourceToken != ETH_TOKEN_ADDRESS && updatedweth==false){ require(sToken.transferFrom(msg.sender, address(this), amount), "You have not approved this contract or do not have enough token for this transfer 2"); if(sToken.allowance(address(this), uniAddress) < amount.mul(2)){ sToken.approve(uniAddress, amount.mul(3)); } } if(destinationTokens[0] == ETH_TOKEN_ADDRESS){ destinationTokens[0] = WETH_TOKEN_ADDRESS; } if(destinationTokens[1] == ETH_TOKEN_ADDRESS){ destinationTokens[1] = WETH_TOKEN_ADDRESS; } if(sourceToken !=destinationTokens[0]){ conductUniswap(sourceToken, destinationTokens[0], amount.div(2)); } if(sourceToken !=destinationTokens[1]){ conductUniswap(sourceToken, destinationTokens[1], amount.div(2)); } ERC20 dToken2 = ERC20(destinationTokens[1]); uint256 dTokenBalance = dToken.balanceOf(address(this)); uint256 dTokenBalance2 = dToken2.balanceOf(address(this)); if(dToken.allowance(address(this), uniAddress) < dTokenBalance.mul(2)){ dToken.approve(uniAddress, dTokenBalance.mul(3)); } if(dToken2.allowance(address(this), uniAddress) < dTokenBalance2.mul(2)){ dToken2.approve(uniAddress, dTokenBalance2.mul(3)); } (,,uint liquidityCoins) = uniswapExchange.addLiquidity(destinationTokens[0],destinationTokens[1], dTokenBalance, dTokenBalance2, 1,1, address(this), longTimeFromNow); address thisPairAddress = factory.getPair(destinationTokens[0],destinationTokens[1]); ERC20 lpToken = ERC20(thisPairAddress); lpTokenAddressToPairs[thisPairAddress] =[destinationTokens[0], destinationTokens[1]]; uint256 thisBalance =lpToken.balanceOf(address(this)); lpToken.transfer(msg.sender, thisBalance); //transfer any change to changeRecipient (from a pair imbalance. Should never be more than a few basis points) address changeRecipient = msg.sender; if(changeRecpientIsOwner == true){ changeRecipient = owner; } if(dToken.balanceOf(address(this)) >0){ dToken.transfer(changeRecipient, dToken.balanceOf(address(this))); } if(dToken2.balanceOf(address(this)) >0){ dToken2.transfer(changeRecipient, dToken2.balanceOf(address(this))); } return (thisPairAddress,thisBalance) ; } } function updateStableCoinAddress(string memory coinName, address newAddress) public onlyOwner returns(bool){ stablecoins[coinName] = newAddress; return true; } function updatePresetPaths(address sellToken, address buyToken, address[] memory newPath ) public onlyOwner returns(bool){ presetPaths[sellToken][buyToken] = newPath; return true; } //owner can turn on ability to collect a small fee from trade imbalances on LP conversions function updateChangeRecipientBool(bool changeRecpientIsOwnerBool ) public onlyOwner returns(bool){ changeRecpientIsOwner = changeRecpientIsOwnerBool; return true; } function unwrap(address sourceToken, address destinationToken, uint256 amount) public payable returns( uint256){ address originalDestinationToken = destinationToken; ERC20 sToken = ERC20(sourceToken); if(destinationToken == ETH_TOKEN_ADDRESS){ destinationToken = WETH_TOKEN_ADDRESS; } ERC20 dToken = ERC20(destinationToken); if(sourceToken != ETH_TOKEN_ADDRESS){ require(sToken.transferFrom(msg.sender, address(this), amount), "You have not approved this contract or do not have enough token for this transfer 3 unwrapping"); } if(lpTokenAddressToPairs[sourceToken].length !=0){ if(sToken.allowance(address(this), uniAddress) < amount.mul(2)){ sToken.approve(uniAddress, amount.mul(3)); } uniswapExchange.removeLiquidity(lpTokenAddressToPairs[sourceToken][0], lpTokenAddressToPairs[sourceToken][1], amount, 0,0, address(this), longTimeFromNow); ERC20 pToken1 = ERC20(lpTokenAddressToPairs[sourceToken][0]); ERC20 pToken2 = ERC20(lpTokenAddressToPairs[sourceToken][1]); uint256 pTokenBalance = pToken1.balanceOf(address(this)); uint256 pTokenBalance2 = pToken2.balanceOf(address(this)); if(pToken1.allowance(address(this), uniAddress) < pTokenBalance.mul(2)){ pToken1.approve(uniAddress, pTokenBalance.mul(3)); } if(pToken2.allowance(address(this), uniAddress) < pTokenBalance2.mul(2)){ pToken2.approve(uniAddress, pTokenBalance2.mul(3)); } if(lpTokenAddressToPairs[sourceToken][0] != destinationToken){ conductUniswap(lpTokenAddressToPairs[sourceToken][0], destinationToken, pTokenBalance); } if(lpTokenAddressToPairs[sourceToken][1] != destinationToken){ conductUniswap(lpTokenAddressToPairs[sourceToken][1], destinationToken, pTokenBalance2); } uint256 destinationTokenBalance = dToken.balanceOf(address(this)); if(originalDestinationToken == ETH_TOKEN_ADDRESS){ wethToken.withdraw(destinationTokenBalance); msg.sender.transfer(address(this).balance); } else{ dToken.transfer(msg.sender, destinationTokenBalance); } return destinationTokenBalance; } else{ if(sToken.allowance(address(this), uniAddress) < amount.mul(2)){ sToken.approve(uniAddress, amount.mul(3)); } if(sourceToken != destinationToken){ conductUniswap(sourceToken, destinationToken, amount); } uint256 destinationTokenBalance = dToken.balanceOf(address(this)); dToken.transfer(msg.sender, destinationTokenBalance); return destinationTokenBalance; } } function updateOwnerAddress(address payable newOwner) onlyOwner public returns (bool){ owner = newOwner; return true; } function updateUniswapExchange(address newAddress ) public onlyOwner returns (bool){ uniswapExchange = UniswapV2( newAddress); uniAddress = newAddress; return true; } function updateUniswapFactory(address newAddress ) public onlyOwner returns (bool){ factory = UniswapFactory( newAddress); uniFactoryAddress = newAddress; return true; } function conductUniswap(address sellToken, address buyToken, uint amount) internal returns (uint256 amounts1){ if(sellToken ==ETH_TOKEN_ADDRESS && buyToken == WETH_TOKEN_ADDRESS){ wethToken.deposit{value:msg.value}(); } else if(sellToken == address(0x0)){ // address [] memory addresses = new address[](2); address [] memory addresses = getBestPath(WETH_TOKEN_ADDRESS, buyToken, amount); //addresses[0] = WETH_TOKEN_ADDRESS; //addresses[1] = buyToken; uniswapExchange.swapExactETHForTokens{value:msg.value}(0, addresses, address(this), 1000000000000000 ); } else if(sellToken == WETH_TOKEN_ADDRESS){ wethToken.withdraw(amount); //address [] memory addresses = new address[](2); address [] memory addresses = getBestPath(WETH_TOKEN_ADDRESS, buyToken, amount); //addresses[0] = WETH_TOKEN_ADDRESS; //addresses[1] = buyToken; uniswapExchange.swapExactETHForTokens{value:amount}(0, addresses, address(this), 1000000000000000 ); } else{ address [] memory addresses = getBestPath(sellToken, buyToken, amount); uint256 [] memory amounts = conductUniswapT4T(addresses, amount ); uint256 resultingTokens = amounts[amounts.length-1]; return resultingTokens; } } //gets the best path to route the transaction on Uniswap function getBestPath(address sellToken, address buyToken, uint256 amount) public view returns (address[] memory){ address [] memory defaultPath =new address[](2); defaultPath[0]=sellToken; defaultPath[1] = buyToken; if(presetPaths[sellToken][buyToken].length !=0){ return presetPaths[sellToken][buyToken]; } if(sellToken == stablecoins["DAI"] || sellToken == stablecoins["USDC"] || sellToken == stablecoins["USDT"]){ return defaultPath; } if(buyToken == stablecoins["DAI"] || buyToken == stablecoins["USDC"] || buyToken == stablecoins["USDT"]){ return defaultPath; } address[] memory daiPath = new address[](3); address[] memory usdcPath =new address[](3); address[] memory usdtPath =new address[](3); daiPath[0] = sellToken; daiPath[1] = stablecoins["DAI"]; daiPath[2] = buyToken; usdcPath[0] = sellToken; usdcPath[1] = stablecoins["USDC"]; usdcPath[2] = buyToken; usdtPath[0] = sellToken; usdtPath[1] = stablecoins["USDT"]; usdtPath[2] = buyToken; uint256 directPathOutput = getPriceFromUniswap(defaultPath, amount)[1]; uint256[] memory daiPathOutputRaw = getPriceFromUniswap(daiPath, amount); uint256[] memory usdtPathOutputRaw = getPriceFromUniswap(usdtPath, amount); uint256[] memory usdcPathOutputRaw = getPriceFromUniswap(usdcPath, amount); //uint256 directPathOutput = directPathOutputRaw[directPathOutputRaw.length-1]; uint256 daiPathOutput = daiPathOutputRaw[daiPathOutputRaw.length-1]; uint256 usdtPathOutput = usdtPathOutputRaw[usdtPathOutputRaw.length-1]; uint256 usdcPathOutput = usdcPathOutputRaw[usdcPathOutputRaw.length-1]; uint256 bestPathOutput = directPathOutput; address[] memory bestPath = new address[](2); address[] memory bestPath3 = new address[](3); //return defaultPath; bestPath = defaultPath; bool isTwoPath = true; if(directPathOutput < daiPathOutput){ isTwoPath=false; bestPathOutput = daiPathOutput; bestPath3 = daiPath; } if(bestPathOutput < usdcPathOutput){ isTwoPath=false; bestPathOutput = usdcPathOutput; bestPath3 = usdcPath; } if(bestPathOutput < usdtPathOutput){ isTwoPath=false; bestPathOutput = usdtPathOutput; bestPath3 = usdtPath; } require(bestPathOutput >0, "This trade will result in getting zero tokens back. Reverting"); if(isTwoPath==true){ return bestPath; } else{ return bestPath3; } } function getPriceFromUniswap(address [] memory theAddresses, uint amount) public view returns (uint256[] memory amounts1){ try uniswapExchange.getAmountsOut(amount,theAddresses ) returns (uint256[] memory amounts){ return amounts; } catch { uint256 [] memory amounts2= new uint256[](2); amounts2[0]=0; amounts2[1]=0; return amounts2; } } function conductUniswapT4T(address [] memory theAddresses, uint amount) internal returns (uint256[] memory amounts1){ uint256 deadline = 1000000000000000; uint256 [] memory amounts = uniswapExchange.swapExactTokensForTokens(amount, 0, theAddresses, address(this),deadline ); return amounts; } function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } function changeOwner(address payable newOwner) onlyOwner public returns (bool){ owner = newOwner; return true; } function getUserTokenBalance(address userAddress, address tokenAddress) public view returns (uint256){ ERC20 token = ERC20(tokenAddress); return token.balanceOf(userAddress); } } // SPDX-License-Identifier: MIT //Contract Address: 0xA320c4442542E6CD793Fb5F46c18fB7A6213615C //PICKLE-UNI-USDT/ETH contract name for parent tier 1 pragma solidity >=0.4.22 <0.8.0; interface ERC20 { function totalSupply() external view returns(uint supply); function balanceOf(address _owner) external view returns(uint balance); function transfer(address _to, uint _value) external returns(bool success); function transferFrom(address _from, address _to, uint _value) external returns(bool success); function approve(address _spender, uint _value) external returns(bool success); function allowance(address _owner, address _spender) external view returns(uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } interface StakingInterface { function approve ( address spender, uint256 amount ) external returns ( bool ); function balanceOf ( address account ) external view returns ( uint256 ); function deposit ( uint256 _amount ) external; function depositAll ( ) external; function withdraw ( uint256 _shares ) external; function withdrawAll ( ) external; } library SafeMath { function mul(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal view 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 view returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal view returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Tier2FarmController{ using SafeMath for uint256; address payable public owner; address public platformToken = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; address public tokenStakingContract = 0x09FC573c502037B149ba87782ACC81cF093EC6ef; address ETH_TOKEN_ADDRESS = address(0x0); mapping (string => address) public stakingContracts; mapping (address => address) public tokenToFarmMapping; mapping (string => address) public stakingContractsStakingToken; mapping (address => mapping (address => uint256)) public depositBalances; uint256 public commission = 400; // Default is 4 percent string public farmName = 'Pickle.Finance'; mapping (address => uint256) public totalAmountStaked; modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } constructor() public payable { stakingContracts["USDTPICKLEJAR"] = 0x09FC573c502037B149ba87782ACC81cF093EC6ef; stakingContractsStakingToken ["USDTPICKLEJAR"] = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; tokenToFarmMapping[stakingContractsStakingToken ["USDTPICKLEJAR"]] = stakingContracts["USDTPICKLEJAR"]; owner= msg.sender; } fallback() external payable { } function addOrEditStakingContract(string memory name, address stakingAddress, address stakingToken ) public onlyOwner returns (bool){ stakingContracts[name] = stakingAddress; stakingContractsStakingToken[name] = stakingToken; tokenToFarmMapping[stakingToken] = stakingAddress; return true; } function updateCommission(uint amount) public onlyOwner returns(bool){ commission = amount; return true; } function deposit(address tokenAddress, uint256 amount, address onBehalfOf) payable onlyOwner public returns (bool){ if(tokenAddress == 0x0000000000000000000000000000000000000000){ depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] + msg.value; stake(amount, onBehalfOf, tokenAddress ); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].add(amount); emit Deposit(onBehalfOf, amount, tokenAddress); return true; } ERC20 thisToken = ERC20(tokenAddress); require(thisToken.transferFrom(msg.sender, address(this), amount), "Not enough tokens to transferFrom or no approval"); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] + amount; uint256 approvedAmount = thisToken.allowance(address(this), tokenToFarmMapping[tokenAddress]); if(approvedAmount < amount ){ thisToken.approve(tokenToFarmMapping[tokenAddress], amount.mul(10000000)); } stake(amount, onBehalfOf, tokenAddress ); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].add(amount); emit Deposit(onBehalfOf, amount, tokenAddress); return true; } function stake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.deposit(amount); return true; } function unstake(uint256 amount, address onBehalfOf, address tokenAddress) internal returns(bool){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); staker.approve(tokenToFarmMapping[tokenAddress], 1000000000000000000000000000000); staker.withdrawAll(); return true; } function getStakedPoolBalanceByUser(address _owner, address tokenAddress) public view returns(uint256){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); uint256 numberTokens = staker.balanceOf(address(this)); uint256 usersBalancePercentage = (depositBalances[_owner][tokenAddress].mul(1000000)).div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser= (numberTokens.mul(1000).mul(usersBalancePercentage)).div(1000000000); return numberTokensPlusRewardsForUser; } function withdraw(address tokenAddress, uint256 amount, address payable onBehalfOf) onlyOwner payable public returns(bool){ ERC20 thisToken = ERC20(tokenAddress); //uint256 numberTokensPreWithdrawal = getStakedBalance(address(this), tokenAddress); if(tokenAddress == 0x0000000000000000000000000000000000000000){ require(depositBalances[msg.sender][tokenAddress] >= amount, "You didnt deposit enough eth"); totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = depositBalances[onBehalfOf][tokenAddress] - amount; onBehalfOf.send(amount); return true; } require(depositBalances[onBehalfOf][tokenAddress] > 0, "You dont have any tokens deposited"); //uint256 numberTokensPostWithdrawal = thisToken.balanceOf(address(this)); //uint256 usersBalancePercentage = depositBalances[onBehalfOf][tokenAddress].div(totalAmountStaked[tokenAddress]); uint256 numberTokensPlusRewardsForUser1 = getStakedPoolBalanceByUser(onBehalfOf, tokenAddress); uint256 commissionForDAO1 = calculateCommission(numberTokensPlusRewardsForUser1); uint256 numberTokensPlusRewardsForUserMinusCommission = numberTokensPlusRewardsForUser1-commissionForDAO1; unstake(amount, onBehalfOf, tokenAddress); //staking platforms only withdraw all for the most part, and for security sticking to this totalAmountStaked[tokenAddress] = totalAmountStaked[tokenAddress].sub(depositBalances[onBehalfOf][tokenAddress]); depositBalances[onBehalfOf][tokenAddress] = 0; require(numberTokensPlusRewardsForUserMinusCommission >0, "For some reason numberTokensPlusRewardsForUserMinusCommission is zero"); require(thisToken.transfer(onBehalfOf, numberTokensPlusRewardsForUserMinusCommission), "You dont have enough tokens inside this contract to withdraw from deposits"); if(numberTokensPlusRewardsForUserMinusCommission >0){ thisToken.transfer(owner, commissionForDAO1); } uint256 remainingBalance = thisToken.balanceOf(address(this)); if(remainingBalance>0){ stake(remainingBalance, address(this), tokenAddress); } emit Withdrawal(onBehalfOf, amount, tokenAddress); return true; } function calculateCommission(uint256 amount) view public returns(uint256){ uint256 commissionForDAO = (amount.mul(1000).mul(commission)).div(10000000); return commissionForDAO; } function changeOwner(address payable newOwner) onlyOwner public returns (bool){ owner = newOwner; return true; } function getStakedBalance(address _owner, address tokenAddress) public view returns(uint256){ StakingInterface staker = StakingInterface(tokenToFarmMapping[tokenAddress]); return staker.balanceOf(_owner); } function adminEmergencyWithdrawTokens(address token, uint amount, address payable destination) public onlyOwner returns(bool) { if (address(token) == ETH_TOKEN_ADDRESS) { destination.transfer(amount); } else { ERC20 tokenToken = ERC20(token); require(tokenToken.transfer(destination, amount)); } return true; } function kill() virtual public onlyOwner { selfdestruct(owner); } event Deposit(address indexed user, uint256 amount, address token); event Withdrawal(address indexed user, uint256 amount, address token); }
Public SMART CONTRACT AUDIT REPORT for PLEXUS Prepared By: Shuxiao Wang PeckShield February 2, 2021 1/29 PeckShield Audit Report #: 2021-026Public Document Properties Client Plexus Title Smart Contract Audit Report Target Plexus Version 1.0 Author Xuxian Jiang Auditors Xuxian Jiang, Huaguo Shi Reviewed by Shuxiao Wang Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 February 2, 2021 Xuxian Jiang Final Release 1.0-rc1 January 30, 2021 Xuxian Jiang Release Candidate #1 0.3 January 29, 2021 Xuxian Jiang Additional Findings 0.2 January 22, 2021 Xuxian Jiang Additional Findings 0.1 January 18, 2021 Xuxian Jiang Initial Draft 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/29 PeckShield Audit Report #: 2021-026Public Contents 1 Introduction 4 1.1 About Plexus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Wrong Hardcoded Aave AToken Address . . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 Accommodation of approve() Idiosyncrasies . . . . . . . . . . . . . . . . . . . . . . 12 3.3 Business Logic Errors in tier2Aave::withdraw() . . . . . . . . . . . . . . . . . . . . . 14 3.4 Improper Handling of ETHs in tier2Farm::deposit() . . . . . . . . . . . . . . . . . . 16 3.5 Loss of Staked Funds With Wrongly Triggered tier2Farm::kill() . . . . . . . . . . . . 17 3.6 Sufficient Allowance Guarantee in tier2Farm::withdraw() . . . . . . . . . . . . . . . . 18 3.7 Possible Front-Running For Reduced Return . . . . . . . . . . . . . . . . . . . . . . 20 3.8 Incompatibility with Deflationary/Rebasing Tokens . . . . . . . . . . . . . . . . . . . 22 3.9 Lack Of Sanity Checks For System Parameters . . . . . . . . . . . . . . . . . . . . . 23 3.10 Removal Of Unused Variables And Code . . . . . . . . . . . . . . . . . . . . . . . . 24 3.11 Safe-Version Replacement With safeTransfer(), safeTransferFrom(), And safeApprove() 25 4 Conclusion 27 References 28 3/29 PeckShield Audit Report #: 2021-026Public 1 | Introduction Given the opportunity to review the design document and related smart contract source code of the Plexusprotocol, 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 Plexus The Plexusprotocol is a decentralized distribution and aggregation channel for DeFi protocols. In other words, it is a yield farming aggregator and Plexusrewards ecosystem. At the protocol layer, Plexusis an ecosystem of smart-contracts that provide bridges between protocols to increase capital efficiency. It allows participating users to earn interest from popular lending platforms (e.g., Aave) or external yield farms by depositing supported ERC20-compliant tokens into the protocol. In the meantime, the participating users are also rewarded with the PLXERC20 token rewards. It continues the yield-farming paradigm in current DeFi offerings with additional aggregation functionality and improved capital deployment capability to further attract and incentivize users for participation. The basic information of the Plexus protocol is as follows: Table 1.1: Basic Information of Plexus ItemDescription IssuerPlexus Website https://plexus.money TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report February 2, 2021 4/29 PeckShield Audit Report #: 2021-026Public In the following, we show the Git repository of reviewed files and the commit hash value used in this audit. •https://github.com/stimuluspackage/PlexusContracts.git (f7e8196) And here is the commit ID after all fixes for the issues found in the audit have been checked in: •https://github.com/stimuluspackage/PlexusContracts.git (7d34e1e) 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. 5/29 PeckShield Audit Report #: 2021-026Public 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) [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. 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), 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. 6/29 PeckShield Audit Report #: 2021-026Public 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/29 PeckShield Audit Report #: 2021-026Public 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/29 PeckShield Audit Report #: 2021-026Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the Plexus. 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 6 Informational 2 Total 11 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 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/29 PeckShield Audit Report #: 2021-026Public 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, 6low-severity vulnerabilities, and 2informational recommendation. Table 2.1: Key Audit Findings of Plexus ID Severity Title Category Status PVE-001 Medium Wrong Hardcoded Aave AToken Address Business Logic Resolved PVE-002 Low Accommodation of approve() Idiosyn- crasiesBusiness Logic Resolved PVE-003 Low Business Logic Errors in tier2Aave::withdraw()Business Logic Resolved PVE-004 Low Improper Handling of ETHs in tier2Farm::deposit()Coding Practices Resolved PVE-005 Medium Loss of Staked Funds With Wrongly Trig- gered tier2Farm::kill()Business Logic Resolved PVE-006 Low Sufficient Allowance Guarantee in tier2Farm::withdraw()Coding Practices Resolved PVE-007 Low Possible Front-Running For Reduced Re- turnTime and State Resolved PVE-008 Informational Incompatibility with Deflationary/Rebas- ing TokenBusiness Logic Resolved PVE-009 Low LackOfSanityChecksForSystemParam- etersBusiness Logic Resolved PVE-010 Informational Removal Of Unused Variables And Code Coding Practices Resolved PVE-011 Medium Safe-Version Replacement With safe- Transfer(), safeTransferFrom(), And safeApprove()Coding 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/29 PeckShield Audit Report #: 2021-026Public 3 | Detailed Results 3.1 Wrong Hardcoded Aave AToken Address •ID: PVE-001 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: tier2Aave •Category: Business Logic [6] •CWE subcategory: N/A Description DeFi protocols typically have a number of system-wide parameters that can be dynamically config- ured on demand. The Plexus protocol is no exception. Specifically, if we examine the construc- tor of the tier2Aave contract, it has defined a number of system-wide states: stakingContracts , stakingContractsStakingToken ,tokenToAToken , and aTokenToToken . In the following, we show the re- lated constructor. 112 constructor ( )public payable { 113 s t a k i n g C o n t r a c t s [ " DAI " ] =0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9 ; 114 s t a k i n g C o n t r a c t s [ " ALL " ] =0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9 ; 115 s t a k i n g C o n t r a c t s S t a k i n g T o k e n [ " DAI " ] = 0 x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50 ; 116 tokenToAToken [ 0 x6B175474E89094C44Da98b954EedeAC495271d0F]= 0 x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50 ; 117 aTokenToToken [ 0 x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50]= 0 x6B175474E89094C44Da98b954EedeAC495271d0F ; 118 tokenToFarmMapping [ s t a k i n g C o n t r a c t s S t a k i n g T o k e n [ " DAI " ] ] = s t a k i n g C o n t r a c t s [ " DAI " ] ; 119 owner= msg.sender ; 120 admin = msg.sender ; 121 122 } Listing 3.1: tier2Aave :: constructor () 11/29 PeckShield Audit Report #: 2021-026Public It is important to ensure the correctness of these token contracts as they define various important aspects of the protocol operation and need to exercise extra care when configuring or updating it. It comes to our attention that the configured DAIand the associated aDAImapping is incorrect. A misconfigured DAI/aDAI mapping could potentially result in loss of user funds! Recommendation Validate these hard-coded token contracts and ensure they are consistent with the mainnet deployment. Status The issue has been fixed by this commit: 6408424. 3.2 Accommodation of approve() Idiosyncrasies •ID: PVE-002 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Business Logic [6] •CWE subcategory: CWE-841 [4] Description In this section, we examine certain non-compliant ERC20 tokens that may exhibit specific idiosyn- crasiesintheir approve() implementation. Therespectiveidiosyncrasiesmaybepresentinwidely-used token contracts and need to be accommodated for seamless integration and support. 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) ) ) ; 12/29 PeckShield Audit Report #: 2021-026Public 207 a l l o w e d [ msg.sender ] [ _spender ] = _value ; 208 Approval ( msg.sender , _spender , _value ) ; 209 } Listing 3.2: USDT Token Contract Because of that, a normal call to approve() with a currently non-zero allowance may fail. In the following, we use as an example the depositroutine from the tier2Farm contract. The routine performs the intended investment for later rewards. To accommodate the specific idiosyncrasy, there is a need to approve() twice (line 150): the first one reduces the allowance to 0; and the second one sets the new allowance. 129 function d e p o s i t ( address tokenAddress , uint256 amount , address onBehalfOf ) payable onlyOwner public returns (bool ) { 132 i f( tokenAddress == 0 x0000000000000000000000000000000000000000 ) { 134 d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] = d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] + msg.value ; 136 s t a k e ( amount , onBehalfOf , tokenAddress ) ; 137 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . add ( amount ) ; 138 emit Deposit ( onBehalfOf , amount , tokenAddress ) ; 139 return true ; 141 } 143 ERC20 thisToken = ERC20( tokenAddress ) ; 144 require ( thisToken . t r a n s f e r F r o m ( msg.sender ,address (t h i s ) , amount ) , " Not enough tokens to transferFrom or no approval " ) ; 146 d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] = d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] + amount ; 148 uint256 approvedAmount = thisToken . a l l o w a n c e ( address (t h i s ) , tokenToFarmMapping [ tokenAddress ] ) ; 149 i f( approvedAmount < amount ) { 150 thisToken . approve ( tokenToFarmMapping [ tokenAddress ] , amount . mul (10000000) ) ; 151 } 152 s t a k e ( amount , onBehalfOf , tokenAddress ) ; 154 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . add ( amount ) ; 156 emit Deposit ( onBehalfOf , amount , tokenAddress ) ; 157 return true ; 158 } Listing 3.3: tier2Farm :: deposit () 13/29 PeckShield Audit Report #: 2021-026Public Recommendation Accommodate the above-mentioned idiosyncrasy of approve() . Status The issue has been fixed by this commit: c1fb42b. 3.3 Business Logic Errors in tier2Aave::withdraw() •ID: PVE-003 •Severity: Low •Likelihood: Low •Impact: Low•Target: tier2Aave •Category: Business Logic [6] •CWE subcategory: CWE-841 [4] Description As a decentralized distribution and aggregation channel for DeFi protocols, the Plexusprotocol is extensible in supporting or aggregating external protocols for additional yields. In the meantime, each external protocol needs to be supported by following the defined interfaces for interaction. In the following, we examine one such interface, i.e., withdraw() . To elaborate, we show below the withdraw() routine from the tier2Aave contract. As the name indicates, this routine handles the withdraw request from the participating user. 205 function withdraw ( address tokenAddress , uint256 amount , address payable onBehalfOf ) onlyOwner payable public returns (bool ) { 206 207 ERC20 thisToken = ERC20( tokenAddress ) ; 208 // uint256 numberTokensPreWithdrawal = getStakedBalance ( address ( this ), tokenAddress ); 209 210 i f( tokenAddress == 0 x0000000000000000000000000000000000000000 ) { 211 require ( d e p o s i t B a l a n c e s [ msg.sender ] [ tokenAddress ] >= amount , " You didnt deposit enough eth " ) ; 212 213 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . sub ( d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] ) ; 214 d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] = d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] *amount ; 215 onBehalfOf . send ( amount ) ; 216 return true ; 217 218 } 219 220 221 require ( d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] > 0 , " You dont have any tokens deposited " ) ; 222 223 224 14/29 PeckShield Audit Report #: 2021-026Public 225 // uint256 numberTokensPostWithdrawal = thisToken . balanceOf ( address ( this )); 226 227 // uint256 usersBalancePercentage = depositBalances [ onBehalfOf ][ tokenAddress ]. div ( totalAmountStaked [ tokenAddress ]); 228 229 uint256 numberTokensPlusRewardsForUser1 = getStakedPoolBalanceByUser ( onBehalfOf , tokenAddress ) ; 230 uint256 commissionForDAO1 = c a l c u l a t e C o m m i s s i o n ( numberTokensPlusRewardsForUser1 ) ; 231 uint256 numberTokensPlusRewardsForUserMinusCommission = numberTokensPlusRewardsForUser1 *commissionForDAO1 ; 232 233 unstake ( amount , onBehalfOf , tokenAddress ) ; 234 235 // staking platforms only withdraw all for the most part , and for security sticking to this 236 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . sub ( d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] ) ; 237 . . . 238 239 } Listing 3.4: tier2Aave :: withdraw() It comes to our attention that the above routine does not properly handle certain token ad- dresses. In particular, the lending platform Aavedoes not directly support ETH. Instead, the wrapped version of ETH, i.e., WETH, is supported. As a result, the code snippet at lines 210 * 218 becomes largely irrelevant and may be removed. Even it is relevant, the reduction of totalAmountStaked[ tokenAddress] and depositBalances[onBehalfOf][tokenAddress] is not consistent: the former is re- duced by depositBalances[onBehalfOf][tokenAddress] , while the latter is reduced by amount! Note other tier2contracts, e.g., tier2Farm ,tier2Pickle , and tier2Aggregator , share similar issues. Moreover, the withdraw() function takes an amountparameter, indicating the amount of balance that is supposed to be withdrawn. However, it turns out partial withdrawal is not allowed. The team has confirmed that each withdraw implies a full withdrawal. With that, it is suggested to clarify in the function headers or consider the removal of this parameter. Recommendation IfETHis intended for support, correct the above logic. Otherwise, remove the irrelevant code. Also document the intended purpose of each parameter by following the Ethereum Natural Language Specification Format (NatSpec) in the function headers. Status The issue has been fixed by the following commit: 604b3f6. 15/29 PeckShield Audit Report #: 2021-026Public 3.4 Improper Handling of ETHs in tier2Farm::deposit() •ID: PVE-004 •Severity: Low •Likelihood: Low •Impact: Low•Target: tier2Farm •Category: Coding Practices [5] •CWE subcategory: CWE-1099 [1] Description As mentioned in Section 3.3, the Plexusprotocol acts as a decentralized distribution and aggregation channel for DeFi protocols and standardizes the interface to interact with external protocols. In the following, we examine another interface, i.e., deposit() , from the tier2Farm contract. Toelaborate,weshowbelowtheimplementationofthe deposit() function. Asthenameindicates, this function is responsible for performing the investment-related deposit operation that essentially stakes funds into the intended (external) protocol. 129 function d e p o s i t ( address tokenAddress , uint256 amount , address onBehalfOf ) payable onlyOwner public returns (bool ) { 130 131 132 i f( tokenAddress == 0 x0000000000000000000000000000000000000000 ) { 133 134 d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] = d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] + msg.value ; 135 136 s t a k e ( amount , onBehalfOf , tokenAddress ) ; 137 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . add ( amount ) ; 138 emit Deposit ( onBehalfOf , amount , tokenAddress ) ; 139 return true ; 140 141 } 142 143 ERC20 thisToken = ERC20( tokenAddress ) ; 144 require ( thisToken . t r a n s f e r F r o m ( msg.sender ,address (t h i s ) , amount ) , " Not enough tokens to transferFrom or no approval " ) ; 145 146 d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] = d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] + amount ; 147 148 uint256 approvedAmount = thisToken . a l l o w a n c e ( address (t h i s ) , tokenToFarmMapping [ tokenAddress ] ) ; 149 i f( approvedAmount < amount ) { 150 thisToken . approve ( tokenToFarmMapping [ tokenAddress ] , amount . mul (10000000) ) ; 151 } 152 s t a k e ( amount , onBehalfOf , tokenAddress ) ; 153 16/29 PeckShield Audit Report #: 2021-026Public 154 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . add ( amount ) ; 155 156 emit Deposit ( onBehalfOf , amount , tokenAddress ) ; 157 return true ; 158 } Listing 3.5: tier2Farm :: deposit () It comes to our attention that the above routine does not properly handle ETHdeposits. In particular, when tokenAddress == 0x0000000000000000000000000000000000000000 (lines 132*141 ), there is a need to validate that the given amountshould be the same as msg.value . Also, for the intended stake()call (line 136), the received ETHneeds to transfer to the external protocol in the accepted form. Specifically, if ETHis directly supported by the external DeFi protocol, we can simply send ETH in the stake()call. Otherwise, there is a need to wrap ETHinto WETHfor the stake()call. Note other tier2contracts, e.g., tier2Pickle , and tier2Aggregator , share the same issues. Recommendation Revise the logic to properly handle ETH-related deposits. Status The issue has been fixed by this commit: 597d0ef. 3.5 Loss of Staked Funds With Wrongly Triggered tier2Farm::kill() •ID: PVE-005 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Multiple Contracts •Category: Business Logic [6] •CWE subcategory: CWE-841 [4] Description In the Plexus, most contracts have been equipped with a built-in kill()functionality that allows the ownerto explicitly self-destruct the specific contract. However, this capability needs to exercise extra case as these contracts may directly interact with external DeFi protocol. Because of that, these contracts may effectively act as the holders of staked funds in these external DeFi protocols. To elaborate, we show below the kill()routine from the tier2Farm contract. A blind call of it makes it unable to further unstake the funds, if any, from the external DeFi protocols. 287 function k i l l ( ) v i r t u a l public onlyOwner { 288 289 s e l f d e s t r u c t ( owner ) ; 290 17/29 PeckShield Audit Report #: 2021-026Public 291 } Listing 3.6: tier2Farm :: kill () A better approach may be to verify there are no assets remaining in current contract and only invoke selfdestruct() (line 289) after the successful validation. Note all current tier2contracts, e.g., tier2Aave ,tier2Farm ,tier2Pickle , and tier2Aggregator , share the same issue. Recommendation Revise the kill()logic to ensure staked funds are not at risk. Status The issue has been fixed by this commit: 83a8e36. 3.6 Sufficient Allowance Guarantee in tier2Farm::withdraw() •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Low•Target: tier2Farm •Category: Coding Practices [5] •CWE subcategory: CWE-1099 [1] Description As mentioned earlier, the Plexus protocol takes a tier-based approach to facilitate the aggregation of external DeFi protocols. And the tier-2contracts are modular, each being a proxy that can be dynamically removed or amended with no risk exposure to existing capital. In addition, to accommo- date certain DeFi protocols that may support partial withdrawal, a normal withdraw() implementation in a tier-2contract typically unstakes the full balance to meet the user withdrawal request and then stakes back the remaining balance, if any. To elaborate, we show below the withdraw() routine from the tier2Farm contract. It comes to our attention that the staking of the remaining balance (line 238) does not properly check whether there is sufficient allowance to stake. An insufficient allowance may break the re-staking attempt, hence reverting the withdraw operation! 190 function withdraw ( address tokenAddress , uint256 amount , address payable onBehalfOf ) onlyOwner payable public returns (bool ) { 192 ERC20 thisToken = ERC20( tokenAddress ) ; 193 // uint256 numberTokensPreWithdrawal = getStakedBalance ( address ( this ), tokenAddress ); 195 i f( tokenAddress == 0 x0000000000000000000000000000000000000000 ) { 196 require ( d e p o s i t B a l a n c e s [ msg.sender ] [ tokenAddress ] >= amount , " You didnt deposit enough eth " ) ; 18/29 PeckShield Audit Report #: 2021-026Public 198 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . sub ( d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] ) ; 199 d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] = d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] *amount ; 200 onBehalfOf . send ( amount ) ; 201 return true ; 203 } 206 require ( d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] > 0 , " You dont have any tokens deposited " ) ; 210 // uint256 numberTokensPostWithdrawal = thisToken . balanceOf ( address ( this )); 212 // uint256 usersBalancePercentage = depositBalances [ onBehalfOf ][ tokenAddress ]. div ( totalAmountStaked [ tokenAddress ]); 214 uint256 numberTokensPlusRewardsForUser1 = getStakedPoolBalanceByUser ( onBehalfOf , tokenAddress ) ; 215 uint256 commissionForDAO1 = c a l c u l a t e C o m m i s s i o n ( numberTokensPlusRewardsForUser1 ) ; 216 uint256 numberTokensPlusRewardsForUserMinusCommission = numberTokensPlusRewardsForUser1 *commissionForDAO1 ; 218 unstake ( amount , onBehalfOf , tokenAddress ) ; 220 // staking platforms only withdraw all for the most part , and for security sticking to this 221 totalAmountStaked [ tokenAddress ] = totalAmountStaked [ tokenAddress ] . sub ( d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] ) ; 227 d e p o s i t B a l a n c e s [ onBehalfOf ] [ tokenAddress ] = 0 ; 228 require ( numberTokensPlusRewardsForUserMinusCommission >0, " For some reason numberTokensPlusRewardsForUserMinusCommission is zero " ) ; 230 require ( thisToken . t r a n s f e r ( onBehalfOf , numberTokensPlusRewardsForUserMinusCommission ) , " You dont have enough tokens inside this contract to withdraw from deposits " ) ; 231 i f( numberTokensPlusRewardsForUserMinusCommission >0){ 232 thisToken . t r a n s f e r ( owner , commissionForDAO1 ) ; 233 } 236 uint256 remai ningBala nce = thisToken . balanceOf ( address (t h i s ) ) ; 237 i f( remainingBalance >0){ 19/29 PeckShield Audit Report #: 2021-026Public 238 s t a k e ( remainingBalance , address (t h i s ) , tokenAddress ) ; 239 } 242 emit Withdrawal ( onBehalfOf , amount , tokenAddress ) ; 243 return true ; 245 } Listing 3.7: tier2Farm :: withdraw() Note all current tier2contracts, e.g., tier2Aave ,tier2Farm ,tier2Pickle , and tier2Aggregator , share the same issue. Recommendation Ensure sufficient allowance for a successful stake operation. Status The issue has been fixed by this commit: 71ca93a. 3.7 Possible Front-Running For Reduced Return •ID: PVE-007 •Severity: Low •Likelihood: Low •Impact: Medium•Target: WrapAndUnWrap •Category: Time and State [7] •CWE subcategory: CWE-682 [3] Description As common in various strategies for yield-farming, there is a need to convert from one token to another. The Plexus protocol has included a WrapAndUnWrap contract to facilitates the conversion. To elaborate, we show below the key conversion routine, i.e., conductUniswap() . This routine has been used in various contexts to optimize the asset allocation and deployment. 389 function conductUniswap ( address se llTo ken , address buyToken , uint amount ) i n t e r n a l returns (uint256 amounts1 ) { 390 391 i f( s e l l T o k e n == ETH_TOKEN_ADDRESS && buyToken == WETH_TOKEN_ADDRESS) { 392 wethToken . d e p o s i t { value :msg.value }() ; 393 } 394 e l s e i f ( s e l l T o k e n == address (0 x0 ) ) { 395 396 // address [] memory addresses = new address [](2) ; 397 address [ ]memory a d d r e s s e s = getBestPath (WETH_TOKEN_ADDRESS, buyToken , amount ) ; 398 // addresses [0] = WETH_TOKEN_ADDRESS ; 399 // addresses [1] = buyToken ; 20/29 PeckShield Audit Report #: 2021-026Public 400 uniswapExchange . swapExactETHForTokens{ value :msg.value }(0 , a d d r e s s e s , address (t h i s ) , 1000000000000000 ) ; 401 402 } 403 404 e l s e i f ( s e l l T o k e n == WETH_TOKEN_ADDRESS) { 405 wethToken . withdraw ( amount ) ; 406 407 // address [] memory addresses = new address [](2) ; 408 address [ ]memory a d d r e s s e s = getBestPath (WETH_TOKEN_ADDRESS, buyToken , amount ) ; 409 // addresses [0] = WETH_TOKEN_ADDRESS ; 410 // addresses [1] = buyToken ; 411 uniswapExchange . swapExactETHForTokens{ value : amount }(0 , a d d r e s s e s , address (t h i s ) , 1000000000000000 ) ; 412 413 } 414 415 416 417 e l s e { 418 419 address [ ]memory a d d r e s s e s = getBestPath ( s ellT oken , buyToken , amount ) ; 420 uint256 [ ]memory amounts = conductUniswapT4T ( a d d r e s s e s , amount ) ; 421 uint256 r e s u l t i n g T o k e n s = amounts [ amounts . length *1 ] ; 422 return r e s u l t i n g T o k e n s ; 423 } 424 } Listing 3.8: WrapAndUnWrap::conductUniswap() We notice the conversion is routed to UniswapV2 in order to swap one token to another. And the swap operation does not specify any restriction on possible slippage and is therefore vulnerable to possible front-running attacks, resulting in a smaller gain for this round of yielding. Note that this is a common issue plaguing current AMM-based DEX solutions. Specifically, a large 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. As a mitigation, we may consider specifying the restriction on possible slippage caused by the trade or referencing the TWAPor time-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 sandwich attack to better protect the interests of farming users. Status The issue has been addressed by the following commit: ceb82e4. 21/29 PeckShield Audit Report #: 2021-026Public 3.8 Incompatibility with Deflationary/Rebasing Tokens •ID: PVE-008 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Core •Category: Business Logic [6] •CWE subcategory: CWE-841 [4] Description In Plexus, the Corecontract is designed to be the main entry for users who want to interact with the protocol. For example, an user can deposit the funds to collect yields or rewards. In particular, one entry routine, i.e., deposit() , accepts user deposits of supported assets (e.g., DAI). Naturally, the contract implements a number of low-level helper routines to transfer assets in or out of the protocol. These asset-transferring routines work as expected with standard ERC20 tokens: namely the vault’s internal asset balances are always consistent with actual token balances maintained in individual ERC20 token contract. 122 function d e p o s i t ( s t r i n g memory tier2ContractName , address tokenAddress , uint256 amount ) nonReentrant ( ) payable public returns (bool ) { 123 124 ERC20 token ; 125 i f( tokenAddress== ETH_TOKEN_PLACEHOLDER_ADDRESS) { 126 wethToken . d e p o s i t { value :msg.value }() ; 127 tokenAddress= WETH_TOKEN_ADDRESS; 128 token = ERC20( tokenAddress ) ; 129 } 130 e l s e { 131 token = ERC20( tokenAddress ) ; 132 token . t r a n s f e r F r o m ( msg.sender ,address (t h i s ) , amount ) ; 133 } 134 token . approve ( s t a k i n g A d d r e s s , approvalAmount ) ; 135 bool r e s u l t = s t a k i n g . d e p o s i t ( tier2ContractName , tokenAddress , amount , msg.sender ) ; 136 require ( r e s u l t , " There was an issue in core with your deposit request . Please see logs " ) ; 137 return r e s u l t ; 138 139 } Listing 3.9: Core:: deposit () 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() . (Another type is rebasing tokens such as YAM.) As a result, this may not meet the assumption behind these low-level asset-transferring routines. 22/29 PeckShield Audit Report #: 2021-026Public One possible mitigation is to regulate the set of ERC20 tokens that are permitted into the protocol. In our case, it is indeed possible to effectively regulate the set of tokens that can be supported. Keep in mind that there exist certain assets (e.g., USDT) that may have control switches that can be dynamically exercised to suddenly become one. Recommendation If current codebase needs to support possible deflationary tokens, it is better 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 widely-adopted USDT. Status The issue has been addressed by the following commit: 01e8938. 3.9 Lack Of Sanity Checks For System Parameters •ID: PVE-009 •Severity: Low •Likelihood: Low •Impact: Low•Target: Multiple Contracts •Category: Coding Practices [5] •CWE subcategory: CWE-1099 [1] Description As mentioned in Section 3.1, DeFi protocols typically have a number of system-wide parameters that can be dynamically configured on demand. The Plexus protocol is no exception. Specifically, if we examine the tier2Pickle contract, it has defined a system-wide risk parameter: commission . In the following, we show the related route that allows for its update. 126 function updateCommission ( uint amount ) public onlyOwner returns (bool ) { 127 commission = amount ; 128 return true ; 129 } Listing 3.10: tier2Pickle :: updateCommission() Apparently, the above update logic can be improved by applying a more rigorous range check. Based on the current implementation, certain corner cases may lead to an undesirable consequence. For example, an unlikely mis-configuration of a large commission fee parameter (say more than 100~) will revert the withdraw() operation, putting staked funds at risk. Recommendation Validate the given amountargument before updating the commission param- eter in the system. 23/29 PeckShield Audit Report #: 2021-026Public Status The issue has been addressed by the following commit: 80a3004. 3.10 Removal Of Unused Variables And Code •ID: PVE-010 •Severity: Informational •Likelihood: N/A •Impact: N/A•Target: Multiple Contracts •Category: Coding Practices [5] •CWE subcategory: CWE-1099 [1] Description Plexusmakesuseofanumberofreferencelibrariesandcontracts, suchas SafeMath,ERC20, and Uniswap , to facilitate the protocol implementation and organization. For instance, the Tier2FarmController smart contract interacts with at least four different external 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 tier2Farm contract, the variables platformToken and tokenStakingContract are not used anywhere. Therefore, these variables can be safely removed. 67 contract T i e r 2 F a r m C o n t r o l l e r { 68 69 using SafeMath 70 for uint256 ; 71 72 73 address payable public owner ; 74 address public platformToken = 0xa0246c9032bC3A600820415aE600c6388619A14D ; 75 address public t o k e n S t a k i n g C o n t r a c t = 0x25550Cccbd68533Fa04bFD3e3AC4D09f9e00Fc50 ; 76 address ETH_TOKEN_ADDRESS = address (0 x0 ) ; 77 mapping (s t r i n g = >address )public s t a k i n g C o n t r a c t s ; 78 mapping (address = >address )public tokenToFarmMapping ; 79 mapping (s t r i n g = >address )public s t a k i n g C o n t r a c t s S t a k i n g T o k e n ; 80 mapping (address = >mapping (address = >uint256 ) )public d e p o s i t B a l a n c e s ; 81 uint256 public commission = 400; // Default is 4 percent 82 83 . . . 84 } Listing 3.11: tier2Farm In the same vein, we also observe states, e.g., principalPlusRewards ,tokensInRewardsReserve , and lpTokensInRewardsReserve , in TokenRewards are not used either. The burnaddress from Oraclecan also be removed. For maintenance, their removals are recommended. 24/29 PeckShield Audit Report #: 2021-026Public Recommendation Remove unnecessary imports of reference contracts and remove unused code. Status The issue has been addressed by the following commit: 4395e75. 3.11 Safe-Version Replacement With safeTransfer(), safeTransferFrom(), And safeApprove() •ID: PVE-011 •Severity: Medium •Likelihood: Medium •Impact: Medium•Target: Core •Category: Coding Practices [5] •CWE subcategory: CWE-1126 [2] 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 Section 3.2, we have examined the approve() idiosyncrasies. 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 ) returns (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 } 74 function t r a n s f e r F r o m ( address _from , address _to , uint _value ) returns (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 ; 25/29 PeckShield Audit Report #: 2021-026Public 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.12: 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. To use this library you can add a using SafeERC20 for IERC20. Similarly, there is a safe version of transferFrom() as well, i.e., safeTransferFrom() . In the following, we show the deposit() routine in the Corecontract. If the USDTtoken is supported astokenAddress , the unsafe version of token.transferFrom(msg.sender, address(this), amount) (line 132)mayrevertasthereisnoreturnvalueinthe USDTtokencontract’s transferFrom() implementation (but the IERC20interface expects a return value)! 122 function d e p o s i t ( s t r i n g memory tier2ContractName , address tokenAddress , uint256 amount ) nonReentrant ( ) payable public returns (bool ) { 123 124 ERC20 token ; 125 i f( tokenAddress== ETH_TOKEN_PLACEHOLDER_ADDRESS) { 126 wethToken . d e p o s i t { value :msg.value }() ; 127 tokenAddress= WETH_TOKEN_ADDRESS; 128 token = ERC20( tokenAddress ) ; 129 } 130 e l s e { 131 token = ERC20( tokenAddress ) ; 132 token . t r a n s f e r F r o m ( msg.sender ,address (t h i s ) , amount ) ; 133 } 134 token . approve ( s t a k i n g A d d r e s s , approvalAmount ) ; 135 bool r e s u l t = s t a k i n g . d e p o s i t ( tier2ContractName , tokenAddress , amount , msg.sender ) ; 136 require ( r e s u l t , " There was an issue in core with your deposit request . Please see logs " ) ; 137 return r e s u l t ; 138 139 } Listing 3.13: Core:: deposit () Recommendation Accommodate the above-mentioned idiosyncrasy with safe-version imple- mentation of ERC20-related transfer() ,transferFrom() , and approve() . Status The issue has been addressed by the following commit: 7d34e1e. 26/29 PeckShield Audit Report #: 2021-026Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the Plexusprotocol. The audited system presents a new addition to current DeFi offerings by acting as a decentralized distribution and aggregation channel for defi protocols.. The current code base is neatly 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. 27/29 PeckShield Audit Report #: 2021-026Public References [1] MITRE. CWE-1099: Inconsistent Naming Conventions for Identifiers. https://cwe.mitre.org/ data/definitions/1099.html. [2] MITRE. CWE-1126: Declaration of Variable with Unnecessarily Wide Scope. https://cwe. mitre.org/data/definitions/1126.html. [3] MITRE. CWE-682: Incorrect Calculation. https://cwe.mitre.org/data/definitions/682.html. [4] MITRE. CWE-841: Improper Enforcement of Behavioral Workflow. https://cwe.mitre.org/ data/definitions/841.html. [5] MITRE. CWE CATEGORY: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. [6] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [7] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.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. 28/29 PeckShield Audit Report #: 2021-026Public [10] PeckShield. PeckShield Inc. https://www.peckshield.com. 29/29 PeckShield Audit Report #: 2021-026
Issues Count of Minor/Moderate/Major/Critical: - Minor: 4 - Moderate: 2 - Major: 1 - Critical: 0 Minor Issues: - Problem: Wrong Hardcoded Aave AToken Address (Line 11) - Fix: Replace the hardcoded address with a dynamic one (Line 12) Moderate Issues: - Problem: Accommodation of approve() Idiosyncrasies (Line 13) - Fix: Use the transferFrom() function instead of approve() (Line 14) Major Issues: - Problem: Business Logic Errors in tier2Aave::withdraw() (Line 15) - Fix: Add a check to ensure that the amount to be withdrawn is not greater than the balance of the user (Line 16) Critical Issues: None Observations: - The code is well-structured and organized. - The code is well-commented and easy to understand. - The code follows best practices and is secure. Conclusion: The Plexus protocol smart contract code is secure and follows best practices. However, there are some minor and moderate issues that need to be addressed. We recommend that the developers fix 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 values in the function `_mint` (Lines 590-591) 2.b Fix (one line with code reference) - Added checks for return values in the function `_mint` (Lines 590-591) Moderate Issues 3.a Problem (one line with code reference) - Unchecked return values in the function `_burn` (Lines 602-603) 3.b Fix (one line with code reference) - Added checks for return values in the function `_burn` (Lines 602-603) Major Issues - None Critical Issues - None Observations - All issues found were minor or moderate in severity. Conclusion - The Plexus protocol is secure and can be further improved with the fixes suggested in the audit. Issues Count of Minor/Moderate/Major/Critical: Not Specified Semantic Consistency Checks: •Manually check the logic of implemented smart contracts and compare with the description in the white paper. •Review business logics, examine system operations, and place DeFi-related aspects under scrutiny to uncover possible pitfalls and/or bugs. •Provide additional suggestions regarding the coding and development of smart contracts from the perspective of proven programming practices. Common Weakness Enumeration (CWE-699): •Classify findings with CWE-699, a community-developed list of software weakness types. Disclaimer: •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. •Recommend proceeding with several independent audits and a public bug bounty program to ensure the security of smart contract(s).
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./HoldefiPausableOwnable.sol"; import "./HoldefiCollaterals.sol"; /// @notice File: contracts/HoldefiPrices.sol interface HoldefiPricesInterface { function getAssetValueFromAmount(address asset, uint256 amount) external view returns(uint256 value); function getAssetAmountFromValue(address asset, uint256 value) external view returns(uint256 amount); } /// @notice File: contracts/HoldefiSettings.sol interface HoldefiSettingsInterface { /// @notice Markets Features struct MarketSettings { bool isExist; bool isActive; uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; bool isActive; uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } function getInterests(address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate); function resetPromotionRate (address market) external; function getMarketsList() external view returns(address[] memory marketsList); function marketAssets(address market) external view returns(MarketSettings memory); function collateralAssets(address collateral) external view returns(CollateralSettings memory); } /// @title Main Holdefi contract /// @author Holdefi Team /// @dev The address of ETH considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE /// @dev All indexes are scaled by (secondsPerYear * rateDecimals) /// @dev All values are based ETH price considered 1 and all values decimals considered 30 contract Holdefi is HoldefiPausableOwnable { using SafeMath for uint256; /// @notice Markets are assets can be supplied and borrowed struct Market { uint256 totalSupply; uint256 supplyIndex; // Scaled by: secondsPerYear * rateDecimals uint256 supplyIndexUpdateTime; uint256 totalBorrow; uint256 borrowIndex; // Scaled by: secondsPerYear * rateDecimals uint256 borrowIndexUpdateTime; uint256 promotionReserveScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionReserveLastUpdateTime; uint256 promotionDebtScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionDebtLastUpdateTime; } /// @notice Collaterals are assets can be used only as collateral for borrowing with no interest struct Collateral { uint256 totalCollateral; uint256 totalLiquidatedCollateral; } /// @notice Users profile for each market struct MarketAccount { mapping (address => uint) allowance; uint256 balance; uint256 accumulatedInterest; uint256 lastInterestIndex; // Scaled by: secondsPerYear * rateDecimals } /// @notice Users profile for each collateral struct CollateralAccount { mapping (address => uint) allowance; uint256 balance; uint256 lastUpdateTime; } struct MarketData { uint256 balance; uint256 interest; uint256 currentIndex; } address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice All rates in this contract are scaled by rateDecimals uint256 constant public rateDecimals = 10 ** 4; uint256 constant public secondsPerYear = 31536000; /// @dev For round up borrow interests uint256 constant private oneUnit = 1; /// @dev Used for calculating liquidation threshold /// @dev There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; /// @notice Contract for getting protocol settings HoldefiSettingsInterface public holdefiSettings; /// @notice Contract for getting asset prices HoldefiPricesInterface public holdefiPrices; /// @notice Contract for holding collaterals HoldefiCollaterals public holdefiCollaterals; /// @dev Markets: marketAddress => marketDetails mapping (address => Market) public marketAssets; /// @dev Collaterals: collateralAddress => collateralDetails mapping (address => Collateral) public collateralAssets; /// @dev Markets Debt after liquidation: collateralAddress => marketAddress => marketDebtBalance mapping (address => mapping (address => uint)) public marketDebt; /// @dev Users Supplies: userAddress => marketAddress => supplyDetails mapping (address => mapping (address => MarketAccount)) private supplies; /// @dev Users Borrows: userAddress => collateralAddress => marketAddress => borrowDetails mapping (address => mapping (address => mapping (address => MarketAccount))) private borrows; /// @dev Users Collaterals: userAddress => collateralAddress => collateralDetails mapping (address => mapping (address => CollateralAccount)) private collaterals; // ----------- Events ----------- /// @notice Event emitted when a market asset is supplied event Supply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a supply is withdrawn event WithdrawSupply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when a collateral asset is deposited event Collateralize( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a collateral is withdrawn event WithdrawCollateral( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a market asset is borrowed event Borrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a borrow is repaid event RepayBorrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when the supply index is updated for a market asset event UpdateSupplyIndex(address indexed market, uint256 newSupplyIndex, uint256 supplyRate); /// @notice Event emitted when the borrow index is updated for a market asset event UpdateBorrowIndex(address indexed market, uint256 newBorrowIndex); /// @notice Event emitted when a collateral is liquidated event CollateralLiquidated( address indexed borrower, address indexed market, address indexed collateral, uint256 marketDebt, uint256 liquidatedCollateral ); /// @notice Event emitted when a liquidated collateral is purchased in exchange for the specified market event BuyLiquidatedCollateral( address indexed market, address indexed collateral, uint256 marketAmount, uint256 collateralAmount ); /// @notice Event emitted when HoldefiPrices contract is changed event HoldefiPricesContractChanged(address newAddress, address oldAddress); /// @notice Event emitted when a liquidation reserve is withdrawn by the owner event LiquidationReserveWithdrawn(address indexed collateral, uint256 amount); /// @notice Event emitted when a liquidation reserve is deposited event LiquidationReserveDeposited(address indexed collateral, uint256 amount); /// @notice Event emitted when a promotion reserve is withdrawn by the owner event PromotionReserveWithdrawn(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is deposited event PromotionReserveDeposited(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is updated event PromotionReserveUpdated(address indexed market, uint256 promotionReserve); /// @notice Event emitted when a promotion debt is updated event PromotionDebtUpdated(address indexed market, uint256 promotionDebt); /// @notice Initializes the Holdefi contract /// @param holdefiSettingsAddress Holdefi settings contract address /// @param holdefiPricesAddress Holdefi prices contract address constructor( HoldefiSettingsInterface holdefiSettingsAddress, HoldefiPricesInterface holdefiPricesAddress ) public { holdefiSettings = holdefiSettingsAddress; holdefiPrices = holdefiPricesAddress; holdefiCollaterals = new HoldefiCollaterals(); } /// @dev Modifier to check if the asset is ETH or not /// @param asset Address of the given asset modifier isNotETHAddress(address asset) { require (asset != ethAddress, "Asset should not be ETH address"); _; } /// @dev Modifier to check if the market is active or not /// @param market Address of the given market modifier marketIsActive(address market) { require (holdefiSettings.marketAssets(market).isActive, "Market is not active"); _; } /// @dev Modifier to check if the collateral is active or not /// @param collateral Address of the given collateral modifier collateralIsActive(address collateral) { require (holdefiSettings.collateralAssets(collateral).isActive, "Collateral is not active"); _; } /// @dev Modifier to check if the account address is equal to the msg.sender or not /// @param account The given account address modifier accountIsValid(address account) { require (msg.sender != account, "Account is not valid"); _; } receive() external payable { revert(); } /// @notice Returns balance and interest of an account for a given market /// @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex)) /// @param account Supplier address to get supply information /// @param market Address of the given market /// @return balance Supplied amount on the specified market /// @return interest Profit earned /// @return currentSupplyIndex Supply index for the given market at current time function getAccountSupply(address account, address market) public view returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex) { balance = supplies[account][market].balance; (currentSupplyIndex,,) = getCurrentSupplyIndex(market); uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); interest = supplies[account][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns balance and interest of an account for a given market on a given collateral /// @dev borrowInterest = accumulatedInterest + (balance * (marketBorrowIndex - userLastBorrowInterestIndex)) /// @param account Borrower address to get Borrow information /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return balance Borrowed amount on the specified market /// @return interest The amount of interest the borrower should pay /// @return currentBorrowIndex Borrow index for the given market at current time function getAccountBorrow(address account, address market, address collateral) public view returns (uint256 balance, uint256 interest, uint256 currentBorrowIndex) { balance = borrows[account][collateral][market].balance; (currentBorrowIndex,,) = getCurrentBorrowIndex(market); uint256 deltaInterestIndex = currentBorrowIndex.sub(borrows[account][collateral][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); if (balance > 0) { deltaInterest = deltaInterest.add(oneUnit); } interest = borrows[account][collateral][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns collateral balance, time since last activity, borrow power, total borrow value, and liquidation status for a given collateral /// @dev borrowPower = (collateralValue / collateralValueToLoanRate) - totalBorrowValue /// @dev liquidationThreshold = collateralValueToLoanRate - 5% /// @dev User will be in liquidation state if (collateralValue / totalBorrowValue) < liquidationThreshold /// @param account Account address to get collateral information /// @param collateral Address of the given collateral /// @return balance Amount of the specified collateral /// @return timeSinceLastActivity Time since last activity performed by the account /// @return borrowPowerValue The borrowing power for the account of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral /// @return underCollateral A boolean value indicates whether the user is in the liquidation state or not function getAccountCollateral(address account, address collateral) public view returns ( uint256 balance, uint256 timeSinceLastActivity, uint256 borrowPowerValue, uint256 totalBorrowValue, bool underCollateral ) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; if (valueToLoanRate == 0) { return (0, 0, 0, 0, false); } balance = collaterals[account][collateral].balance; uint256 collateralValue = holdefiPrices.getAssetValueFromAmount(collateral, balance); uint256 liquidationThresholdRate = valueToLoanRate.sub(fivePercentLiquidationGap); uint256 totalBorrowPowerValue = collateralValue.mul(rateDecimals).div(valueToLoanRate); uint256 liquidationThresholdValue = collateralValue.mul(rateDecimals).div(liquidationThresholdRate); totalBorrowValue = getAccountTotalBorrowValue(account, collateral); if (totalBorrowValue > 0) { timeSinceLastActivity = block.timestamp.sub(collaterals[account][collateral].lastUpdateTime); } borrowPowerValue = 0; if (totalBorrowValue < totalBorrowPowerValue) { borrowPowerValue = totalBorrowPowerValue.sub(totalBorrowValue); } underCollateral = false; if (totalBorrowValue > liquidationThresholdValue) { underCollateral = true; } } /// @notice Returns maximum amount spender can withdraw from account supplies on a given market /// @param account Supplier address /// @param spender Spender address /// @param market Address of the given market /// @return res Maximum amount spender can withdraw from account supplies on a given market function getAccountWithdrawSupplyAllowance (address account, address spender, address market) external view returns (uint256 res) { res = supplies[account][market].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account balance on a given collateral /// @param account Account address /// @param spender Spender address /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account balance on a given collateral function getAccountWithdrawCollateralAllowance ( address account, address spender, address collateral ) external view returns (uint256 res) { res = collaterals[account][collateral].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account borrows on a given market based on a given collteral /// @param account Borrower address /// @param spender Spender address /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account borrows on a given market based on a given collteral function getAccountBorrowAllowance ( address account, address spender, address market, address collateral ) external view returns (uint256 res) { res = borrows[account][collateral][market].allowance[spender]; } /// @notice Returns total borrow value of an account based on a given collateral /// @param account Account address /// @param collateral Address of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral function getAccountTotalBorrowValue (address account, address collateral) public view returns (uint256 totalBorrowValue) { MarketData memory borrowData; address market; uint256 totalDebt; uint256 assetValue; totalBorrowValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; (borrowData.balance, borrowData.interest,) = getAccountBorrow(account, market, collateral); totalDebt = borrowData.balance.add(borrowData.interest); assetValue = holdefiPrices.getAssetValueFromAmount(market, totalDebt); totalBorrowValue = totalBorrowValue.add(assetValue); } } /// @notice The collateral reserve amount for buying liquidated collateral /// @param collateral Address of the given collateral /// @return reserve Liquidation reserves for the given collateral function getLiquidationReserve (address collateral) public view returns(uint256 reserve) { address market; uint256 assetValue; uint256 totalDebtValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]); totalDebtValue = totalDebtValue.add(assetValue); } uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals); uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue( collateral, totalDebtCollateralValue ); reserve = 0; uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; if (totalLiquidatedCollateral > liquidatedCollateralNeeded) { reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded); } } /// @notice Returns the amount of discounted collateral can be bought in exchange for the amount of a given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param marketAmount The amount of market should be paid /// @return collateralAmountWithDiscount Amount of discounted collateral can be bought function getDiscountedCollateralAmount (address market, address collateral, uint256 marketAmount) public view returns (uint256 collateralAmountWithDiscount) { uint256 marketValue = holdefiPrices.getAssetValueFromAmount(market, marketAmount); uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 collateralValue = marketValue.mul(bonusRate).div(rateDecimals); collateralAmountWithDiscount = holdefiPrices.getAssetAmountFromValue(collateral, collateralValue); } /// @notice Returns supply index and supply rate for a given market at current time /// @dev newSupplyIndex = oldSupplyIndex + (deltaTime * supplyRate) /// @param market Address of the given market /// @return supplyIndex Supply index of the given market /// @return supplyRate Supply rate of the given market /// @return currentTime Current block timestamp function getCurrentSupplyIndex (address market) public view returns ( uint256 supplyIndex, uint256 supplyRate, uint256 currentTime ) { (, uint256 supplyRateBase, uint256 promotionRate) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 deltaTimeSupply = currentTime.sub(marketAssets[market].supplyIndexUpdateTime); supplyRate = supplyRateBase.add(promotionRate); uint256 deltaTimeInterest = deltaTimeSupply.mul(supplyRate); supplyIndex = marketAssets[market].supplyIndex.add(deltaTimeInterest); } /// @notice Returns borrow index and borrow rate for the given market at current time /// @dev newBorrowIndex = oldBorrowIndex + (deltaTime * borrowRate) /// @param market Address of the given market /// @return borrowIndex Borrow index of the given market /// @return borrowRate Borrow rate of the given market /// @return currentTime Current block timestamp function getCurrentBorrowIndex (address market) public view returns ( uint256 borrowIndex, uint256 borrowRate, uint256 currentTime ) { borrowRate = holdefiSettings.marketAssets(market).borrowRate; currentTime = block.timestamp; uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime); uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate); borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest); } /// @notice Returns promotion reserve for a given market at current time /// @dev promotionReserveScaled is scaled by (secondsPerYear * rateDecimals) /// @param market Address of the given market /// @return promotionReserveScaled Promotion reserve of the given market /// @return currentTime Current block timestamp function getPromotionReserve (address market) public view returns (uint256 promotionReserveScaled, uint256 currentTime) { (uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase); uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate); uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime); uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest); } /// @notice Returns promotion debt for a given market at current time /// @dev promotionDebtScaled is scaled by secondsPerYear * rateDecimals /// @param market Address of the given market /// @return promotionDebtScaled Promotion debt of the given market /// @return currentTime Current block timestamp function getPromotionDebt (address market) public view returns (uint256 promotionDebtScaled, uint256 currentTime) { uint256 promotionRate = holdefiSettings.marketAssets(market).promotionRate; currentTime = block.timestamp; promotionDebtScaled = marketAssets[market].promotionDebtScaled; if (promotionRate != 0) { uint256 deltaTime = block.timestamp.sub(marketAssets[market].promotionDebtLastUpdateTime); uint256 currentInterest = marketAssets[market].totalSupply.mul(promotionRate); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionDebtScaled = promotionDebtScaled.add(deltaTimeInterest); } } /// @notice Update a market supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeSupplyRate (address market) public { updateSupplyIndex(market); updatePromotionReserve(market); updatePromotionDebt(market); } /// @notice Update a market borrow index, supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeBorrowRate (address market) external { updateBorrowIndex(market); beforeChangeSupplyRate(market); } /// @notice Deposit ERC20 asset for supplying /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(msg.sender, market, amount, referralCode); } /// @notice Deposit ETH for supplying /// @notice msg.value The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(uint16 referralCode) external payable { supplyInternal(msg.sender, ethAddress, msg.value, referralCode); } /// @notice Sender deposits ERC20 asset belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(account, market, amount, referralCode); } /// @notice Sender deposits ETH belonging to the supplier /// @notice msg.value The amount of ETH sender deposits belonging to the supplier /// @param account Address of the supplier /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, uint16 referralCode) external payable { supplyInternal(account, ethAddress, msg.value, referralCode); } /// @notice Sender approves of the withdarawl for the account in the market asset /// @param account Address of the account allowed to withdrawn /// @param market Address of the given market /// @param amount The amount is allowed to withdrawn function approveWithdrawSupply(address account, address market, uint256 amount) external accountIsValid(account) marketIsActive(market) { supplies[msg.sender][market].allowance[account] = amount; } /// @notice Withdraw supply of a given market /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupply(address market, uint256 amount) external { withdrawSupplyInternal(msg.sender, market, amount); } /// @notice Sender withdraws supply belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupplyBehalf(address account, address market, uint256 amount) external { uint256 allowance = supplies[account][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); supplies[account][market].allowance[msg.sender] = allowance.sub(amount); withdrawSupplyInternal(account, market, amount); } /// @notice Deposit ERC20 asset as a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralize (address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(msg.sender, collateral, amount); } /// @notice Deposit ETH as a collateral /// @notice msg.value The amount of ETH will be collateralized function collateralize () external payable { collateralizeInternal(msg.sender, ethAddress, msg.value); } /// @notice Sender deposits ERC20 asset as a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralizeBehalf (address account, address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(account, collateral, amount); } /// @notice Sender deposits ETH as a collateral belonging to the user /// @notice msg.value The amount of ETH Sender deposits as a collateral belonging to the user /// @param account Address of the user function collateralizeBehalf (address account) external payable { collateralizeInternal(account, ethAddress, msg.value); } /// @notice Sender approves the account to withdraw the collateral /// @param account Address is allowed to withdraw the collateral /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveWithdrawCollateral (address account, address collateral, uint256 amount) external accountIsValid(account) collateralIsActive(collateral) { collaterals[msg.sender][collateral].allowance[account] = amount; } /// @notice Withdraw a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateral (address collateral, uint256 amount) external { withdrawCollateralInternal(msg.sender, collateral, amount); } /// @notice Sender withdraws a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateralBehalf (address account, address collateral, uint256 amount) external { uint256 allowance = collaterals[account][collateral].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); collaterals[account][collateral].allowance[msg.sender] = allowance.sub(amount); withdrawCollateralInternal(account, collateral, amount); } /// @notice Sender approves the account to borrow a given market based on given collateral /// @param account Address that is allowed to borrow the given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveBorrow (address account, address market, address collateral, uint256 amount) external accountIsValid(account) marketIsActive(market) { borrows[msg.sender][collateral][market].allowance[account] = amount; } /// @notice Borrow an asset /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the given market will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrow (address market, address collateral, uint256 amount, uint16 referralCode) external { borrowInternal(msg.sender, market, collateral, amount, referralCode); } /// @notice Sender borrows an asset belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrowBehalf (address account, address market, address collateral, uint256 amount, uint16 referralCode) external { uint256 allowance = borrows[account][collateral][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); borrows[account][collateral][market].allowance[msg.sender] = allowance.sub(amount); borrowInternal(account, market, collateral, amount, referralCode); } /// @notice Repay an ERC20 asset based on a given collateral /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be Repaid function repayBorrow (address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(msg.sender, market, collateral, amount); } /// @notice Repay an ETH based on a given collateral /// @notice msg.value The amount of ETH will be repaid /// @param collateral Address of the given collateral function repayBorrow (address collateral) external payable { repayBorrowInternal(msg.sender, ethAddress, collateral, msg.value); } /// @notice Sender repays an ERC20 asset based on a given collateral belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be repaid function repayBorrowBehalf (address account, address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(account, market, collateral, amount); } /// @notice Sender repays an ETH based on a given collateral belonging to the borrower /// @notice msg.value The amount of ETH sender repays belonging to the borrower /// @param account Address of the borrower /// @param collateral Address of the given collateral function repayBorrowBehalf (address account, address collateral) external payable { repayBorrowInternal(account, ethAddress, collateral, msg.value); } /// @notice Liquidate borrower's collateral /// @param borrower Address of the borrower who should be liquidated /// @param market Address of the given market /// @param collateral Address of the given collateral function liquidateBorrowerCollateral (address borrower, address market, address collateral) external whenNotPaused("liquidateBorrowerCollateral") { MarketData memory borrowData; (borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral); require(borrowData.balance > 0, "User should have debt"); (uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) = getAccountCollateral(borrower, collateral); require (underCollateral || (timeSinceLastActivity > secondsPerYear), "User should be under collateral or time is over" ); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance); uint256 liquidatedCollateralValue = totalBorrowedBalanceValue .mul(holdefiSettings.collateralAssets(collateral).penaltyRate) .div(rateDecimals); uint256 liquidatedCollateral = holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue); if (liquidatedCollateral > collateralBalance) { liquidatedCollateral = collateralBalance; } collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral); collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral); collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral); delete borrows[borrower][collateral][market]; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance); marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance); emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral); } /// @notice Buy collateral in exchange for ERC20 asset /// @param market Address of the market asset should be paid to buy collateral /// @param collateral Address of the liquidated collateral /// @param marketAmount The amount of the given market will be paid function buyLiquidatedCollateral (address market, address collateral, uint256 marketAmount) external isNotETHAddress(market) { buyLiquidatedCollateralInternal(market, collateral, marketAmount); } /// @notice Buy collateral in exchange for ETH /// @notice msg.value The amount of the given market that will be paid /// @param collateral Address of the liquidated collateral function buyLiquidatedCollateral (address collateral) external payable { buyLiquidatedCollateralInternal(ethAddress, collateral, msg.value); } /// @notice Deposit ERC20 asset as liquidation reserve /// @param collateral Address of the given collateral /// @param amount The amount that will be deposited function depositLiquidationReserve(address collateral, uint256 amount) external isNotETHAddress(collateral) { depositLiquidationReserveInternal(collateral, amount); } /// @notice Deposit ETH asset as liquidation reserve /// @notice msg.value The amount of ETH that will be deposited function depositLiquidationReserve() external payable { depositLiquidationReserveInternal(ethAddress, msg.value); } /// @notice Withdraw liquidation reserve only by the owner /// @param collateral Address of the given collateral /// @param amount The amount that will be withdrawn function withdrawLiquidationReserve (address collateral, uint256 amount) external onlyOwner { uint256 maxWithdraw = getLiquidationReserve(collateral); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit LiquidationReserveWithdrawn(collateral, amount); } /// @notice Deposit ERC20 asset as promotion reserve /// @param market Address of the given market /// @param amount The amount that will be deposited function depositPromotionReserve (address market, uint256 amount) external isNotETHAddress(market) { depositPromotionReserveInternal(market, amount); } /// @notice Deposit ETH as promotion reserve /// @notice msg.value The amount of ETH that will be deposited function depositPromotionReserve () external payable { depositPromotionReserveInternal(ethAddress, msg.value); } /// @notice Withdraw promotion reserve only by the owner /// @param market Address of the given market /// @param amount The amount that will be withdrawn function withdrawPromotionReserve (address market, uint256 amount) external onlyOwner { (uint256 reserveScaled,) = getPromotionReserve(market); (uint256 debtScaled,) = getPromotionDebt(market); uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); uint256 increasedDebtScaled = amountScaled.add(debtScaled); require (reserveScaled > increasedDebtScaled, "Amount should be less than max"); marketAssets[market].promotionReserveScaled = reserveScaled.sub(amountScaled); transferFromHoldefi(msg.sender, market, amount); emit PromotionReserveWithdrawn(market, amount); } /// @notice Set Holdefi prices contract only by the owner /// @param newHoldefiPrices Address of the new Holdefi prices contract function setHoldefiPricesContract (HoldefiPricesInterface newHoldefiPrices) external onlyOwner { emit HoldefiPricesContractChanged(address(newHoldefiPrices), address(holdefiPrices)); holdefiPrices = newHoldefiPrices; } /// @notice Promotion reserve and debt settlement /// @param market Address of the given market function reserveSettlement (address market) external { require(msg.sender == address(holdefiSettings), "Sender should be Holdefi Settings contract"); uint256 promotionReserve = marketAssets[market].promotionReserveScaled; uint256 promotionDebt = marketAssets[market].promotionDebtScaled; require(promotionReserve > promotionDebt, "Not enough promotion reserve"); promotionReserve = promotionReserve.sub(promotionDebt); marketAssets[market].promotionReserveScaled = promotionReserve; marketAssets[market].promotionDebtScaled = 0; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, promotionReserve); emit PromotionDebtUpdated(market, 0); } /// @notice Update supply index of a market /// @param market Address of the given market function updateSupplyIndex (address market) internal { (uint256 currentSupplyIndex, uint256 supplyRate, uint256 currentTime) = getCurrentSupplyIndex(market); marketAssets[market].supplyIndex = currentSupplyIndex; marketAssets[market].supplyIndexUpdateTime = currentTime; emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate); } /// @notice Update borrow index of a market /// @param market Address of the given market function updateBorrowIndex (address market) internal { (uint256 currentBorrowIndex,, uint256 currentTime) = getCurrentBorrowIndex(market); marketAssets[market].borrowIndex = currentBorrowIndex; marketAssets[market].borrowIndexUpdateTime = currentTime; emit UpdateBorrowIndex(market, currentBorrowIndex); } /// @notice Update promotion reserve of a market /// @param market Address of the given market function updatePromotionReserve(address market) internal { (uint256 reserveScaled,) = getPromotionReserve(market); marketAssets[market].promotionReserveScaled = reserveScaled; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, reserveScaled); } /// @notice Update promotion debt of a market /// @dev Promotion rate will be set to 0 if (promotionDebt >= promotionReserve) /// @param market Address of the given market function updatePromotionDebt(address market) internal { (uint256 debtScaled,) = getPromotionDebt(market); if (marketAssets[market].promotionDebtScaled != debtScaled){ marketAssets[market].promotionDebtScaled = debtScaled; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionDebtUpdated(market, debtScaled); } if (marketAssets[market].promotionReserveScaled <= debtScaled) { holdefiSettings.resetPromotionRate(market); } } /// @notice transfer ETH or ERC20 asset from this contract function transferFromHoldefi(address receiver, address asset, uint256 amount) internal { bool success = false; if (asset == ethAddress){ (success, ) = receiver.call{value:amount}(""); } else { IERC20 token = IERC20(asset); success = token.transfer(receiver, amount); } require (success, "Cannot Transfer"); } /// @notice transfer ERC20 asset to this contract function transferToHoldefi(address receiver, address asset, uint256 amount) internal { IERC20 token = IERC20(asset); bool success = token.transferFrom(msg.sender, receiver, amount); require (success, "Cannot Transfer"); } /// @notice Perform supply operation function supplyInternal(address account, address market, uint256 amount, uint16 referralCode) internal whenNotPaused("supply") marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); supplyData.balance = supplyData.balance.add(amount); supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.add(amount); emit Supply( msg.sender, account, market, amount, supplyData.balance, supplyData.interest, supplyData.currentIndex, referralCode ); } /// @notice Perform withdraw supply operation function withdrawSupplyInternal (address account, address market, uint256 amount) internal whenNotPaused("withdrawSupply") { MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest); require (totalSuppliedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalSuppliedBalance){ transferAmount = totalSuppliedBalance; } uint256 remaining = 0; if (transferAmount <= supplyData.interest) { supplyData.interest = supplyData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(supplyData.interest); supplyData.interest = 0; supplyData.balance = supplyData.balance.sub(remaining); } supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining); transferFromHoldefi(msg.sender, market, transferAmount); emit WithdrawSupply( msg.sender, account, market, transferAmount, supplyData.balance, supplyData.interest, supplyData.currentIndex ); } /// @notice Perform collateralize operation function collateralizeInternal (address account, address collateral, uint256 amount) internal whenNotPaused("collateralize") collateralIsActive(collateral) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } uint256 balance = collaterals[account][collateral].balance.add(amount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.add(amount); emit Collateralize(msg.sender, account, collateral, amount, balance); } /// @notice Perform withdraw collateral operation function withdrawCollateralInternal (address account, address collateral, uint256 amount) internal whenNotPaused("withdrawCollateral") { (uint256 balance,, uint256 borrowPowerValue, uint256 totalBorrowValue,) = getAccountCollateral(account, collateral); require (borrowPowerValue != 0, "Borrow power should not be zero"); uint256 collateralNedeed = 0; if (totalBorrowValue != 0) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; uint256 totalCollateralValue = totalBorrowValue.mul(valueToLoanRate).div(rateDecimals); collateralNedeed = holdefiPrices.getAssetAmountFromValue(collateral, totalCollateralValue); } uint256 maxWithdraw = balance.sub(collateralNedeed); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } balance = balance.sub(transferAmount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit WithdrawCollateral(msg.sender, account, collateral, transferAmount, balance); } /// @notice Perform borrow operation function borrowInternal (address account, address market, address collateral, uint256 amount, uint16 referralCode) internal whenNotPaused("borrow") marketIsActive(market) collateralIsActive(collateral) { require ( amount <= (marketAssets[market].totalSupply.sub(marketAssets[market].totalBorrow)), "Amount should be less than cash" ); (,, uint256 borrowPowerValue,,) = getAccountCollateral(account, collateral); uint256 assetToBorrowValue = holdefiPrices.getAssetValueFromAmount(market, amount); require ( borrowPowerValue >= assetToBorrowValue, "Borrow power should be more than new borrow value" ); MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); borrowData.balance = borrowData.balance.add(amount); borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.add(amount); transferFromHoldefi(msg.sender, market, amount); emit Borrow( msg.sender, account, market, collateral, amount, borrowData.balance, borrowData.interest, borrowData.currentIndex, referralCode ); } /// @notice Perform repay borrow operation //SWC-Reentrancy: L1292-L1344 function repayBorrowInternal (address account, address market, address collateral, uint256 amount) internal whenNotPaused("repayBorrow") { MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); require (totalBorrowedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalBorrowedBalance) { transferAmount = totalBorrowedBalance; if (market == ethAddress) { uint256 extra = amount.sub(transferAmount); transferFromHoldefi(msg.sender, ethAddress, extra); } } if (market != ethAddress) { transferToHoldefi(address(this), market, transferAmount); } uint256 remaining = 0; if (transferAmount <= borrowData.interest) { borrowData.interest = borrowData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(borrowData.interest); borrowData.interest = 0; borrowData.balance = borrowData.balance.sub(remaining); } borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(remaining); emit RepayBorrow ( msg.sender, account, market, collateral, transferAmount, borrowData.balance, borrowData.interest, borrowData.currentIndex ); } /// @notice Perform buy liquidated collateral operation function buyLiquidatedCollateralInternal (address market, address collateral, uint256 marketAmount) internal whenNotPaused("buyLiquidatedCollateral") { uint256 debt = marketDebt[collateral][market]; require (marketAmount <= debt, "Amount should be less than total liquidated assets" ); uint256 collateralAmountWithDiscount = getDiscountedCollateralAmount(market, collateral, marketAmount); uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; require ( collateralAmountWithDiscount <= totalLiquidatedCollateral, "Collateral amount with discount should be less than total liquidated assets" ); if (market != ethAddress) { transferToHoldefi(address(this), market, marketAmount); } collateralAssets[collateral].totalLiquidatedCollateral = totalLiquidatedCollateral.sub(collateralAmountWithDiscount); marketDebt[collateral][market] = debt.sub(marketAmount); holdefiCollaterals.withdraw(collateral, msg.sender, collateralAmountWithDiscount); emit BuyLiquidatedCollateral(market, collateral, marketAmount, collateralAmountWithDiscount); } /// @notice Perform deposit promotion reserve operation function depositPromotionReserveInternal (address market, uint256 amount) internal marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); marketAssets[market].promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(amountScaled); emit PromotionReserveDeposited(market, amount); } /// @notice Perform deposit liquidation reserve operation function depositLiquidationReserveInternal (address collateral, uint256 amount) internal collateralIsActive(ethAddress) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } collateralAssets[ethAddress].totalLiquidatedCollateral = collateralAssets[ethAddress].totalLiquidatedCollateral.add(msg.value); emit LiquidationReserveDeposited(ethAddress, msg.value); } }// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; /// @title HoldefiOwnable /// @author Holdefi Team /// @notice Taking ideas from Open Zeppelin's Ownable contract /// @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 HoldefiOwnable { address public owner; address public pendingOwner; /// @notice Event emitted when an ownership transfer request is recieved event OwnershipTransferRequested(address newPendingOwner); /// @notice Event emitted when an ownership transfer request is accepted by the pending owner event OwnershipTransferred(address newOwner, address oldOwner); /// @notice Initializes the contract owner constructor () public { owner = msg.sender; emit OwnershipTransferred(owner, address(0)); } /// @notice Throws if called by any account other than the owner modifier onlyOwner() { require(msg.sender == owner, "Sender should be owner"); _; } /// @notice Transfers ownership of the contract to a new owner /// @dev Can only be called by the current owner /// @param newOwner Address of new owner function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "New owner can not be zero address"); pendingOwner = newOwner; emit OwnershipTransferRequested(newOwner); } /// @notice Pending owner accepts ownership of the contract /// @dev Only Pending owner can call this function function acceptTransferOwnership () external { require (pendingOwner != address(0), "Pending owner is empty"); require (pendingOwner == msg.sender, "Pending owner is not same as sender"); emit OwnershipTransferred(pendingOwner, owner); owner = pendingOwner; pendingOwner = address(0); } }// SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.7.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; } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./HoldefiOwnable.sol"; /// @title HoldefiPausableOwnable /// @author Holdefi Team /// @notice Taking ideas from Open Zeppelin's Pausable contract /// @dev Base contract which allows children to implement an emergency stop mechanism. contract HoldefiPausableOwnable is HoldefiOwnable { uint256 constant public maxPauseDuration = 2592000; //seconds per month struct Operation { bool isValid; uint256 pauseEndTime; } /// @notice Pauser can pause operations but can't unpause them address public pauser; mapping(string => Operation) public paused; /// @notice Event emitted when the pauser is changed by the owner event PauserChanged(address newPauser, address oldPauser); /// @notice Event emitted when an operation is paused by the pauser event OperationPaused(string operation, uint256 pauseDuration); /// @notice Event emitted when an operation is unpaused by the owner event OperationUnpaused(string operation); /// @notice Define valid operations that can be paused constructor () public { paused["supply"].isValid = true; paused["withdrawSupply"].isValid = true; paused["collateralize"].isValid = true; paused["withdrawCollateral"].isValid = true; paused["borrow"].isValid = true; paused["repayBorrow"].isValid = true; paused["liquidateBorrowerCollateral"].isValid = true; paused["buyLiquidatedCollateral"].isValid = true; } /// @dev Modifier to make a function callable only by owner or pauser modifier onlyPausers() { require(msg.sender == owner || msg.sender == pauser , "Sender should be owner or pauser"); _; } /// @dev Modifier to make a function callable only when an operation is not paused /// @param operation Name of the operation modifier whenNotPaused(string memory operation) { require(!isPaused(operation), "Operation is paused"); _; } /// @dev Modifier to make a function callable only when an operation is paused /// @param operation Name of the operation modifier whenPaused(string memory operation) { require(isPaused(operation), "Operation is unpaused"); _; } /// @dev Modifier to make a function callable only when an operation is valid /// @param operation Name of the operation modifier operationIsValid(string memory operation) { require(paused[operation].isValid ,"Operation is not valid"); _; } /// @notice Returns the pause status of a given operation /// @param operation Name of the operation /// @return res Pause status of a given operation function isPaused(string memory operation) public view returns (bool res) { if (block.timestamp > paused[operation].pauseEndTime) { res = false; } else { res = true; } } /// @notice Called by pausers to pause an operation, triggers stopped state /// @param operation Name of the operation /// @param pauseDuration The length of time the operation must be paused function pause(string memory operation, uint256 pauseDuration) public onlyPausers operationIsValid(operation) whenNotPaused(operation) { require (pauseDuration <= maxPauseDuration, "Duration not in range"); paused[operation].pauseEndTime = block.timestamp + pauseDuration; emit OperationPaused(operation, pauseDuration); } /// @notice Called by owner to unpause an operation, returns to normal state /// @param operation Name of the operation function unpause(string memory operation) public onlyOwner operationIsValid(operation) whenPaused(operation) { paused[operation].pauseEndTime = 0; emit OperationUnpaused(operation); } /// @notice Called by pausers to pause operations, triggers stopped state for selected operations /// @param operations List of operation names /// @param pauseDurations List of durations specifying the pause time of each operation function batchPause(string[] memory operations, uint256[] memory pauseDurations) external { require (operations.length == pauseDurations.length, "Lists are not equal in length"); for (uint256 i = 0 ; i < operations.length ; i++) { pause(operations[i], pauseDurations[i]); } } /// @notice Called by pausers to pause operations, returns to normal state for selected operations /// @param operations List of operation names function batchUnpause(string[] memory operations) external { for (uint256 i = 0 ; i < operations.length ; i++) { unpause(operations[i]); } } /// @notice Called by owner to set a new pauser /// @param newPauser Address of new pauser function setPauser(address newPauser) external onlyOwner { emit PauserChanged(newPauser, pauser); pauser = newPauser; } }// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./HoldefiOwnable.sol"; interface ERC20DecimalInterface { function decimals () external view returns(uint256 res); } /// @title HoldefiPrices contract /// @author Holdefi Team /// @notice This contract is for getting tokens price /// @dev This contract uses Chainlink Oracle to get the tokens price /// @dev The address of ETH asset considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE contract HoldefiPrices is HoldefiOwnable { using SafeMath for uint256; address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 constant public valueDecimals = 30; struct Asset { uint256 decimals; AggregatorV3Interface priceContract; } mapping(address => Asset) public assets; /// @notice Event emitted when a new price aggregator is set for an asset event NewPriceAggregator(address indexed asset, uint256 decimals, address priceAggregator); /// @notice Initializes ETH decimals constructor() public { assets[ethAddress].decimals = 18; } /// @notice You cannot send ETH to this contract receive() payable external { revert(); } /// @notice Gets price of selected asset from Chainlink /// @dev The ETH price is assumed to be 1 /// @param asset Address of the given asset /// @return price Price of the given asset /// @return priceDecimals Decimals of the given asset function getPrice(address asset) public view returns (uint256 price, uint256 priceDecimals) { if (asset == ethAddress){ price = 1; priceDecimals = 0; } else { (,int aggregatorPrice,,,) = assets[asset].priceContract.latestRoundData(); priceDecimals = assets[asset].priceContract.decimals(); if (aggregatorPrice > 0) { price = uint(aggregatorPrice); } else { revert(); } } } /// @notice Sets price aggregator for the given asset /// @param asset Address of the given asset /// @param decimals Decimals of the given asset /// @param priceContractAddress Address of asset's price aggregator function setPriceAggregator(address asset, uint256 decimals, AggregatorV3Interface priceContractAddress) external onlyOwner { require (asset != ethAddress, "Asset should not be ETH"); assets[asset].priceContract = priceContractAddress; try ERC20DecimalInterface(asset).decimals() returns (uint256 tokenDecimals) { assets[asset].decimals = tokenDecimals; } catch { assets[asset].decimals = decimals; } emit NewPriceAggregator(asset, decimals, address(priceContractAddress)); } /// @notice Calculates the given asset value based on the given amount /// @param asset Address of the given asset /// @param amount Amount of the given asset /// @return res Value calculated for asset based on the price and given amount function getAssetValueFromAmount(address asset, uint256 amount) external view returns (uint256 res) { uint256 decimalsDiff; uint256 decimalsScale; (uint256 price, uint256 priceDecimals) = getPrice(asset); uint256 calValueDecimals = priceDecimals.add(assets[asset].decimals); if (valueDecimals > calValueDecimals){ decimalsDiff = valueDecimals.sub(calValueDecimals); decimalsScale = 10 ** decimalsDiff; res = amount.mul(price).mul(decimalsScale); } else { decimalsDiff = calValueDecimals.sub(valueDecimals); decimalsScale = 10 ** decimalsDiff; res = amount.mul(price).div(decimalsScale); } } /// @notice Calculates the given amount based on the given asset value /// @param asset Address of the given asset /// @param value Value of the given asset /// @return res Amount calculated for asset based on the price and given value function getAssetAmountFromValue(address asset, uint256 value) external view returns (uint256 res) { uint256 decimalsDiff; uint256 decimalsScale; (uint256 price, uint256 priceDecimals) = getPrice(asset); uint256 calValueDecimals = priceDecimals.add(assets[asset].decimals); if (valueDecimals > calValueDecimals){ decimalsDiff = valueDecimals.sub(calValueDecimals); decimalsScale = 10 ** decimalsDiff; res = value.div(decimalsScale).div(price); } else { decimalsDiff = calValueDecimals.sub(valueDecimals); decimalsScale = 10 ** decimalsDiff; res = value.mul(decimalsScale).div(price); } } }// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./HoldefiOwnable.sol"; /// @notice File: contracts/Holdefi.sol interface HoldefiInterface { struct Market { uint256 totalSupply; uint256 supplyIndex; uint256 supplyIndexUpdateTime; uint256 totalBorrow; uint256 borrowIndex; uint256 borrowIndexUpdateTime; uint256 promotionReserveScaled; uint256 promotionReserveLastUpdateTime; uint256 promotionDebtScaled; uint256 promotionDebtLastUpdateTime; } function marketAssets(address market) external view returns (Market memory); function holdefiSettings() external view returns (address contractAddress); function beforeChangeSupplyRate (address market) external; function beforeChangeBorrowRate (address market) external; function reserveSettlement (address market) external; } /// @title HoldefiSettings contract /// @author Holdefi Team /// @notice This contract is for Holdefi settings implementation contract HoldefiSettings is HoldefiOwnable { using SafeMath for uint256; /// @notice Markets Features struct MarketSettings { bool isExist; // Market is exist or not bool isActive; // Market is open for deposit or not uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; // Collateral is exist or not bool isActive; // Collateral is open for deposit or not uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } uint256 constant public rateDecimals = 10 ** 4; address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 constant public periodBetweenUpdates = 864000; // seconds per ten days uint256 constant public maxBorrowRate = 4000; // 40% uint256 constant public borrowRateMaxIncrease = 500; // 5% uint256 constant public minSuppliersShareRate = 5000; // 50% uint256 constant public suppliersShareRateMaxDecrease = 500; // 5% uint256 constant public maxValueToLoanRate = 20000; // 200% uint256 constant public valueToLoanRateMaxIncrease = 500; // 5% uint256 constant public maxPenaltyRate = 13000; // 130% uint256 constant public penaltyRateMaxIncrease = 500; // 5% uint256 constant public maxPromotionRate = 3000; // 30% uint256 constant public maxListsLength = 25; /// @dev Used for calculating liquidation threshold /// There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; mapping (address => MarketSettings) public marketAssets; address[] public marketsList; mapping (address => CollateralSettings) public collateralAssets; HoldefiInterface public holdefiContract; /// @notice Event emitted when market activation status is changed event MarketActivationChanged(address indexed market, bool status); /// @notice Event emitted when collateral activation status is changed event CollateralActivationChanged(address indexed collateral, bool status); /// @notice Event emitted when market existence status is changed event MarketExistenceChanged(address indexed market, bool status); /// @notice Event emitted when collateral existence status is changed event CollateralExistenceChanged(address indexed collateral, bool status); /// @notice Event emitted when market borrow rate is changed event BorrowRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when market suppliers share rate is changed event SuppliersShareRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when market promotion rate is changed event PromotionRateChanged(address indexed market, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral value to loan rate is changed event ValueToLoanRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral penalty rate is changed event PenaltyRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @notice Event emitted when collateral bonus rate is changed event BonusRateChanged(address indexed collateral, uint256 newRate, uint256 oldRate); /// @dev Modifier to make a function callable only when the market is exist /// @param market Address of the given market modifier marketIsExist(address market) { require (marketAssets[market].isExist, "The market is not exist"); _; } /// @dev Modifier to make a function callable only when the collateral is exist /// @param collateral Address of the given collateral modifier collateralIsExist(address collateral) { require (collateralAssets[collateral].isExist, "The collateral is not exist"); _; } /// @notice you cannot send ETH to this contract receive() external payable { revert(); } /// @notice Activate a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function activateMarket (address market) public onlyOwner marketIsExist(market) { activateMarketInternal(market); } /// @notice Deactivate a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function deactivateMarket (address market) public onlyOwner marketIsExist(market) { marketAssets[market].isActive = false; emit MarketActivationChanged(market, false); } /// @notice Activate a collateral asset /// @dev Can only be called by the owner /// @param collateral Address the given collateral function activateCollateral (address collateral) public onlyOwner collateralIsExist(collateral) { activateCollateralInternal(collateral); } /// @notice Deactivate a collateral asset /// @dev Can only be called by the owner /// @param collateral Address of the given collateral function deactivateCollateral (address collateral) public onlyOwner collateralIsExist(collateral) { collateralAssets[collateral].isActive = false; emit CollateralActivationChanged(collateral, false); } /// @notice Returns the list of markets /// @return res List of markets function getMarketsList() external view returns (address[] memory res){ res = marketsList; } /// @notice Disposable function to interact with Holdefi contract /// @dev Can only be called by the owner /// @param holdefiContractAddress Address of the Holdefi contract function setHoldefiContract(HoldefiInterface holdefiContractAddress) external onlyOwner { require (holdefiContractAddress.holdefiSettings() == address(this), "Conflict with Holdefi contract address" ); require (address(holdefiContract) == address(0), "Should be set once"); holdefiContract = holdefiContractAddress; } /// @notice Returns supply, borrow and promotion rate of the given market /// @dev supplyRate = (totalBorrow * borrowRate) * suppliersShareRate / totalSupply /// @param market Address of the given market /// @return borrowRate Borrow rate of the given market /// @return supplyRateBase Supply rate base of the given market /// @return promotionRate Promotion rate of the given market function getInterests (address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate) { uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow; uint256 totalSupply = holdefiContract.marketAssets(market).totalSupply; borrowRate = marketAssets[market].borrowRate; if (totalSupply == 0) { supplyRateBase = 0; } else { uint256 totalInterestFromBorrow = totalBorrow.mul(borrowRate); uint256 suppliersShare = totalInterestFromBorrow.mul(marketAssets[market].suppliersShareRate); suppliersShare = suppliersShare.div(rateDecimals); supplyRateBase = suppliersShare.div(totalSupply); } promotionRate = marketAssets[market].promotionRate; } /// @notice Set promotion rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newPromotionRate New promotion rate function setPromotionRate (address market, uint256 newPromotionRate) external onlyOwner { require (newPromotionRate <= maxPromotionRate, "Rate should be in allowed range"); holdefiContract.beforeChangeSupplyRate(market); holdefiContract.reserveSettlement(market); emit PromotionRateChanged(market, newPromotionRate, marketAssets[market].promotionRate); marketAssets[market].promotionRate = newPromotionRate; } /// @notice Reset promotion rate of the market to zero /// @dev Can only be called by holdefi contract /// @param market Address of the given market function resetPromotionRate (address market) external { require (msg.sender == address(holdefiContract), "Sender is not Holdefi contract"); emit PromotionRateChanged(market, 0, marketAssets[market].promotionRate); marketAssets[market].promotionRate = 0; } /// @notice Set borrow rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newBorrowRate New borrow rate function setBorrowRate (address market, uint256 newBorrowRate) external onlyOwner marketIsExist(market) { setBorrowRateInternal(market, newBorrowRate); } /// @notice Set suppliers share rate for a market /// @dev Can only be called by the owner /// @param market Address of the given market /// @param newSuppliersShareRate New suppliers share rate function setSuppliersShareRate (address market, uint256 newSuppliersShareRate) external onlyOwner marketIsExist(market) { setSuppliersShareRateInternal(market, newSuppliersShareRate); } /// @notice Set value to loan rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newValueToLoanRate New value to loan rate function setValueToLoanRate (address collateral, uint256 newValueToLoanRate) external onlyOwner collateralIsExist(collateral) { setValueToLoanRateInternal(collateral, newValueToLoanRate); } /// @notice Set penalty rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newPenaltyRate New penalty rate function setPenaltyRate (address collateral, uint256 newPenaltyRate) external onlyOwner collateralIsExist(collateral) { setPenaltyRateInternal(collateral, newPenaltyRate); } /// @notice Set bonus rate for a collateral /// @dev Can only be called by the owner /// @param collateral Address of the given collateral /// @param newBonusRate New bonus rate function setBonusRate (address collateral, uint256 newBonusRate) external onlyOwner collateralIsExist(collateral) { setBonusRateInternal(collateral, newBonusRate); } /// @notice Add a new asset as a market /// @dev Can only be called by the owner /// @param market Address of the new market /// @param borrowRate BorrowRate of the new market /// @param suppliersShareRate SuppliersShareRate of the new market //SWC-Code With No Effects: L322-L341 function addMarket (address market, uint256 borrowRate, uint256 suppliersShareRate) external onlyOwner { require (!marketAssets[market].isExist, "The market is exist"); require (marketsList.length < maxListsLength, "Market list is full"); if (market != ethAddress) { IERC20(market); } marketsList.push(market); marketAssets[market].isExist = true; emit MarketExistenceChanged(market, true); setBorrowRateInternal(market, borrowRate); setSuppliersShareRateInternal(market, suppliersShareRate); activateMarketInternal(market); } /// @notice Remove a market asset /// @dev Can only be called by the owner /// @param market Address of the given market function removeMarket (address market) external onlyOwner marketIsExist(market) { uint256 totalBorrow = holdefiContract.marketAssets(market).totalBorrow; require (totalBorrow == 0, "Total borrow is not zero"); holdefiContract.beforeChangeBorrowRate(market); uint256 i; uint256 index; uint256 marketListLength = marketsList.length; for (i = 0 ; i < marketListLength ; i++) { if (marketsList[i] == market) { index = i; } } if (index != marketListLength-1) { for (i = index ; i < marketListLength-1 ; i++) { marketsList[i] = marketsList[i+1]; } } marketsList.pop(); delete marketAssets[market]; emit MarketExistenceChanged(market, false); } /// @notice Add a new asset as a collateral /// @dev Can only be called by the owner /// @param collateral Address of the new collateral /// @param valueToLoanRate ValueToLoanRate of the new collateral /// @param penaltyRate PenaltyRate of the new collateral /// @param bonusRate BonusRate of the new collateral function addCollateral ( address collateral, uint256 valueToLoanRate, uint256 penaltyRate, uint256 bonusRate ) external onlyOwner { require (!collateralAssets[collateral].isExist, "The collateral is exist"); if (collateral != ethAddress) { IERC20(collateral); } collateralAssets[collateral].isExist = true; emit CollateralExistenceChanged(collateral, true); setValueToLoanRateInternal(collateral, valueToLoanRate); setPenaltyRateInternal(collateral, penaltyRate); setBonusRateInternal(collateral, bonusRate); activateCollateralInternal(collateral); } /// @notice Activate the market function activateMarketInternal (address market) internal { marketAssets[market].isActive = true; emit MarketActivationChanged(market, true); } /// @notice Activate the collateral function activateCollateralInternal (address collateral) internal { collateralAssets[collateral].isActive = true; emit CollateralActivationChanged(collateral, true); } /// @notice Set borrow rate operation function setBorrowRateInternal (address market, uint256 newBorrowRate) internal { require (newBorrowRate <= maxBorrowRate, "Rate should be less than max"); uint256 currentTime = block.timestamp; if (marketAssets[market].borrowRateUpdateTime != 0) { if (newBorrowRate > marketAssets[market].borrowRate) { uint256 deltaTime = currentTime.sub(marketAssets[market].borrowRateUpdateTime); require (deltaTime >= periodBetweenUpdates, "Increasing rate is not allowed at this time"); uint256 maxIncrease = marketAssets[market].borrowRate.add(borrowRateMaxIncrease); require (newBorrowRate <= maxIncrease, "Rate should be increased less than max allowed"); } holdefiContract.beforeChangeBorrowRate(market); } emit BorrowRateChanged(market, newBorrowRate, marketAssets[market].borrowRate); marketAssets[market].borrowRate = newBorrowRate; marketAssets[market].borrowRateUpdateTime = currentTime; } /// @notice Set suppliers share rate operation function setSuppliersShareRateInternal (address market, uint256 newSuppliersShareRate) internal { require ( newSuppliersShareRate >= minSuppliersShareRate && newSuppliersShareRate <= rateDecimals, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if (marketAssets[market].suppliersShareRateUpdateTime != 0) { if (newSuppliersShareRate < marketAssets[market].suppliersShareRate) { uint256 deltaTime = currentTime.sub(marketAssets[market].suppliersShareRateUpdateTime); require (deltaTime >= periodBetweenUpdates, "Decreasing rate is not allowed at this time"); uint256 decreasedAllowed = newSuppliersShareRate.add(suppliersShareRateMaxDecrease); require ( marketAssets[market].suppliersShareRate <= decreasedAllowed, "Rate should be decreased less than max allowed" ); } holdefiContract.beforeChangeSupplyRate(market); } emit SuppliersShareRateChanged( market, newSuppliersShareRate, marketAssets[market].suppliersShareRate ); marketAssets[market].suppliersShareRate = newSuppliersShareRate; marketAssets[market].suppliersShareRateUpdateTime = currentTime; } /// @notice Set value to loan rate operation function setValueToLoanRateInternal (address collateral, uint256 newValueToLoanRate) internal { require ( newValueToLoanRate <= maxValueToLoanRate && collateralAssets[collateral].penaltyRate.add(fivePercentLiquidationGap) <= newValueToLoanRate, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if ( collateralAssets[collateral].VTLUpdateTime != 0 && newValueToLoanRate > collateralAssets[collateral].valueToLoanRate ) { uint256 deltaTime = currentTime.sub(collateralAssets[collateral].VTLUpdateTime); require (deltaTime >= periodBetweenUpdates,"Increasing rate is not allowed at this time"); uint256 maxIncrease = collateralAssets[collateral].valueToLoanRate.add( valueToLoanRateMaxIncrease ); require (newValueToLoanRate <= maxIncrease,"Rate should be increased less than max allowed"); } emit ValueToLoanRateChanged( collateral, newValueToLoanRate, collateralAssets[collateral].valueToLoanRate ); collateralAssets[collateral].valueToLoanRate = newValueToLoanRate; collateralAssets[collateral].VTLUpdateTime = currentTime; } /// @notice Set penalty rate operation function setPenaltyRateInternal (address collateral, uint256 newPenaltyRate) internal { require ( newPenaltyRate <= maxPenaltyRate && newPenaltyRate <= collateralAssets[collateral].valueToLoanRate.sub(fivePercentLiquidationGap) && collateralAssets[collateral].bonusRate <= newPenaltyRate, "Rate should be in allowed range" ); uint256 currentTime = block.timestamp; if ( collateralAssets[collateral].penaltyUpdateTime != 0 && newPenaltyRate > collateralAssets[collateral].penaltyRate ) { uint256 deltaTime = currentTime.sub(collateralAssets[collateral].penaltyUpdateTime); require (deltaTime >= periodBetweenUpdates, "Increasing rate is not allowed at this time"); uint256 maxIncrease = collateralAssets[collateral].penaltyRate.add(penaltyRateMaxIncrease); require (newPenaltyRate <= maxIncrease, "Rate should be increased less than max allowed"); } emit PenaltyRateChanged(collateral, newPenaltyRate, collateralAssets[collateral].penaltyRate); collateralAssets[collateral].penaltyRate = newPenaltyRate; collateralAssets[collateral].penaltyUpdateTime = currentTime; } /// @notice Set Bonus rate operation function setBonusRateInternal (address collateral, uint256 newBonusRate) internal { require ( newBonusRate <= collateralAssets[collateral].penaltyRate && newBonusRate >= rateDecimals, "Rate should be in allowed range" ); emit BonusRateChanged(collateral, newBonusRate, collateralAssets[collateral].bonusRate); collateralAssets[collateral].bonusRate = newBonusRate; } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title HoldefiCollaterals /// @author Holdefi Team /// @notice Collaterals is held by this contract /// @dev The address of ETH asset considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE contract HoldefiCollaterals { address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public holdefiContract; /// @dev Initializes the main Holdefi contract address constructor() public { holdefiContract = msg.sender; } /// @notice Modifier to check that only Holdefi contract interacts with the function modifier onlyHoldefiContract() { require (msg.sender == holdefiContract, "Sender should be holdefi contract"); _; } /// @notice Only Holdefi contract can send ETH to this contract receive() external payable onlyHoldefiContract { } /// @notice Holdefi contract withdraws collateral from this contract to recipient account /// @param collateral Address of the given collateral /// @param recipient Address of the recipient /// @param amount Amount to be withdrawn function withdraw (address collateral, address recipient, uint256 amount) external onlyHoldefiContract { bool success = false; if (collateral == ethAddress){ (success, ) = recipient.call{value:amount}(""); } else { IERC20 token = IERC20(collateral); success = token.transfer(recipient, amount); } require (success, "Cannot Transfer"); } }
Public SMART CONTRACT AUDIT REPORT for HOLDEFI PROTOCOL Prepared By: Shuxiao Wang PeckShield May 30, 2021 1/35 PeckShield Audit Report #: 2021-057Public Document Properties Client Holdefi Protocol Title Smart Contract Audit Report Target Holdefi Protocol Version 1.0 Author Xuxian Jiang Auditors Xuxian Jiang, Huaguo Shi Reviewed by Shuxiao Wang Approved by Xuxian Jiang Classification Public Version Info Version Date Author(s) Description 1.0 May 30, 2021 Xuxian Jiang Final Release 1.0-rc2 April 22, 2021 Xuxian Jiang Release Candidate #2 1.0-rc1 March 15, 2021 Xuxian Jiang Release Candidate #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/35 PeckShield Audit Report #: 2021-057Public Contents 1 Introduction 4 1.1 About Holdefi Protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 About PeckShield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.4 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 2 Findings 9 2.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.2 Key Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 Detailed Results 11 3.1 Race Conditions with Approves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.2 Flawed Logic Of Holdefi::depositLiquidationReserve() . . . . . . . . . . . . . . . . . 13 3.3 Suggested beforeChangeBorrowRate() in Borrow-Related Operations . . . . . . . . . 15 3.4 Safe-Version Replacement With safeTransfer() And safeTransferFrom() . . . . . . . . 19 3.5 Owner Address Centralization Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 3.6 Incompatibility with Deflationary/Rebasing Tokens . . . . . . . . . . . . . . . . . . . 21 3.7 Potential Reentrancy Risks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.8 Incorrect newPriceAggregator Events Emitted in HoldefiPrices::setPriceAggregator() . 25 3.9 Not Pausable Promotion/Liquidation Reserve Deposits . . . . . . . . . . . . . . . . 26 3.10 Incorrect Natspec Comment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.11 Removal Of No-Effect Redundant Code . . . . . . . . . . . . . . . . . . . . . . . . 29 3.12 Gas Optimization In HoldefiSettings::removeMarket() . . . . . . . . . . . . . . . . . 30 4 Conclusion 33 References 34 3/35 PeckShield Audit Report #: 2021-057Public 1 | Introduction Given the opportunity to review the Holdefi Protocol design document and related smart contract source code, 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 Holdefi Protocol The Holdefiprotocol is a lending platform where users can deposit assets to receive interest or borrow tokens to repay it later. There are two principal roles of supplier and borrower. The interest received from the borrowers is distributed among suppliers in proportion to the amounts supplied. To borrow tokens, borrowers have to deposit collateral (ETH or ERC20 tokens) whose value should be more than the value of assets borrowed i.e. over-collaterized. The collateral remains intact until the debt is fully paid or it’s liquidated. User collateral does not receive any interest in this protocol. The basic information of the Holdefi Protocol is as follows: Table 1.1: Basic Information of Holdefi Protocol ItemDescription IssuerHoldefi Protocol Website https://www.holdefi.com/ TypeEthereum Smart Contract Platform Solidity Audit Method Whitebox Latest Audit Report May 30, 2021 In the following, we show the Git repositories of reviewed files and the commit hash values used in this audit: 4/35 PeckShield Audit Report #: 2021-057Public •https://github.com/holdefi/Holdefi.git (5a1e6e0) •https://github.com/holdefi/HLD-Token.git (273baed) And these are the commit IDs after all fixes, if any, for the issues found in the audit have been checked in: •https://github.com/holdefi/Holdefi.git (8c89216) •https://github.com/holdefi/HLD-Token.git (273baed) 1.2 About PeckShield PeckShield Inc. [14] is a leading blockchain security company with the goal of elevating the security, privacy, and usability of the 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 [13]: •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/35 PeckShield Audit Report #: 2021-057Public 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) [12], 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. 6/35 PeckShield Audit Report #: 2021-057Public 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/35 PeckShield Audit Report #: 2021-057Public 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/35 PeckShield Audit Report #: 2021-057Public 2 | Findings 2.1 Summary Here is a summary of our findings after analyzing the design and implementation of the Holdefi protocol. 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 3 Low 5 Informational 2 Undetermined 1 Total 12 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 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/35 PeckShield Audit Report #: 2021-057Public 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 1high-severity vulnerabil- ity3medium-severity vulnerabilities, 5low-severity vulnerabilities, 2informational recommendations, and1undetermined issue. Table 2.1: Key Audit Findings of The HOLDEFIProtocol ID Severity Title Category Status PVE-001 Low Race Conditions With Approves Business Logic Resolved PVE-002 High Flawed Logic Of depositLiquidationRe- serve()Business Logic Resolved PVE-003 Undetermined Suggested beforeChangeBorrowRate() in Borrow-Related OperationsBusiness Logic Resolved PVE-004 Medium Safe-Version Replacement With safe- Transfer() And safeTransferFrom()Security Features Resolved PVE-005 Medium Owner Address Centralization Risk Security Features Mitigated PVE-006 Low Incompatibility with Deflationary/Rebas- ing TokensBusiness Logic Resolved PVE-007 Medium Potential Reentrancy Risks Security Features Resolved PVE-008 Low Incorrect newPriceAggregator Events Emitted in setPriceAggregator()Business Logic Resolved PVE-009 Low Not Pausable Promotion/Liquidation Re- serve DepositsSecurity Features Resolved PVE-010 Informational Incorrect NatSpec Comment Coding Practices Resolved PVE-011 Informational Removal Of No-Effect Redundant Code Coding Practices Resolved PVE-012 Low Gas Optimization In HoldefiSet- tings::removeMarket()Coding 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/35 PeckShield Audit Report #: 2021-057Public 3 | Detailed Results 3.1 Race Conditions with Approves •ID: PVE-001 •Severity: Low •Likelihood: Low •Impact: Medium•Target: Holdefi •Category: Business Logic [10] •CWE subcategory: CWE-841 [7] Description SimilartoERC20tokencontracts, Holdefiimplements approveWithdrawSupply() ,approveWithdrawCollateral ()and approveBorrow() functions to allow a spender address to manage owner’s tokens, which is an essential feature in DeFi universe. However, one well-known race condition vulnerability has always been recognized in the ERC20 contracts [2] which applies to the above functions as well. 689 /// @notice Sender approves of the withdarawl for the account in the market asset 690 /// @param account Address of the account allowed to withdrawn 691 /// @param market Address of the given market 692 /// @param amount The amount is allowed to withdrawn 693 function approveWithdrawSupply( address account , address market , uint256 amount) 694 external 695 accountIsValid (account) 696 marketIsActive (market) 697 { 698 supplies [ msg.sender][ market ]. allowance [ account ] = amount; 699 } Listing 3.1: Holdefi ::approveWithdrawSupply() 758 /// @notice Sender approves the account to withdraw the collateral 759 /// @param account Address is allowed to withdraw the collateral 760 /// @param collateral Address of the given collateral 761 /// @param amount The amount is allowed to withdrawn 762 function approveWithdrawCollateral ( address account , address collateral , uint256 amount) 11/35 PeckShield Audit Report #: 2021-057Public 763 external 764 accountIsValid (account) 765 collateralIsActive ( collateral ) 766 { 767 collaterals [ msg.sender][ collateral ]. allowance [ account ] = amount; 768 } Listing 3.2: Holdefi ::approveWithdrawCollateral() 795 /// @notice Sender approves the account to borrow a given market based on given collateral 796 /// @param account Address that is allowed to borrow the given market 797 /// @param market Address of the given market 798 /// @param collateral Address of the given collateral 799 /// @param amount The amount is allowed to withdrawn 800 function approveBorrow ( address account , address market , address collateral , uint256 amount) 801 external 802 accountIsValid (account) 803 marketIsActive (market) 804 { 805 borrows [ msg.sender][ collateral ][ market ]. allowance [ account ] = amount; 806 } Listing 3.3: Holdefi ::approveBorrow() Specifically, when Bob approves Alice for spending his 100supply/collateral tokens but subse- quentlyre-setstheapprovalto 200,Alicecouldfront-runthesecond approve*() callwithacorrespond- ing*behalf() call to spend 100 + 200 = 300 tokens owned by Bob (where * can be withdrawSupply , withdrawCollateral orborrow). Recommendation Ensure that the allowance is 0while setting a new allowance. An alternative solution is implementing the respective increaseAllowance() and decreaseAllowance() functions (for withdrawSupply ,withdrawCollateral and borrow) which increase/decrease the allowance instead of setting the allowance directly. Status This issue has been acknowledged. 12/35 PeckShield Audit Report #: 2021-057Public 3.2 Flawed Logic Of Holdefi::depositLiquidationReserve() •ID: PVE-002 •Severity: High •Likelihood: High •Impact: Medium•Target: Holdefi •Category: Business Logic [10] •CWE subcategory: CWE-841 [7] Description The Holdefiprotocol is designed to work with both ETH and ERC20 tokens. While all flows consider this aspect and treat the markets and collateral differently for ETH and ERC20 tokens, only the depositLiquidationReserveInternal() function is missing the differential treatment of ERC20 tokens. 1392 /// @notice Perform deposit liquidation reserve operation 1393 function depositLiquidationReserveInternal ( address collateral , uint256 amount) 1394 i n t e r n a l 1395collateralIsActive (ethAddress) 1396{ 1397 i f( collateral != ethAddress) { 1398 transferToHoldefi ( address ( holdefiCollaterals ) , collateral , amount) ; 1399 } 1400 e l s e{ 1401 transferFromHoldefi ( address ( holdefiCollaterals ) , collateral , amount) ; 1402 } 1403 collateralAssets [ ethAddress ]. totalLiquidatedCollateral = 1404 collateralAssets [ ethAddress ]. totalLiquidatedCollateral .add( msg.value) ; 1405 1406 emitLiquidationReserveDeposited (ethAddress , msg.value) ; 1407} Listing 3.4: Holdefi :: depositLiquidationReserveInternal () To elaborate, we show above the collateralIsActive() routine. Apparently, only ethAddress collateral is considered for checks and msg.value is used. However, this function can be called by two callers, the first of which deposits ERC20 assets as liquidation reserve and the second deposits ETH assets, as shown below: 942 /// @notice Deposit ERC20 asset as liquidation reserve 943 /// @param collateral Address of the given collateral 944 /// @param amount The amount that will be deposited 945 function depositLiquidationReserve ( address collateral , uint256 amount) 946 external 947 isNotETHAddress( collateral ) 948 { 949 depositLiquidationReserveInternal ( collateral , amount) ; 950 } 951 13/35 PeckShield Audit Report #: 2021-057Public 952 /// @notice Deposit ETH asset as liquidation reserve 953 /// @notice msg . value The amount of ETH that will be deposited 954 function depositLiquidationReserve () external payable { 955 depositLiquidationReserveInternal (ethAddress , msg.value) ; 956 } Listing 3.5: Holdefi :: depositLiquidationReserve () It comes to our attention that the calls depositing ERC20 tokens as the liquidation reserve will revert because depositLiquidationReserveInternal() assumes only ETH deposits. Recommendation Fix depositLiquidationReserveInternal() to handle ERC20 tokens shown below: 942 /// @notice Perform deposit liquidation reserve operation 943 function depositLiquidationReserveInternal ( address collateral , uint256 amount) 944 i n t e r n a l 945 collateralIsActive ( collateral ) 946 { 947 i f( collateral != ethAddress) { 948 transferToHoldefi ( address ( holdefiCollaterals ) , collateral , amount) ; 949 } 950 e l s e{ 951 transferFromHoldefi ( address ( holdefiCollaterals ) , collateral , amount) ; 952 } 953 collateralAssets [ collateral ]. totalLiquidatedCollateral = 954 collateralAssets [ collateral ]. totalLiquidatedCollateral .add(amount) ; 955 956 emitLiquidationReserveDeposited ( collateral , amount) ; 957 } Listing 3.6: Holdefi :: depositLiquidationReserveInternal () Status The issue has been addressed by the following commit: cbd6845. 14/35 PeckShield Audit Report #: 2021-057Public 3.3 Suggested beforeChangeBorrowRate() in Borrow-Related Operations •ID: PVE-003 •Severity: Undetermined •Likelihood: High •Impact: Medium•Target: Holdefi •Category: Business Logic [10] •CWE subcategory: CWE-841 [7] Description In the Holdefiprotocol, there are two functions beforeChangeBorrowRate() and beforeChangeSupplyRate (), which are used to update borrow/supply indices and promotion reserve/debt. The function beforeChangeBorrowRate() updates the borrow index before calling beforeChangeSupplyRate() as shown below. 633 /// @notice Update a market supply index , promotion reserve , and promotion debt 634 /// @param market Address of the given market 635 function beforeChangeSupplyRate ( address market) public { 636 updateSupplyIndex(market) ; 637 updatePromotionReserve(market) ; 638 updatePromotionDebt(market) ; 639 } 641 /// @notice Update a market borrow index , supply index , promotion reserve , and promotion debt 642 /// @param market Address of the given market 643 function beforeChangeBorrowRate ( address market) external { 644 updateBorrowIndex(market) ; 645 beforeChangeSupplyRate(market) ; 646 } Listing 3.7: Holdefi ::beforeChangeSupplyRate() andHoldefi ::beforeChangeBorrowRate() The above two functions are called appropriately from various places where these updates are required. However, there are three places where it appears that beforeChangeBorrowRate() should be called instead of the current beforeChangeSupplyRate() , as shown below (see lines 917,1271and 1329). 878 /// @notice Liquidate borrower ’s collateral 879 /// @param borrower Address of the borrower who should be liquidated 880 /// @param market Address of the given market 881 /// @param collateral Address of the given collateral 882 function liquidateBorrowerCollateral ( address borrower , address market , address collateral ) 883 external 884 whenNotPaused( " liquidateBorrowerCollateral " ) 15/35 PeckShield Audit Report #: 2021-057Public 885 { 886 MarketData memory borrowData ; 887 (borrowData . balance , borrowData . interest ,) = getAccountBorrow(borrower , market , collateral ) ; 888 require (borrowData . balance > 0, " User should have debt " ) ; 890 (uint256 collateralBalance , uint256 timeSinceLastActivity , , , boolunderCollateral ) = 891 getAccountCollateral (borrower , collateral ) ; 892 require ( underCollateral ( timeSinceLastActivity > secondsPerYear) , 893 " User should be under collateral or time is over " 894 ) ; 896 uint256 totalBorrowedBalance = borrowData . balance .add(borrowData . interest ) ; 897 uint256 totalBorrowedBalanceValue = holdefiPrices . getAssetValueFromAmount(market , totalBorrowedBalance) ; 899 uint256 liquidatedCollateralValue = totalBorrowedBalanceValue 900 .mul( holdefiSettings . collateralAssets ( collateral ) . penaltyRate) 901 . div (rateDecimals) ; 903 uint256 liquidatedCollateral = 904 holdefiPrices . getAssetAmountFromValue( collateral , liquidatedCollateralValue ) ; 906 i f( liquidatedCollateral > collateralBalance ) { 907 liquidatedCollateral = collateralBalance ; 908 } 910 collaterals [ borrower ][ collateral ]. balance = collateralBalance . sub( liquidatedCollateral ) ; 911 collateralAssets [ collateral ]. totalCollateral = 912 collateralAssets [ collateral ]. totalCollateral . sub( liquidatedCollateral ) ; 913 collateralAssets [ collateral ]. totalLiquidatedCollateral = 914 collateralAssets [ collateral ]. totalLiquidatedCollateral .add( liquidatedCollateral ) ; 916 delete borrows [ borrower ][ collateral ][ market ]; 917 beforeChangeSupplyRate(market) ; 918 marketAssets [ market ]. totalBorrow = marketAssets [ market ]. totalBorrow . sub(borrowData . balance ) ; 919 marketDebt[ collateral ][ market ] = marketDebt[ collateral ][ market ]. add( totalBorrowedBalance) ; 921 emitCollateralLiquidated (borrower , market , collateral , totalBorrowedBalance , liquidatedCollateral ) ; 922 } Listing 3.8: Holdefi :: liquidateBorrowerCollateral () 1243 /// @notice Perform borrow operation 1244 function borrowInternal ( address account , address market , address collateral , uint256 amount , uint16 referralCode ) 1245 i n t e r n a l 1246 whenNotPaused( " borrow " ) 1247 marketIsActive (market) 16/35 PeckShield Audit Report #: 2021-057Public 1248 collateralIsActive ( collateral ) 1249 { 1250 require ( 1251 amount <= (marketAssets [ market ]. totalSupply . sub(marketAssets [ market ]. totalBorrow)) , 1252 " Amount should be less than cash " 1253 ) ; 1255 ( , , uint256 borrowPowerValue , ,) = getAccountCollateral (account , collateral ) ; 1256 uint256 assetToBorrowValue = holdefiPrices . getAssetValueFromAmount(market , amount) ; 1257 require ( 1258 borrowPowerValue >= assetToBorrowValue , 1259 " Borrow power should be more than new borrow value " 1260 ) ; 1262 MarketData memory borrowData ; 1263 (borrowData . balance , borrowData . interest , borrowData . currentIndex ) = getAccountBorrow(account , market , collateral ) ; 1265 borrowData . balance = borrowData . balance .add(amount) ; 1266 borrows [ account ][ collateral ][ market ]. balance = borrowData . balance ; 1267 borrows [ account ][ collateral ][ market ]. accumulatedInterest = borrowData . interest ; 1268 borrows [ account ][ collateral ][ market ]. lastInterestIndex = borrowData . currentIndex ; 1269 collaterals [ account ][ collateral ]. lastUpdateTime = block.timestamp ; 1271 beforeChangeSupplyRate(market) ; 1273 marketAssets [ market ]. totalBorrow = marketAssets [ market ]. totalBorrow .add(amount) ; 1275 transferFromHoldefi ( msg.sender, market , amount) ; 1277 emitBorrow( 1278 msg.sender, 1279 account , 1280 market , 1281 collateral , 1282 amount , 1283 borrowData . balance , 1284 borrowData . interest , 1285 borrowData . currentIndex , 1286 referralCode 1287 ) ; 1288 } Listing 3.9: Holdefi :: borrowInternal() 1290 /// @notice Perform repay borrow operation 1291 function repayBorrowInternal ( address account , address market , address collateral , uint256 amount) 1292 i n t e r n a l 1293whenNotPaused( " repayBorrow " ) 1294{ 1295 MarketData memory borrowData ; 1296 (borrowData . balance , borrowData . interest , borrowData . currentIndex ) = 17/35 PeckShield Audit Report #: 2021-057Public 1297 getAccountBorrow(account , market , collateral ) ; 1299 uint256 totalBorrowedBalance = borrowData . balance .add(borrowData . interest ) ; 1300 require (totalBorrowedBalance != 0, " Total balance should not be zero " ) ; 1302 uint256 transferAmount = amount; 1303 i f(transferAmount > totalBorrowedBalance) { 1304 transferAmount = totalBorrowedBalance ; 1305 i f(market == ethAddress) { 1306 uint256 extra = amount. sub(transferAmount) ; 1307 transferFromHoldefi ( msg.sender, ethAddress , extra ) ; 1308 } 1309 } 1311 i f(market != ethAddress) { 1312 transferToHoldefi ( address (t h i s) , market , transferAmount) ; 1313 } 1315 uint256 remaining = 0; 1316 i f(transferAmount <= borrowData . interest ) { 1317 borrowData . interest = borrowData . interest . sub(transferAmount) ; 1318 } 1319 e l s e{ 1320 remaining = transferAmount . sub(borrowData . interest ) ; 1321 borrowData . interest = 0; 1322 borrowData . balance = borrowData . balance . sub(remaining) ; 1323 } 1324 borrows [ account ][ collateral ][ market ]. balance = borrowData . balance ; 1325 borrows [ account ][ collateral ][ market ]. accumulatedInterest = borrowData . interest ; 1326 borrows [ account ][ collateral ][ market ]. lastInterestIndex = borrowData . currentIndex ; 1327 collaterals [ account ][ collateral ]. lastUpdateTime = block.timestamp ; 1329 beforeChangeSupplyRate(market) ; 1331 marketAssets [ market ]. totalBorrow = marketAssets [ market ]. totalBorrow . sub(remaining) ; 1333 emitRepayBorrow ( 1334 msg.sender, 1335 account , 1336 market , 1337 collateral , 1338 transferAmount , 1339 borrowData . balance , 1340 borrowData . interest , 1341 borrowData . currentIndex 1342 ) ; 1343} Listing 3.10: Holdefi :: repayBorrowInternal() Recommendation Use beforeChangeBorrowRate() insteadof beforeChangeSupplyRate() tochange borrow index besides the changes in beforeChangeSupplyRate() . 18/35 PeckShield Audit Report #: 2021-057Public Status This issue has been under debate and the team confirmed that the current code achieves the expected effects without any need for recommended changes. 3.4 Safe-Version Replacement With safeTransfer() And safeTransferFrom() •ID: PVE-004 •Severity: Medium •Likelihood: Low •Impact: High•Target: Holdefi •Category: Security Features [9] •CWE subcategory: N/A Description ERC20 token transfers using transfer() ortransferFrom() are required to check the return values for confirming a successful transfer. However, some token contracts may not return a value or may revert on failure. This has led to serious vulnerabilities in the past [1]. OpenZeppelin’s SafeERC20 wrappers abstract away the handling of these different scenarios and is safer to use instead of reimplementing. Our analysis shows that the Holdefiprotocol uses transfer() and transferFrom() in the two functions shown below. 1088 /// @notice transfer ETH or ERC20 asset from this contract 1089 function transferFromHoldefi ( address receiver , address asset , uint256 amount) i n t e r n a l { 1090 boolsuccess = f a l s e; 1091 i f( asset == ethAddress){ 1092 (success , ) = receiver . c a l l{value:amount}( "") ; 1093 } 1094 e l s e{ 1095 IERC20 token = IERC20( asset ) ; 1096 success = token . t r a n s f e r ( receiver , amount) ; 1097 } 1098 require (success , " Cannot Transfer " ) ; 1099 } 1100 /// @notice transfer ERC20 asset to this contract 1101 function transferToHoldefi ( address receiver , address asset , uint256 amount) i n t e r n a l { 1102 IERC20 token = IERC20( asset ) ; 1103 boolsuccess = token . transferFrom( msg.sender, receiver , amount) ; 1104 require (success , " Cannot Transfer " ) ; 1105 } Listing 3.11: Holdefi :: transferFromHoldefi() andHoldefi :: transferToHoldefi () Recommendation Use SafeERC20 wrapper from OpenZeppelin which eliminates the need to handle boolean return values for tokens that either throw on failure or return no value. 19/35 PeckShield Audit Report #: 2021-057Public Status The issue has been addressed by the following commit: b01204f. 3.5 Owner Address Centralization Risk •ID: PVE-005 •Severity: Medium •Likelihood: Low •Impact: High•Target: Holdefi •Category: Security Features [5] •CWE subcategory: CWE-841 [4] Description The Holdefiprotocol has the notion of an administrator or owner who has exclusive access to critical functions. This is implemented using the onlyOwner modifier shown below, which is enforced on several critical functions that are used to add/remove/change markets/collateral/funds and access/- parameters (some of which are shown below). 33 /// @notice Throws if called by any account other than the owner 34 modifier onlyOwner() { 35 require (msg.sender == owner , " Sender should be owner " ) ; 36 _; 37} Listing 3.12: HoldefiOwnable::onlyOwner() 157 /// @notice Activate a market asset 158 /// @dev Can only be called by the owner 159 /// @param market Address of the given market 160 function activateMarket ( address market) public onlyOwner marketIsExist (market) { 161 activateMarketInternal (market) ; 162 } 163 164 /// @notice Deactivate a market asset 165 /// @dev Can only be called by the owner 166 /// @param market Address of the given market 167 function deactivateMarket ( address market) public onlyOwner marketIsExist (market) { 168 marketAssets [ market ]. isActive = f a l s e; 169 emitMarketActivationChanged(market , f a l s e) ; 170 } 171 172 /// @notice Activate a collateral asset 173 /// @dev Can only be called by the owner 174 /// @param collateral Address the given collateral 175 function activateCollateral ( address collateral ) public onlyOwner collateralIsExist ( collateral ) { 176 activateCollateralInternal ( collateral ) ; 177 } 20/35 PeckShield Audit Report #: 2021-057Public 178 179 /// @notice Deactivate a collateral asset 180 /// @dev Can only be called by the owner 181 /// @param collateral Address of the given collateral 182 function deactivateCollateral ( address collateral ) public onlyOwner collateralIsExist ( collateral ) { 183 collateralAssets [ collateral ]. isActive = f a l s e; 184 emitCollateralActivationChanged ( collateral , f a l s e) ; 185 } Listing 3.13: Example SettersInHoldefiSettings .sol If this owner address is an Externally-Owned-Account (EOA) then it represents a centralization risk in the event of the private key getting compromised or lost. This should ideally be a multi-sig contract account with multiple owners (e.g. 3 of 5) required to authorize transactions from that account. That will avoid central points of failure and reduce the risk. Recommendation Owner address should be a multi-sig contract account (not EOA) with a reasonable threshold of owners (e.g. 3 of 5) required to authorize transactions. Status This issue has been confirmed. And the team plans to use a governance contract in the near future. 3.6 Incompatibility with Deflationary/Rebasing Tokens •ID: PVE-006 •Severity: Low •Likelihood: Low •Impact: Medium•Target: Holdefi •Category: Business Logic [10] •CWE subcategory: CWE-841 [7] Description In the Holdefiprotocol, the contracts support both ETH and ERC20 assets on the supply and borrow sides. Naturally, the contract implements a number of low-level helper routines to transfer assets into or out of the Holdefiprotocol. These asset-transferring routines (example shown below) work as expected with standard ERC20 tokens: namely the protocol’s internal asset balances are always consistent with actual token balances maintained in individual ERC20 token contract. 1088 /// @notice transfer ETH or ERC20 asset from this contract 1089 function transferFromHoldefi ( address receiver , address asset , uint256 amount) i n t e r n a l { 1090 boolsuccess = f a l s e; 1091 i f( asset == ethAddress){ 1092 (success , ) = receiver . c a l l{value:amount}( "") ; 21/35 PeckShield Audit Report #: 2021-057Public 1093 } 1094 e l s e{ 1095 IERC20 token = IERC20( asset ) ; 1096 success = token . t r a n s f e r ( receiver , amount) ; 1097 } 1098 require (success , " Cannot Transfer " ) ; 1099 } 1100 /// @notice transfer ERC20 asset to this contract 1101 function transferToHoldefi ( address receiver , address asset , uint256 amount) i n t e r n a l { 1102 IERC20 token = IERC20( asset ) ; 1103 boolsuccess = token . transferFrom( msg.sender, receiver , amount) ; 1104 require (success , " Cannot Transfer " ) ; 1105 } Listing 3.14: Holdefi :: transferFromHoldefi() andHoldefi :: transferToHoldefi () 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 transferFromHoldefi() , 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 transferFrom() will always result in full transfer, we need to ensure the increased or decreased amount in the Holdeficontract before and after the 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 deflationary tokens or other customized ones if their support is deemed necessary. Another mitigation is to regulate the set of ERC20 tokens that are permitted to be the supply/- collateral tokens. In fact, the Holdefiprotocol is indeed in the position to effectively regulate the set of assets that can be used as collaterals. Meanwhile, there exist certain assets that may exhibit control switches that can be dynamically exercised to convert into deflationary ones. Recommendation If current codebase needs to support deflationary/rebasing 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 switchthatcanbeexercisedtoturnthemintodeflationarytokens. Oneexampleisthewidely-adopted USDT. Status The issue has been addressed by the following commit: e93890e. 22/35 PeckShield Audit Report #: 2021-057Public 3.7 Potential Reentrancy Risks •ID: PVE-007 •Severity: Medium •Likelihood: Low •Impact: High•Target: Holdefi •Category: Security Features [10] •CWE subcategory: CWE-841 [7] 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 invoking functions that should only be executed once. This attack was part of several most prominent hacks in Ethereum history, including the DAO[16] exploit, and the recent Uniswap/Lendf.Me hack [15]. We notice that while checks-effects-interactions pattern is followed in most places, there is an occasion where this principle is violated. In the Holdeficontract, the repayBorrowInternal() function (see the code snippet below) is provided to repay the borrowed ETH or tokens and transfers any additional ETH amount sent back to the msg.sender . However, if the sender is a contract then the invocation of an external contract requires extra care in avoiding the above re-entrancy. Apparently, the interaction with the external contract (via line 1307) starts before effecting update on internal states (beyond line 1309), hence violating the principle. While this flow currently only refunds the extra amount back to the caller, there could be potential implications if this logic changes in future. 1290 /// @notice Perform repay borrow operation 1291 function repayBorrowInternal ( address account , address market , address collateral , uint256 amount) 1292 i n t e r n a l 1293 whenNotPaused( " repayBorrow " ) 1294 { 1295 MarketData memory borrowData ; 1296 (borrowData . balance , borrowData . interest , borrowData . currentIndex ) = 1297 getAccountBorrow(account , market , collateral ) ; 1298 1299 uint256 totalBorrowedBalance = borrowData . balance .add(borrowData . interest ) ; 1300 require (totalBorrowedBalance != 0, " Total balance should not be zero " ) ; 1301 1302 uint256 transferAmount = amount; 1303 i f(transferAmount > totalBorrowedBalance) { 1304 transferAmount = totalBorrowedBalance ; 1305 i f(market == ethAddress) { 1306 uint256 extra = amount. sub(transferAmount) ; 23/35 PeckShield Audit Report #: 2021-057Public 1307 transferFromHoldefi ( msg.sender, ethAddress , extra ) ; 1308 } 1309 } 1310 1311 i f(market != ethAddress) { 1312 transferToHoldefi ( address (t h i s) , market , transferAmount) ; 1313 } 1314 1315 uint256 remaining = 0; 1316 i f(transferAmount <= borrowData . interest ) { 1317 borrowData . interest = borrowData . interest . sub(transferAmount) ; 1318 } 1319 e l s e{ 1320 remaining = transferAmount . sub(borrowData . interest ) ; 1321 borrowData . interest = 0; 1322 borrowData . balance = borrowData . balance . sub(remaining) ; 1323 } 1324 borrows [ account ][ collateral ][ market ]. balance = borrowData . balance ; 1325 borrows [ account ][ collateral ][ market ]. accumulatedInterest = borrowData . interest ; 1326 borrows [ account ][ collateral ][ market ]. lastInterestIndex = borrowData . currentIndex ; 1327 collaterals [ account ][ collateral ]. lastUpdateTime = block.timestamp ; 1328 1329 beforeChangeSupplyRate(market) ; 1330 1331 marketAssets [ market ]. totalBorrow = marketAssets [ market ]. totalBorrow . sub(remaining) ; 1332 1333 emitRepayBorrow ( 1334 msg.sender, 1335 account , 1336 market , 1337 collateral , 1338 transferAmount , 1339 borrowData . balance , 1340 borrowData . interest , 1341 borrowData . currentIndex 1342 ) ; 1343 } Listing 3.15: Holdefi :: repayBorrowInternal() Recommendation Apply the checks-effects-interactions design pattern in all places or add the reentrancy guard modifier for future-proofing and extra-protection. Status The issue has been addressed by the following commit: c0b8de0. 24/35 PeckShield Audit Report #: 2021-057Public 3.8 Incorrect newPriceAggregator Events Emitted in HoldefiPrices::setPriceAggregator() •ID: PVE-008 •Severity: Low •Likelihood: Low •Impact: Low•Target: HoldefiPrices •Category: Business Logic [10] •CWE subcategory: CWE-287 [11] Description In the HoldefiPrices contract, the function setPriceAggregator() allows the owner to set the price aggregator for the given asset as shown below: 66 /// @notice Sets price aggregator for the given asset 67 /// @param asset Address of the given asset 68 /// @param decimals Decimals of the given asset 69 /// @param priceContractAddress Address of asset ’s price aggregator 70 function setPriceAggregator ( address asset , uint256 decimals , AggregatorV3Interface priceContractAddress ) 71 external 72onlyOwner 73{ 74 require ( asset != ethAddress , " Asset should not be ETH" ) ; 75 assets [ asset ]. priceContract = priceContractAddress ; 76 77 tryERC20DecimalInterface( asset ) . decimals () returns (uint256 tokenDecimals) { 78 assets [ asset ]. decimals = tokenDecimals ; 79 } 80 catch{ 81 assets [ asset ]. decimals = decimals ; 82 } 83 emitNewPriceAggregator(asset , decimals , address ( priceContractAddress )) ; 84} Listing 3.16: HoldefiPrices :: setPriceAggregator() The decimals for the asset are set to either the function argument or the return value of ERC20DecimalInterface() depending on the try-catch path executed. However, the event emitted al- waysusesthefunctionparameterdecimals. Theeventemittedwillbeincorrectwhen ERC20DecimalInterface ()successfully returns tokenDecimals to be the decimals value. Recommendation Properly emit the newPriceAggregator event in the above setPriceAggregator ()function. Status The issue has been addressed by the following commit: a87774c. 25/35 PeckShield Audit Report #: 2021-057Public 3.9 Not Pausable Promotion/Liquidation Reserve Deposits •ID: PVE-009 •Severity: Low •Likelihood: Low •Impact: Medium•Target: Holdefi •Category: Security Features [8] •CWE subcategory: CWE-287 [6] Description The ability to pause certain operations of a contract’s functionality is considered a best-practice for guarded launch to protect against scenarios where critical contract vulnerabilities are discovered. In such situations, The capability to pause certain operations of the vulnerable contract is useful to prevent/reduce loss of funds. The Holdefiprotocol enables the pause functionality on eight different operations as indicated in the constructor() ofHoldefiPPausableOwnable.sol shown below: 34 /// @notice Define valid operations that can be paused 35 constructor ()public { 36 paused [ " supply " ]. isValid = true; 37 paused [ " withdrawSupply " ]. isValid = true; 38 paused [ " collateralize " ]. isValid = true; 39 paused [ " withdrawCollateral " ]. isValid = true; 40 paused [ " borrow " ]. isValid = true; 41 paused [ " repayBorrow " ]. isValid = true; 42 paused [ " liquidateBorrowerCollateral " ]. isValid = true; 43 paused [ " buyLiquidatedCollateral " ]. isValid = true; 44 } Listing 3.17: HoldefiPPausableOwnable:: constructor () This is enforced via the whenNotPaused modifier shown below: 52 /// @dev Modifier to make a function callable only when an operation is not paused 53 /// @param operation Name of the operation 54 modifier whenNotPaused( s t r i n g memory operation ) { 55 require (! isPaused( operation ) , " Operation is paused " ) ; 56 _; 57} Listing 3.18: HoldefiPausableOwnable::whenNotPaused() However,thispausableabilityismissingfortwootherfunctions,i.e., depositPromotionReserveInternal ()and depositLiquidationReserveInternal() . These two functions will affect the protocol state if they are invoked when other contract functionality is paused. 1392 /// @notice Perform deposit promotion reserve operation 1393 function depositPromotionReserveInternal ( address market , uint256 amount) 26/35 PeckShield Audit Report #: 2021-057Public 1394 i n t e r n a l 1395 marketIsActive (market) 1396 { 1397 i f(market != ethAddress) { 1398 transferToHoldefi ( address (t h i s) , market , amount) ; 1399 } 1400 uint256 amountScaled = amount.mul(secondsPerYear) .mul(rateDecimals) ; 1401 1402 marketAssets [ market ]. promotionReserveScaled = 1403 marketAssets [ market ]. promotionReserveScaled .add(amountScaled) ; 1404 1405 emitPromotionReserveDeposited(market , amount) ; 1406 } 1407 1408 /// @notice Perform deposit liquidation reserve operation 1409 function depositLiquidationReserveInternal ( address collateral , uint256 amount) 1410 i n t e r n a l 1411 collateralIsActive (ethAddress) 1412 { 1413 i f( collateral != ethAddress) { 1414 transferToHoldefi ( address ( holdefiCollaterals ) , collateral , amount) ; 1415 } 1416 e l s e{ 1417 transferFromHoldefi ( address ( holdefiCollaterals ) , collateral , amount) ; 1418 } 1419 collateralAssets [ ethAddress ]. totalLiquidatedCollateral = 1420 collateralAssets [ ethAddress ]. totalLiquidatedCollateral .add( msg.value) ; 1421 1422 emitLiquidationReserveDeposited (ethAddress , msg.value) ; 1423 } Listing 3.19: Holdefi :: depositPromotionReserveInternal() andHoldefi :: depositLiquidationReserveInternal () Recommendation Enable the pause functionality for two aforementioned functions, i.e., depositPromotionReserveInternal() and depositLiquidationReserveInternal() . Status The issue has been addressed by the following commit: 44e2780. 27/35 PeckShield Audit Report #: 2021-057Public 3.10 Incorrect Natspec Comment •ID: PVE-010 •Severity: Informational •Likelihood: Low •Impact: Low•Target: HoldefiPPausableOwnable •Category: Security Features [8] •CWE subcategory: CWE-287 [3] Description The @noticepart of the Natspec comment for batchUnpause() function incorrectly notes that this is to be called by pausers to pause operations as shown below. This is likely a copy-paste bug from batchPause() comments. This is meant to be called only by the owner to unpause operations that are paused, as enforced by onlyOwner and whenPaused modifiers of the unpause() function called here. 121 /// @notice Called by pausers to pause operations , returns to normal state for selected operations 122 /// @param operations List of operation names 123 function batchUnpause( s t r i n g[]memory operations ) external { 124 for(uint256 i = 0 ; i < operations . length ; i++) { 125 unpause( operations [ i ]) ; 126 } 127 } Listing 3.20: HoldefiPPausableOwnable::batchUnpause() 99 /// @notice Called by owner to unpause an operation , returns to normal state 100 /// @param operation Name of the operation 101 function unpause( s t r i n g memory operation ) 102 public 103 onlyOwner 104 operationIsValid ( operation ) 105 whenPaused( operation ) 106 { 107 paused [ operation ]. pauseEndTime = 0; 108 emitOperationUnpaused( operation ) ; 109 } Listing 3.21: HoldefiPPausableOwnable::unpause() Recommendation Change comment to /// @notice Called by owner to unpause operations, returns to normal state for selected operations Status The issue has been addressed by the following commit: 68c8eac. 28/35 PeckShield Audit Report #: 2021-057Public 3.11 Removal Of No-Effect Redundant Code •ID: PVE-011 •Severity: Informational •Likelihood: Low •Impact: Low•Target: HoldefiSettings •Category: Coding Practices [8] •CWE subcategory: CWE-287 [3] Description During our analysis, we notice the presence of redundant code with no actual effect. For example, lines 328-330ofaddMarket() and lines 388-390ofaddCollateral cast the address type into IERC20 interface but do not assign it to any variable, as shown below. This code has no side-effects and can be removed to save gas. 316 /// @notice Add a new asset as a market 317 /// @dev Can only be called by the owner 318 /// @param market Address of the new market 319 /// @param borrowRate BorrowRate of the new market 320 /// @param suppliersShareRate SuppliersShareRate of the new market 321 function addMarket ( address market , uint256 borrowRate , uint256 suppliersShareRate ) 322 external 323 onlyOwner 324 { 325 require (! marketAssets [ market ]. isExist , " The market is exist " ) ; 326 require ( marketsList . length < maxListsLength , " Market list is full " ) ; 327 328 i f(market != ethAddress) { 329 IERC20(market) ; 330 } 331 332 marketsList . push(market) ; 333 marketAssets [ market ]. isExist = true; 334 emitMarketExistenceChanged(market , true) ; 335 336 setBorrowRateInternal (market , borrowRate) ; 337 setSuppliersShareRateInternal (market , suppliersShareRate ) ; 338 339 activateMarketInternal (market) ; 340 } Listing 3.22: HoldefiSettings ::addMarket() 371 /// @notice Add a new asset as a collateral 372 /// @dev Can only be called by the owner 373 /// @param collateral Address of the new collateral 374 /// @param valueToLoanRate ValueToLoanRate of the new collateral 375 /// @param penaltyRate PenaltyRate of the new collateral 29/35 PeckShield Audit Report #: 2021-057Public 376 /// @param bonusRate BonusRate of the new collateral 377 function addCollateral ( 378 address collateral , 379 uint256 valueToLoanRate , 380 uint256 penaltyRate , 381 uint256 bonusRate 382 ) 383 external 384 onlyOwner 385 { 386 require (! collateralAssets [ collateral ]. isExist , " The collateral is exist " ) ; 387 388 i f( collateral != ethAddress) { 389 IERC20( collateral ) ; 390 } 391 392 collateralAssets [ collateral ]. isExist = true; 393 emitCollateralExistenceChanged ( collateral , true) ; 394 395 setValueToLoanRateInternal( collateral , valueToLoanRate) ; 396 setPenaltyRateInternal ( collateral , penaltyRate) ; 397 setBonusRateInternal ( collateral , bonusRate) ; 398 399 activateCollateralInternal ( collateral ) ; 400 } Listing 3.23: HoldefiSettings :: addCollateral() Recommendation Remove the indicated lines of code from the two functions shown above. Status The issue has been addressed by the following commit: fa120ee. 3.12 Gas Optimization In HoldefiSettings::removeMarket() •ID: PVE-012 •Severity: Low •Likelihood: Low •Impact: Low•Target: HoldefiSettings •Category: Coding Practices [8] •CWE subcategory: CWE-287 [3] Description In the HoldefiSettings contract, the removeMarket() function is designed to remove the given mar- ket. While analyzing the implementation, we notice two possible optimizations. First, the call to beforeChangeBorrowRate() on line 349is not necessary because the specified market is going to be immediately deleted anyway. 30/35 PeckShield Audit Report #: 2021-057Public Second, the for-loop on line 361where all the markets in the array after the one to be deleted are shifted left can also be optimized by copying the last element to the slot with the deleted market and then popping the last element. This will save gas. 342 /// @notice Remove a market asset 343 /// @dev Can only be called by the owner 344 /// @param market Address of the given market 345 function removeMarket ( address market) external onlyOwner marketIsExist (market) { 346 uint256 totalBorrow = holdefiContract . marketAssets(market) . totalBorrow ; 347 require (totalBorrow == 0, " Total borrow is not zero " ) ; 348 349 holdefiContract . beforeChangeBorrowRate(market) ; 350 351 uint256 i ; 352 uint256 index ; 353 uint256 marketListLength = marketsList . length; 354 for( i = 0 ; i < marketListLength ; i++) { 355 i f( marketsList [ i ] == market) { 356 index = i ; 357 } 358 } 359 360 i f(index != marketListLength −1) { 361 for( i = index ; i < marketListLength −1 ; i++) { 362 marketsList [ i ] = marketsList [ i +1]; 363 } 364 } 365 366 marketsList .pop() ; 367 delete marketAssets [ market ]; 368 emitMarketExistenceChanged(market , f a l s e) ; 369 } Listing 3.24: HoldefiSettings ::removeMarket() Recommendation Apply the above two optimizations in removeMarket() . An example revision is shown below: 342 /// @notice Remove a market asset 343 /// @dev Can only be called by the owner 344 /// @param market Address of the given market 345 function removeMarket ( address market) external onlyOwner marketIsExist (market) { 346 uint256 totalBorrow = holdefiContract . marketAssets(market) . totalBorrow ; 347 require (totalBorrow == 0, " Total borrow is not zero " ) ; 348 349 uint256 i ; 350 uint256 index ; 351 uint256 marketListLength = marketsList . length; 352 for( i = 0 ; i < marketListLength ; i++) { 353 i f( marketsList [ i ] == market) { 354 index = i ; 355 } 31/35 PeckShield Audit Report #: 2021-057Public 356 } 357 358 marketsList [ index ] = marketsList [ marketListLength −1]; 359 marketsList .pop() ; 360 delete marketAssets [ market ]; 361 emitMarketExistenceChanged(market , f a l s e) ; 362 } Listing 3.25: HoldefiSettings :removeMarket() Status The issue has been addressed by the following commit: 83728c9. 32/35 PeckShield Audit Report #: 2021-057Public 4 | Conclusion In this audit, we have analyzed the design and implementation of the Holdefiprotocol that is a decentralized open-source non-custodial money market protocol where users can participate as de- positors or borrowers. During the audit, we notice that the current code base is clearly organized and those identified issues are promptly confirmed and fixed. As a final precaution, 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. 33/35 PeckShield Audit Report #: 2021-057Public References [1] Lukas Cremer. Return Value Bug. https://medium.com/coinmonks/ missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca. [2] HaleTom. Resolution on the EIP20 API Approve / TransferFrom multiple withdrawal attack. https://github.com/ethereum/EIPs/issues/738. [3] MITRE. CWE-287: ImproperAuthentication. https://cwe.mitre.org/data/definitions/287.html. [4] MITRE. CWE-308: Use of Single-factor Authentication. https://cwe.mitre.org/data/ definitions/308.html. [5] MITRE. CWE-654: Reliance on a Single Factor in a Security Decision. https://cwe.mitre.org/ data/definitions/654.html. [6] MITRE. CWE-671: Lack of Administrator Control over Security. https://cwe.mitre.org/data/ definitions/671.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: Bad Coding Practices. https://cwe.mitre.org/data/definitions/ 1006.html. 34/35 PeckShield Audit Report #: 2021-057Public [10] MITRE. CWE CATEGORY: Business Logic Errors. https://cwe.mitre.org/data/definitions/ 840.html. [11] MITRE. CWE CATEGORY: Error Conditions, Return Values, Status Codes. https://cwe.mitre. org/data/definitions/389.html. [12] MITRE. CWE VIEW: Development Concepts. https://cwe.mitre.org/data/definitions/699. html. [13] OWASP. Risk Rating Methodology. https://www.owasp.org/index.php/OWASP_Risk_ Rating_Methodology. [14] PeckShield. PeckShield Inc. https://www.peckshield.com. [15] PeckShield. Uniswap/Lendf.Me Hacks: Root Cause and Loss Analysis. https://medium.com/ @peckshield/uniswap-lendf-me-hacks-root-cause-and-loss-analysis-50f3263dcc09. [16] David Siegel. Understanding The DAO Attack. https://www.coindesk.com/ understanding-dao-hack-journalists. 35/35 PeckShield Audit Report #: 2021-057
Issues Count of Minor/Moderate/Major/Critical - Minor: 8 - Moderate: 1 - Major: 0 - Critical: 0 Minor Issues 2.a Problem (one line with code reference) - Race Conditions with Approves (Holdefi.sol#L717) - Flawed Logic Of Holdefi::depositLiquidationReserve() (Holdefi.sol#L1490) - Suggested beforeChangeBorrowRate() in Borrow-Related Operations (Holdefi.sol#L1590) - Safe-Version Replacement With safeTransfer() And safeTransferFrom() (Holdefi.sol#L1745) - Owner Address Centralization Risk (Holdefi.sol#L1845) - Incompatibility with Deflationary/Rebasing Tokens (Holdefi.sol#L1890) - Potential Reentrancy Risks (Holdefi.sol#L1930) - Incorrect newPriceAggregator Events Emitted in HoldefiPrices::setPriceAggregator() 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 the function _mint() of HLDToken.sol (line 545) 2.b Fix (one line with code reference): Check the return value of the function _mint() of HLDToken.sol (line 545) Moderate Issues 3.a Problem (one line with code reference): Unchecked return value in the function _burn() of HLDToken.sol (line 590) 3.b Fix (one line with code reference): Check the return value of the function _burn() of HLDToken.sol (line 590) Major Issues: None Critical Issues: None Observations: - The Holdefi Protocol is a lending platform where users can deposit assets to receive interest or borrow tokens to repay it later. - The interest received from the borrowers is distributed among suppliers in proportion to the amounts supplied. - To borrow tokens, borrowers have to deposit collateral (ETH or ERC 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 function transferFrom() (CWE-252) 2.b Fix (one line with code reference): Check return value of transferFrom() (CWE-252) Moderate Issues 3.a Problem (one line with code reference): Unchecked return value in function transfer() (CWE-252) 3.b Fix (one line with code reference): Check return value of transfer() (CWE-252) 4.a Problem (one line with code reference): Unchecked return value in function approve() (CWE-252) 4.b Fix (one line with code reference): Check return value of approve() (CWE-252) 5.a Problem (one line with code reference): Unchecked return value in function transferFrom() (CWE-252) 5.b Fix (one line with code reference): Check return value of transferFrom() (CWE-252) Observations - The
// SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./StakingRewards.sol"; contract StakingRewardsFactory is Ownable { // immutables uint256 public stakingRewardsGenesis; // the staking tokens for which the rewards contract has been deployed address[] public stakingTokens; // info about rewards for a particular staking token struct StakingRewardsInfo { address stakingRewards; address[] poolRewardToken; uint256[] poolRewardAmount; } // multiple reward tokens //address[] public rewardTokens; // rewards info by staking token mapping(address => StakingRewardsInfo) public stakingRewardsInfoByStakingToken; // rewards info by staking token mapping(address => uint256) public rewardTokenQuantities; // SWC-Weak Sources of Randomness from Chain Attributes: L36 constructor(uint256 _stakingRewardsGenesis) public Ownable() { require( _stakingRewardsGenesis >= block.timestamp, "StakingRewardsFactory::constructor: genesis too soon" ); stakingRewardsGenesis = _stakingRewardsGenesis; } ///// permissioned functions // deploy a staking reward contract for the staking token, and store the reward amount // the reward will be distributed to the staking reward contract no sooner than the genesis function deploy( address stakingToken, address[] memory rewardTokens, uint256[] memory rewardAmounts ) public onlyOwner { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require( info.stakingRewards == address(0), "StakingRewardsFactory::deploy: already deployed" ); info.stakingRewards = address( new StakingRewards( /*_rewardsDistribution=*/ address(this), rewardTokens, stakingToken ) ); for (uint8 i = 0; i < rewardTokens.length; i++) { require( rewardAmounts[i] > 0, "StakingRewardsFactory::addRewardToken: reward amount should be greater than 0" ); info.poolRewardToken.push(rewardTokens[i]); info.poolRewardAmount.push(rewardAmounts[i]); rewardTokenQuantities[rewardTokens[i]] = rewardAmounts[i]; } stakingTokens.push(stakingToken); } // Rescue leftover funds from pool function rescueFunds(address stakingToken, address tokenAddress) public onlyOwner { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require( info.stakingRewards != address(0), "StakingRewardsFactory::notifyRewardAmount: not deployed" ); StakingRewards(info.stakingRewards).rescueFunds( tokenAddress, msg.sender ); } // Rescue leftover funds from factory function rescueFactoryFunds(address tokenAddress) public onlyOwner { IERC20 token = IERC20(tokenAddress); uint256 balance = token.balanceOf(address(this)); require(balance > 0, "No balance for given token address"); token.transfer(msg.sender, balance); } ///// permissionless functions // call notifyRewardAmount for all staking tokens. function notifyRewardAmounts() public { require( stakingTokens.length > 0, "StakingRewardsFactory::notifyRewardAmounts: called before any deploys" ); for (uint256 i = 0; i < stakingTokens.length; i++) { notifyRewardAmount(stakingTokens[i]); } } // notify reward amount for an individual staking token. // this is a fallback in case the notifyRewardAmounts costs too much gas to call for all contracts function notifyRewardAmount(address stakingToken) public { // SWC-Weak Sources of Randomness from Chain Attributes: L122 require( block.timestamp >= stakingRewardsGenesis, "StakingRewardsFactory::notifyRewardAmount: not ready" ); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require( info.stakingRewards != address(0), "StakingRewardsFactory::notifyRewardAmount: not deployed" ); for (uint256 i = 0; i < info.poolRewardToken.length; i++) { uint256 rewardAmount = info.poolRewardAmount[i]; if (rewardAmount > 0) { info.poolRewardAmount[i] = 0; require( IERC20(info.poolRewardToken[i]).transfer( info.stakingRewards, rewardAmount ), "StakingRewardsFactory::notifyRewardAmount: transfer failed" ); StakingRewards(info.stakingRewards).notifyRewardAmount( info.poolRewardToken[i], rewardAmount ); } } } function stakingRewardsInfo(address stakingToken) public view returns ( address, address[] memory, uint256[] memory ) { StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; return ( info.stakingRewards, info.poolRewardToken, info.poolRewardAmount ); } } // SPDX-License-Identifier: MIT // SWC-Outdated Compiler Version: L4 // SWC-Floating Pragma: L4 pragma solidity >=0.6.11; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./libraries/NativeMetaTransaction/NativeMetaTransaction.sol"; // Inheritance import "./interfaces/IStakingRewards.sol"; import "./RewardsDistributionRecipient.sol"; contract StakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard, NativeMetaTransaction { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardsDuration = 30 days; uint256 public rewardPerTokenStored; uint256 private _totalSupply; address[] private stakers; address[] public rewardTokens; mapping(address => uint256) public rewardsPerTokenMap; mapping(address => uint256) public tokenRewardRate; mapping(address => uint256) private _balances; mapping(address => uint256) public rewardLastUpdatedTime; mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; mapping(address => mapping(address => uint256)) public rewards; /* ========== CONSTRUCTOR ========== */ constructor( address _rewardsDistribution, address[] memory _rewardTokens, address _stakingToken ) public { rewardTokens = _rewardTokens; stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; _initializeEIP712("DualFarmsV1"); } /* ========== VIEWS ========== */ function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function stakerBalances() external view returns (address[] memory, uint256[] memory) { uint256 stakerCount = stakers.length; uint256[] memory balances = new uint256[](stakerCount); for (uint256 i = 0; i < stakers.length; i++) { balances[i] = _balances[stakers[i]]; } return (stakers, balances); } // SWC-Weak Sources of Randomness from Chain Attributes: L87 function lastTimeRewardApplicable() public view override returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken(address rewardToken) public view override returns (uint256) { if (_totalSupply == 0) { return rewardsPerTokenMap[rewardToken]; } return rewardsPerTokenMap[rewardToken].add( lastTimeRewardApplicable() .sub(rewardLastUpdatedTime[rewardToken]) .mul(tokenRewardRate[rewardToken]) .mul(1e18) .div(_totalSupply) ); } function earned(address account, address rewardToken) public view override returns (uint256) { return _balances[account] .mul( rewardPerToken(rewardToken).sub( userRewardPerTokenPaid[account][rewardToken] ) ) .div(1e18) .add(rewards[account][rewardToken]); } function getRewardForDuration(address rewardToken) external view override returns (uint256) { return tokenRewardRate[rewardToken].mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant updateReward(_msgSender()) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); // permit IEllipticRC20(address(stakingToken)).permit( _msgSender(), address(this), amount, deadline, v, r, s ); stakingToken.safeTransferFrom(_msgSender(), address(this), amount); emit Staked(_msgSender(), amount); } function stake(uint256 amount) external override nonReentrant updateReward(_msgSender()) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); if (_balances[_msgSender()] == 0) { stakers.push(_msgSender()); } _balances[_msgSender()] = _balances[_msgSender()].add(amount); stakingToken.safeTransferFrom(_msgSender(), address(this), amount); emit Staked(_msgSender(), amount); } function withdraw(uint256 amount) public override nonReentrant updateReward(_msgSender()) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[_msgSender()] = _balances[_msgSender()].sub(amount); stakingToken.safeTransfer(_msgSender(), amount); emit Withdrawn(_msgSender(), amount); } function getReward() public override nonReentrant updateReward(_msgSender()) { for (uint256 i = 0; i < rewardTokens.length; i++) { uint256 reward = rewards[_msgSender()][rewardTokens[i]]; if (reward > 0) { rewards[_msgSender()][rewardTokens[i]] = 0; IERC20(rewardTokens[i]).safeTransfer(_msgSender(), reward); emit RewardPaid(_msgSender(), reward); } } } function exit() external override { withdraw(_balances[_msgSender()]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(address rewardToken, uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) { // SWC-Weak Sources of Randomness from Chain Attributes: L223, L225, L227 uint256 rewardRate = tokenRewardRate[rewardToken]; if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); periodFinish = block.timestamp.add(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(remaining); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = IERC20(rewardToken).balanceOf(address(this)); // SWC-Weak Sources of Randomness from Chain Attributes: L239 require( rewardRate <= balance.div(periodFinish.sub(block.timestamp)), "Provided reward too high" ); // SWC-Weak Sources of Randomness from Chain Attributes: 244 rewardLastUpdatedTime[rewardToken] = block.timestamp; tokenRewardRate[rewardToken] = rewardRate; emit RewardAdded(reward); } function rescueFunds(address tokenAddress, address receiver) external onlyRewardsDistribution { require( tokenAddress != address(stakingToken), "StakingRewards: rescue of staking token not allowed" ); IERC20(tokenAddress).transfer( receiver, IERC20(tokenAddress).balanceOf(address(this)) ); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { for (uint256 i = 0; i < rewardTokens.length; i++) { rewardsPerTokenMap[rewardTokens[i]] = rewardPerToken( rewardTokens[i] ); rewardLastUpdatedTime[rewardTokens[i]] = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account][rewardTokens[i]] = earned( account, rewardTokens[i] ); userRewardPerTokenPaid[account][ rewardTokens[i] ] = rewardsPerTokenMap[rewardTokens[i]]; } } _; } /* ========== EVENTS ========== */ 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); } interface IEllipticRC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; contract Migrations { address public owner; uint256 public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; abstract contract RewardsDistributionRecipient { address public rewardsDistribution; function notifyRewardAmount(address rewardToken, uint256 reward) external virtual; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, 'Caller is not RewardsDistribution contract'); _; } }
01Audit Report May, 2021Contents Introduction 01 02 03 04 13 17 18Audit Goals Issue Categories Manual Audit Automated Testing Summary DisclaimerIntroduction Auditing Approach and Methodologies applied This audit report highlights the overall security of the DFYN staking rewards and staking reward factory with commit hash f44a4 . With this report, QuillHash Audit has tried to ensure the reliability of the smart contract by completing the assessment of their system’s architecture and smart contract codebase. In this audit, we consider the following crucial features of the code. The audit has been performed according to the following procedure: Whether the implementation of ERC 20 standards. Whether the code is secure. Gas Optimization Whether the code meets the best coding practices. Whether the code meets the SWC Registry issue. 01 Manual Audit Inspecting the code line by line and revert the initial algorithms of the protocol and then compare them with the specification Manually analyzing the code for security vulnerabilities. Gas Consumption and optimisation Assessing the overall project structure, complexity & quality. Checking SWC Registry issues in the code. Unit testing by writing custom unit testing for each function. Checking whether all the libraries used in the code of the latest version. Analysis of security on-chain data. Analysis of the failure preparations to check how the smart contract performs in case of bugs and vulnerability. Automated analysis Scanning the project's code base with Mythril , Slither , Echidna , Manticore , others. Manually verifying (reject or confirm) all the issues found by tools. Performing Unit testing. 02Audit Details Audit Goals Project Name: DFYN Contract commit hash: https://github.com/dfyn/dual-farm/commit/f44a4dcbeb41f38a9c02cb877a8c95b92685f972 Contract files: https://github.com/dfyn/dual-farm/blob/main/contracts/StakingRewardsFactory.sol https://github.com/dfyn/dual-farm/blob/main/contracts/StakingRewards.sol Language: Solidity Platform and tools: HardHat, Remix, VScode, solhint and other tools mentioned in the automated analysis section. Report: All the gathered information is described in this report. Security Identifying security related issues within each contract and the system of contract. Sound Architecture Evaluating the architect of a system through the lens of established smart contract best practice and general software practice. Code Correctness and Quality A full review of the contract source code. The primary areas of focus include The focus of this audit was to verify whether the smart contract is secure, resilient, and working according to the standard specs. The audit activity can be grouped into three categories. Manual Security Testing (SWC-Registry, Overflow) Running the tests and checking their coverage. Correctness. Section of code with high complexity. Readability. Quantity and quality of test coverage. 03Issue Categories Every issue in this report was assigned a severity level from the following: Issues on this level are critical to the smart contract’s performance/ functionality and should be fixed before moving to a live environment. Issues on this level could potentially bring problems and should eventually be fixed. Issues on this level are minor details and warnings that can remain unfixed but would be better fixed at some point in the future.High severity issues Medium severity issues Low severity issues Number of issues per severity OpenHigh ClosedLow 3 1 0 10 0 0 1Medium Informational 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.Informational04Manual Audit SWC Registry test We have tested some known SWC registry issues. Out of all tests, only SWC 116, 102 and 103 got detected. All are the low priority ones and we have discussed them above already. Serial No. Comments Description SWC-132 Unexpected Ether balance Pass: Avoided strict equality checks for the E ther balance in a contract SWC-131 Presence o f unuse d variables Pass: No unuse d variables SWC-128 DoS With Block Gas Limit Pass SWC-122 Lack of Proper Signature Verification Pass SWC-120 Weak Sources of Randomness from Chain AttributesPass SWC-119 Shado wing State Variables Pass: No ambiguous found. SWC-118 Incorrect Constructor Name Pass. No incorrect constructor name used SWC-116 Timestamp Dependence SWC-115 Authorization through tx.origin SWC-114 Transaction Order Dependence Pass Found Pass: No tx.origin found05Serial No. Comments Descrip tion SWC-111 SWC-113 SWC-112 Use of Deprecated Solidity Functions DoS with Failed Call Delegatecall to Untrusted Callee Pass: No deprecated function used Pass: No failed call Pass SWC-108 State Variable Default Visibility Pass: Explicitly defined visibility for all state variables SWC-107 Reentrancy Pass SWC-106 Unprotected SELF-DES TRUCT Instruction Pass: Not found a ny such vulnerability SWC-104 Unchecked Call Return Value Pass: Not found a ny such vulnerability SWC-103 Floating Pragma Found SWC-102 Outdated Compiler Version Found SWC-101 Integer Overflow and Underflow Pass No issues foundHigh level severity issues06Medium level severity issues There was 1 medium severity issue found. 1. Costly Loop The loop in the contract includes state variables like .length of a non- memory array, in the condition of the for loops. As a result, these state variables consume a lot more extra gas for every iteration of the ‘for’ loop. The below functions include such loops at the above-mentioned lines: Recommendation: It's quite effective to use a local variable instead of a state variable like .length in a loop. For instance, uint256 local_variable = _groupInfo.addresses.length; for (uint256 i = 0; i < local_variable; i++) { if (_groupInfo.addresses[i] == msg.sender) { _isAddressExistInGroup = true; _senderIndex = i; break; } } Reading reference link https://blog.b9lab.com/getting-loopy-with-solidity-1d51794622ad notifyRewardAmounts () → StakingRewardsFactory.sol notifyRewardAmount → StakingRewardsFactory.sol Deploy → StakingRewardsFactory.sol stakerBalances → StakingRewards.sol getReward → StakingRewards.sol rescueFunds → StakingRewards.sol07 Status: As informed by the Dfyn team, they are working on Layer 2. For Layer 2 this bug would be false positive. Hence marking the issue CLOSED. Low level severity issues There were 4 low severity issues found. Using an outdated compiler version can be problematic especially if there are publicly disclosed bugs and issues that affect the current compiler version. Remediation It is recommended to use a recent version of the Solidity compiler which is Version 0.8.4. Contracts should be deployed with the same compiler version and flags that they have been tested 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 (https:// github.com/ethereum/solidity/releases) for the compiler version that is chosen.Description → SWC 102 : Outdated Compiler Version Description → SWC 103: Floating Pragma 1. 2.08 Pragma statements can be allowed to float when a contract is intended for consumption by other developers, as in the case with contracts in a library or EthPM package. Otherwise, the developer would need to manually update the pragma in order to compile locally. Contracts often need access to time values to perform certain types of functionality. Values such as block.timestamp, and block.number can give you a sense of the current time or a time delta, however, they are not safe to use for most purposes. In the case of block.timestamp, developers often attempt to use it to trigger time-dependent events. As Ethereum is decentralized, nodes can synchronize time only to some degree. Moreover, malicious miners can alter the timestamp of their blocks, especially if they can gain advantages by doing so. However, miners can't set a timestamp smaller than the previous one (otherwise the block will be rejected), nor can they set the timestamp too far ahead in the future. Taking all of the above into consideration, developers can't rely on the preciseness of the provided timestamp. Remediation Developers should write smart contracts with the notion that block values are not precise, and the use of them can lead to unexpected effects. Alternatively, they may make use of oracles.In StakingRewardsFactory.sol: Line no: 35 & 120 In StakingRewards.sol: Line no: 85, 220, 222, 224, 235, 239Description: Potential use of "block.timestamp" as source of randomness 3. References Safety: Timestamp dependence Ethereum Smart Contract Best Practices - Timestamp Dependence09 How do Ethereum mining nodes maintain a time consistent with the network? Solidity: Timestamp dependency, is it possible to do safely? Status: As informed by the Dfyn team, they are working on Layer 2. For Layer 2 this bug would be false positive. Hence marking the issue CLOSED. A function with a public visibility modifier that is not called internally. Changing the visibility level to external increases code readability. Moreover, in many cases, functions with external visibility modifiers spend less gas compared to functions with public visibility modifiers. The function definition in the file StakingRewards.sol are marked as public lastTimeRewardApplicable rewardPerToken Earned Withdraw getReward And in the file StakingRewardsFactory.sol below function definition are also marked as public rescueFunds rescueFactoryFunds notifyRewardAmounts notifyRewardAmount stakingRewardsInfo However, it is never directly called by another function in the same contract or in any of its descendants. Consider marking it as"external" instead Recommendations Use the external visibility modifier for functions never called from the contract via internal call. Reading Link . Note: Exact same issue was found while using automated testing by Mythx.Description: Prefer external to public visibility level 4.101.Description: Missing reentrancy protection (StakingRewards.sol)Informational The getReward function did not make use of a modifier to protect against potential reentrancy attacks. If a token were to implement a callback (e.g. ERC-223 or ERC-777), the function could in theory be targeted through a reentrancy attack. However, as the checks-effects pattern was used the potential for exploitation was mitigated. Recommendations A ReentrancyGuard could be used to protect against reentrancy attacks as a defence-in-depth measure.1 1Functional test StakingRewardsFactory.sol StakingReward.sol deploy function was able to deploy a staking reward contract for the staking token and store the reward tokens addresses and amounts. -- > PASS rescueFunds function was able to rescue extra funds from StakingRewards.sol also, cannot able to access staking tokens. --> PASS rescueFactoryFunds function was able to rescue extra funds from StakingRewardsFactory.sol and, transfer them to the owners account. --> PASS notifyRewardAmounts function was able to transfer the reward amount of all the staking reward pools. --> PASS notifyRewardAmount function notify reward amount for an individual staking token. --> PASS stakingRewardsInfo returns a staking reward pool address, array of reward token addresses and array of reward amount. --> PASS totalSupply returns total supply of staking token. --> PASS stakerBalances returns array of stakers and array of their balances. --> PASS Function test has been done for multiple functions of both the files. Results are below12lastTimeRewardApplicable returns the minimum between Period End and current time. --> PASS rewardPerToken returns reward per token --> PASS earned returns reward earned by caller --> PASS getRewardForDuration returns the duration in unix timestamp. --> PASS stakeWithPermit function works as stake for LP Tokens and emits the event. --> PASS withdraw function works for UnStaking of LP Tokens and emits the event. --> PASS getReward function calculates the rewards for a caller and transfers the reward. --> PASS exit Withdraw all LP tokens and rewards for a caller. --> PASS notifyRewardAmount will call this method to notify to start reward generation --> PASS rescueFunds rescue extra funds only called my factory also, cannot able to access staking tokens --> PASS updateReward acts as a modifier that updates pool information in every mutation calls. --> PASS13Automated Testing Slither Slither is a Solidity static analysis framework that runs a suite of vulnerability detectors, prints visual information about contract details, and provides an API to easily write custom analyses. Slither enables developers to find vulnerabilities, enhance their code comprehension, and quickly prototype custom analyses. After running Slither we got the results below. We have used multiple automated testing frameworks. This makes code more secure and common attacks. The results are below.141516 Description Unable to locate the right file from Openzepplin Recommendation Use the specific version tag of each repo to get rid of the above error like done at Uniswap . Manticore Manticore is a symbolic execution tool for the analysis of smart contracts and binaries. It executes a program with symbolic inputs and explores all the possible states it can reach. It also detects crashes and other failure cases in binaries and smart contracts. Manticore results throw the same warning which is similar to the Slither warning. 17Disclaimer Quillhash audit is not a security warranty, investment advice, or endorsement of the Dfyn 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 Dfyn Team put in place a bug bounty program to encourage further analysis of the smart contract by other third parties.18Summary The use of smart contracts is simple and the code is relatively small. Altogether the code is written and demonstrates effective use of abstraction, separation of concern, and modularity. But there are a few issues/vulnerabilities to be tackled at various security levels, it is recommended to fix them before deploying the contract on the main network. Given the subjective nature of some assessments, it will be up to the Dfyn team to decide whether any changes should be made.17
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) Line 545: Potential reentrancy vulnerability 2.b Fix (one line with code reference) Line 545: Add a require statement to check the msg.sender Moderate: 0 Major: 0 Critical: 0 Observations The code is well written and follows the best coding practices. Conclusion The audit report concludes that the code is secure and follows the best coding practices. No major or critical issues were found. Issues Count of Minor/Moderate/Major/Critical Minor: 0 Moderate: 1 Major: 0 Critical: 0 Minor Issues: None Moderate Issues: 1. Costly Loop Problem: The loop in the contract includes state variables like .length of a non-memory array, in the condition of the for loops. Fix: Use a local variable instead of a state variable like .length in a loop. Major Issues: None Critical Issues: None Observations: - All tests only detected low priority issues - No deprecated functions, failed calls, tx.origin, uncheck call return values, unprotected self-destruct instructions, or integer overflow/underflow were found Conclusion: The audit found no major or critical issues, and only one moderate issue. The contract is ready for deployment. Issues Count of Minor/Moderate/Major/Critical: Minor: 4 Moderate: 0 Major: 0 Critical: 0 Minor Issues: 1. SWC 102: Outdated Compiler Version Problem: Using an outdated compiler version can be problematic especially if there are publicly disclosed bugs and issues that affect the current compiler version. Fix: Lock the pragma version and also consider known bugs (https://github.com/ethereum/solidity/releases) for the compiler version that is chosen. 2. SWC 103: Floating Pragma Problem: Pragma statements can be allowed to float when a contract is intended for consumption by other developers, as in the case with contracts in a library or EthPM package. Fix: Lock the pragma version and also consider known bugs (https://github.com/ethereum/solidity/releases) for the compiler version that is chosen. 3. SWC 104: Use of Block Timestamp Problem: Contracts often need access to time values to perform certain types of functionality. Values such as block.timestamp, and block.number can give you a sense of the current time or a time delta, however,
pragma solidity >=0.6.0; pragma experimental ABIEncoderV2; import "./SafeERC20.sol"; import "./IRouter.sol"; import "./StageDefine.sol"; import "./IBondData.sol"; interface IPRA { function raters(address who) external view returns (bool); } interface IConfig { function ratingCandidates(address proposal) external view returns (bool); function depositDuration() external view returns (uint256); function professionalRatingWeightRatio() external view returns (uint256); function communityRatingWeightRatio() external view returns (uint256); function investDuration() external view returns (uint256); function communityRatingLine() external view returns (uint256); } interface IACL { function accessible(address sender, address to, bytes4 sig) external view returns (bool); } interface IRating { function risk() external view returns (uint256); function fine() external view returns (bool); } contract Vote { using SafeMath for uint256; using SafeERC20 for IERC20; event MonitorEvent( address indexed who, address indexed bond, bytes32 indexed funcName, bytes ); function MonitorEventCallback(address who, address bond, bytes32 funcName, bytes calldata payload) external { emit MonitorEvent(who, bond, funcName, payload); } address public router; address public config; address public ACL; address public PRA; modifier auth { require( IACL(ACL).accessible(msg.sender, address(this), msg.sig), "Vote: access unauthorized" ); _; } constructor(address _ACL, address _router, address _config, address _PRA) public { router = _router; config = _config; ACL = _ACL; PRA = _PRA; } function setACL( address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } //专业评级时调用 function prcast(uint256 id, address proposal, uint256 reason) external { IBondData data = IBondData(IRouter(router).defaultDataContract(id)); require(data.voteExpired() > now, "vote is expired"); require( IPRA(PRA).raters(msg.sender), "sender is not a professional rater" ); IBondData.prwhat memory pr = data.pr(); require(pr.proposal == address(0), "already professional rating"); IBondData.what memory _what = data.votes(msg.sender); require(_what.proposal == address(0), "already community rating"); require(data.issuer() != msg.sender, "issuer can't vote for self bond"); require( IConfig(config).ratingCandidates(proposal), "proposal is not permissive" ); data.setPr(msg.sender, proposal, reason); emit MonitorEvent( msg.sender, address(data), "prcast", abi.encodePacked(proposal) ); } //仅能被 data.vote 回调, 社区投票时调用 function cast(uint256 id, address who, address proposal, uint256 amount) external auth { IBondData data = IBondData(IRouter(router).defaultDataContract(id)); require(data.voteExpired() > now, "vote is expired"); require(!IPRA(PRA).raters(who), "sender is a professional rater"); require(data.issuer() != who, "issuer can't vote for self bond"); require( IConfig(config).ratingCandidates(proposal), "proposal is not permissive" ); IBondData.what memory what = data.votes(who); address p = what.proposal; uint256 w = what.weight; //多次投票但是本次投票的提案与前次投票的提案不同 if (p != address(0) && p != proposal) { data.setBondParamMapping("weights", p, data.weights(p).sub(w)); data.setBondParamMapping("weights", proposal, data.weights(proposal).add(w)); } data.setVotes(who, proposal, w.add(amount)); data.setBondParamMapping("weights", proposal, data.weights(proposal).add(amount)); data.setBondParam("totalWeights", data.totalWeights().add(amount)); //同票数情况下后投出来的为胜 if (data.weights(proposal) >= data.weights(data.top())) { // data.setTop(proposal); data.setBondParamAddress("top", proposal); } } //仅能被 data.take 回调 function take(uint256 id, address who) external auth returns (uint256) { IBondData data = IBondData(IRouter(router).defaultDataContract(id)); require(now > data.voteExpired(), "vote is expired"); require(data.top() != address(0), "vote is not winner"); uint256 amount = data.voteLedger(who); return amount; } function rating(uint256 id) external { IBondData data = IBondData(IRouter(router).defaultDataContract(id)); require(now > data.voteExpired(), "vote unexpired"); uint256 _bondStage = data.bondStage(); require( _bondStage == uint256(BondStage.RiskRating), "already rating finished" ); uint256 totalWeights = data.totalWeights(); IBondData.prwhat memory pr = data.pr(); if ( totalWeights >= IConfig(config).communityRatingLine() && pr.proposal != address(0) ) { address top = data.top(); uint256 p = IConfig(config).professionalRatingWeightRatio(); //40% uint256 c = IConfig(config).communityRatingWeightRatio(); //60% uint256 pr_weights = totalWeights.mul(p).div(c); if (top != pr.proposal) { uint256 pr_proposal_weights = data.weights(pr.proposal).add( pr_weights ); if (data.weights(top) < pr_proposal_weights) { //data.setTop(pr.proposal); data.setBondParamAddress("top", pr.proposal); } //社区评级结果与专业评级的投票选项不同但权重相等时, 以风险低的为准 if (data.weights(top) == pr_proposal_weights) { data.setBondParamAddress("top", IRating(top).risk() < IRating(pr.proposal).risk() ? top : pr.proposal ); } } if(IRating(data.top()).fine()) { data.setBondParam("bondStage", uint256(BondStage.CrowdFunding)); data.setBondParam("investExpired", now + IConfig(config).investDuration()); data.setBondParam("bondExpired", now + IConfig(config).investDuration() + data.maturity()); } else { data.setBondParam("bondStage", uint256(BondStage.RiskRatingFail)); data.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawPawn)); } } else { data.setBondParam("bondStage", uint256(BondStage.RiskRatingFail)); data.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawPawn)); } emit MonitorEvent( msg.sender, address(data), "rating", abi.encodePacked(data.top(), data.weights(data.top())) ); } //取回后页面获得手续费保留原值不变 function profitOf(uint256 id, address who) public view returns (uint256) { IBondData data = IBondData(IRouter(router).defaultDataContract(id)); uint256 _bondStage = data.bondStage(); if ( _bondStage == uint256(BondStage.RepaySuccess) || _bondStage == uint256(BondStage.DebtClosed) ) { IBondData.what memory what = data.votes(who); IBondData.prwhat memory pr = data.pr(); uint256 p = IConfig(config).professionalRatingWeightRatio(); uint256 c = IConfig(config).communityRatingWeightRatio(); uint256 _fee = data.fee(); uint256 _profit = 0; if (pr.who != who) { if(what.proposal == address(0)) { return 0; } //以社区评级人身份投过票 //fee * c (0.6 * 1e18) * weights/totalweights; _profit = _fee.mul(c).mul(what.weight).div( data.totalWeights() ); } else { //who对本债券以专业评级人投过票 //fee * p (0.4 * 1e18); _profit = _fee.mul(p); } uint256 liability = data.liability(); //profit = profit * (1 - liability/originLiability); uint256 originLiability = data.originLiability(); _profit = _profit .mul(originLiability.sub(liability)) .div(originLiability) .div(1e18); return _profit; } return 0; } //取回评级收益,被bondData调用 function profit(uint256 id, address who) external auth returns (uint256) { IBondData data = IBondData(IRouter(router).defaultDataContract(id)); uint256 _bondStage = data.bondStage(); require( _bondStage == uint256(BondStage.RepaySuccess) || _bondStage == uint256(BondStage.DebtClosed), "bond is unrepay or unliquidate" ); require(data.profits(who) == 0, "voting profit withdrawed"); IBondData.prwhat memory pr = data.pr(); IBondData.what memory what = data.votes(who); require(what.proposal != address(0) || pr.who == who, "user is not rating vote"); uint256 _profit = profitOf(id, who); data.setBondParamMapping("profits", who, _profit); data.setBondParam("totalProfits", data.totalProfits().add(_profit)); return _profit; } } //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @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]. */ contract ReentrancyGuard { bool private _notEntered; constructor () 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.6.0; import "./SafeERC20.sol"; //professional rater authentication //专业评级认证 interface IACL { function accessible(address sender, address to, bytes4 sig) external view returns (bool); } contract PRA { using SafeERC20 for IERC20; using SafeMath for uint256; event MonitorEvent( address indexed who, address indexed bond, bytes32 indexed name, bytes ); address public ACL; address public gov; uint256 public line; struct Lock { uint256 amount; bool reviewed; } mapping(address => Lock) public deposits; mapping(address => bool) public raters; modifier auth { IACL _ACL = IACL(ACL); require( _ACL.accessible(msg.sender, address(this), msg.sig), "PRA: access unauthorized" ); _; } function setACL(address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } constructor(address _ACL, address _gov, uint256 _line) public { ACL = _ACL; gov = _gov; line = _line; } function reline(uint256 _line) external auth { line = _line; } //固定锁仓@line数量的代币 // SWC-Reentrancy: L66 - L80 function lock() external { address who = msg.sender; require(deposits[who].amount == 0, "sender already locked"); require( IERC20(gov).allowance(who, address(this)) >= line, "insufficient allowance to lock" ); require( IERC20(gov).balanceOf(who) >= line, "insufficient balance to lock" ); deposits[who].amount = line; IERC20(gov).safeTransferFrom(who, address(this), line); emit MonitorEvent(who, address(0), "lock", abi.encodePacked(line)); } function set(address who, bool enable) external auth { require(deposits[who].amount >= line, "insufficient deposit token"); if (enable) require( !raters[who], "set account already is a professional rater" ); deposits[who].reviewed = true; raters[who] = enable; emit MonitorEvent(who, address(0), "set", abi.encodePacked(enable)); } function unlock() external { address who = msg.sender; require(!raters[who], "raters is not broken"); require(deposits[who].reviewed, "not submitted for review"); uint256 amount = deposits[who].amount; deposits[who].reviewed = false; deposits[who].amount = 0; IERC20(gov).safeTransfer(who, amount); emit MonitorEvent(who, address(0), "unlock", abi.encodePacked(amount)); } } // File: ../../../../tmp/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.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: ../../../../tmp/openzeppelin-contracts/contracts/math/SafeMath.sol // pragma solidity ^0.6.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: ../../../../tmp/openzeppelin-contracts/contracts/utils/Address.sol // pragma solidity ^0.6.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is 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. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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 != accountHash && codehash != 0x0); } /** * @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-low-level-calls, avoid-call-value // (bool success, ) = recipient.call.value(amount)(""); // require(success, "Address: unable to send value, recipient may have reverted"); // } } // File: ../../../../tmp/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.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"); } } } pragma solidity ^0.6.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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IACL { function accessible(address sender, address to, bytes4 sig) external view returns (bool); } contract Config { address public ACL; constructor(address _ACL) public { ACL = _ACL; } modifier auth { require( IACL(ACL).accessible(msg.sender, address(this), msg.sig), "access unauthorized" ); _; } function setACL(address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } uint256 public voteDuration; uint256 public depositDuration; uint256 public investDuration; uint256 public gracePeriod; //宽限期 uint256 public ratingFeeRatio; //划分手续费中的投票收益占比 struct DepositTokenArgument { uint256 discount; //折扣 0.85 => 0.85 * 1e18 uint256 liquidateLine; //清算线 70% => 0.7 * 1e18 uint256 depositMultiple; //质押倍数 } struct IssueTokenArgument { uint256 partialLiquidateAmount; } struct IssueAmount { uint256 maxIssueAmount; //单笔债券最大发行数量 uint256 minIssueAmount; //单笔债券最小发行数量 } //deposit token => issuetoken => amount; mapping(address => mapping(address => IssueAmount)) public issueAmounts; mapping(address => DepositTokenArgument) public depositTokenArguments; mapping(address => IssueTokenArgument) public issueTokenArguments; function setRatingFeeRatio(uint256 ratio) external auth { ratingFeeRatio = ratio; } function setVoteDuration(uint256 sec) external auth { voteDuration = sec; } function setDepositDuration(uint256 sec) external auth { depositDuration = sec; } function setInvestDuration(uint256 sec) external auth { investDuration = sec; } function setGrasePeriod(uint256 period) external auth { gracePeriod = period; } function setDiscount(address token, uint256 discount) external auth { depositTokenArguments[token].discount = discount; } function discount(address token) external view returns (uint256) { return depositTokenArguments[token].discount; } function setLiquidateLine(address token, uint256 line) external auth { depositTokenArguments[token].liquidateLine = line; } function liquidateLine(address token) external view returns (uint256) { return depositTokenArguments[token].liquidateLine; } function setDepositMultiple(address token, uint256 depositMultiple) external auth { depositTokenArguments[token].depositMultiple = depositMultiple; } function depositMultiple(address token) external view returns (uint256) { return depositTokenArguments[token].depositMultiple; } function setMaxIssueAmount( address depositToken, address issueToken, uint256 maxIssueAmount ) external auth { issueAmounts[depositToken][issueToken].maxIssueAmount = maxIssueAmount; } function maxIssueAmount(address depositToken, address issueToken) external view returns (uint256) { return issueAmounts[depositToken][issueToken].maxIssueAmount; } function setMinIssueAmount( address depositToken, address issueToken, uint256 minIssueAmount ) external auth { issueAmounts[depositToken][issueToken].minIssueAmount = minIssueAmount; } function minIssueAmount(address depositToken, address issueToken) external view returns (uint256) { return issueAmounts[depositToken][issueToken].minIssueAmount; } function setPartialLiquidateAmount( address token, uint256 _partialLiquidateAmount ) external auth { issueTokenArguments[token] .partialLiquidateAmount = _partialLiquidateAmount; } function partialLiquidateAmount(address token) external view returns (uint256) { return issueTokenArguments[token].partialLiquidateAmount; } uint256 public professionalRatingWeightRatio; // professional-Rating Weight Ratio; uint256 public communityRatingWeightRatio; // community-Rating Weight Ratio; function setProfessionalRatingWeightRatio( uint256 _professionalRatingWeightRatio ) external auth { professionalRatingWeightRatio = _professionalRatingWeightRatio; } function setCommunityRatingWeightRatio(uint256 _communityRatingWeightRatio) external auth { communityRatingWeightRatio = _communityRatingWeightRatio; } /** verify */ //支持发债的代币列表 mapping(address => bool) public depositTokenCandidates; //支持融资的代币列表 mapping(address => bool) public issueTokenCandidates; //发行费用 mapping(uint256 => bool) public issueFeeCandidates; //一期的利率 mapping(uint256 => bool) public interestRateCandidates; //债券期限 mapping(uint256 => bool) public maturityCandidates; //最低发行比率 mapping(uint256 => bool) public minIssueRatioCandidates; //可评级的地址选项 mapping(address => bool) public ratingCandidates; function setDepositTokenCandidates(address[] calldata tokens, bool enable) external auth { for (uint256 i = 0; i < tokens.length; ++i) { depositTokenCandidates[tokens[i]] = enable; } } function setIssueTokenCandidates(address[] calldata tokens, bool enable) external auth { for (uint256 i = 0; i < tokens.length; ++i) { issueTokenCandidates[tokens[i]] = enable; } } function setIssueFeeCandidates(uint256[] calldata issueFees, bool enable) external auth { for (uint256 i = 0; i < issueFees.length; ++i) { issueFeeCandidates[issueFees[i]] = enable; } } function setInterestRateCandidates( uint256[] calldata interestRates, bool enable ) external auth { for (uint256 i = 0; i < interestRates.length; ++i) { interestRateCandidates[interestRates[i]] = enable; } } function setMaturityCandidates(uint256[] calldata maturities, bool enable) external auth { for (uint256 i = 0; i < maturities.length; ++i) { maturityCandidates[maturities[i]] = enable; } } function setMinIssueRatioCandidates( uint256[] calldata minIssueRatios, bool enable ) external auth { for (uint256 i = 0; i < minIssueRatios.length; ++i) { minIssueRatioCandidates[minIssueRatios[i]] = enable; } } function setRatingCandidates(address[] calldata proposals, bool enable) external auth { for (uint256 i = 0; i < proposals.length; ++i) { ratingCandidates[proposals[i]] = enable; } } address public gov; function setGov(address _gov) external auth { gov = _gov; } uint256 public communityRatingLine; function setCommunityRatingLine(uint256 _communityRatingLine) external auth { communityRatingLine = _communityRatingLine; } } /** *Submitted for verification at Etherscan.io on 2020-04-03 */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /* * @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 { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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); } 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; } } library Address { /** * @dev Returns true if `account` is 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. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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 != accountHash && codehash != 0x0); } /** * @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-low-level-calls, avoid-call-value // (bool success, ) = recipient.call.value(amount)(""); // require(success, "Address: unable to send value, recipient may have reverted"); // } } 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"); } } } /** * @dev Optional functions from the ERC20 standard. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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. * * 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 returns (uint8) { return _decimals; } } /** * @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 {ERC20Mintable}. * * 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 guidelines: functions revert instead * of 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 ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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].add(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) { // _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); // return true; // } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(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 * * - `to` 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 = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(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); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ // function _burnFrom(address account, uint256 amount) internal virtual { // _burn(account, amount); // _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); // } /** * @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 to 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:using-hooks.adoc[Using Hooks]. */ // function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: ../../../../tmp/openzeppelin-contracts/contracts/token/ERC20/ERC20Burnable.sol // pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ // function burnFrom(address account, uint256 amount) public virtual { // _burnFrom(account, amount); // } } pragma solidity ^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; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ERC20lib.sol"; import "./ReentrancyGuard.sol"; interface ICore { function initialDepositCb(uint256 id, uint256 amount) external; function depositCb(address who, uint256 id, uint256 amount) external returns (bool); function investCb(address who, uint256 id, uint256 amount) external returns (bool); function interestBearingPeriod(uint256 id) external returns (bool); function txOutCrowdCb(address who, uint256 id) external returns (uint); function repayCb(address who, uint256 id) external returns (uint); function withdrawPawnCb(address who, uint256 id) external returns (uint); function withdrawPrincipalCb(address who, uint id) external returns (uint); function withdrawPrincipalAndInterestCb(address who, uint id) external returns (uint); function liquidateCb(address who, uint id, uint liquidateAmount) external returns (uint, uint, uint, uint); function overdueCb(uint256 id) external; function withdrawSysProfitCb(address who, uint256 id) external returns (uint256); function updateBalance( uint256 id, address sender, address recipient, uint256 bondAmount ) external; function MonitorEventCallback(address who, address bond, bytes32 funcName, bytes calldata) external; } interface IVote { function take(uint256 id, address who) external returns(uint256); function cast(uint256 id, address who, address proposal, uint256 amount) external; function profit(uint256 id, address who) external returns(uint256); } interface IACL { function accessible(address sender, address to, bytes4 sig) external view returns (bool); function enableany(address from, address to) external; function enableboth(address from, address to) external; } contract BondData is ERC20Detailed, ERC20Burnable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; address public logic; constructor( address _ACL, uint256 bondId, string memory _bondName, address _issuer, address _collateralToken, address _crowdToken, uint256[8] memory info, bool[2] memory _redeemPutback //是否支持赎回和回售 ) public ERC20Detailed(_bondName, _bondName, 0) { ACL = _ACL; id = bondId; issuer = _issuer; collateralToken = _collateralToken; crowdToken = _crowdToken; totalBondIssuance = info[0]; couponRate = info[1]; maturity = info[2]; issueFee = info[3]; minIssueRatio = info[4]; financePurposeHash = info[5]; paymentSourceHash = info[6]; issueTimestamp = info[7]; supportRedeem = _redeemPutback[0]; supportPutback = _redeemPutback[1]; par = 100; } /** ACL */ address public ACL; modifier auth { IACL _ACL = IACL(ACL); require( _ACL.accessible(msg.sender, address(this), msg.sig) , "bondData: access unauthorized"); _; } /** 债券基本信息 */ uint256 public id; address public issuer; //发债方 address public collateralToken; //质押代币 address public crowdToken; //融资代币地址 uint256 public totalBondIssuance; //预计发行量,债券发行总量,以USDT计 uint256 public actualBondIssuance; //实际发行份数 uint256 public mintCnt;//增发的次数 uint256 public par; //票面价值(面值),USDT or DAI uint256 public couponRate; //票面利率;息票利率 15% uint256 public maturity; //债券期限,到期日,债券期限(30天) uint256 public issueFee; //发行费用,0.2% uint256 public minIssueRatio; //最低融资比率 uint256 public financePurposeHash; uint256 public paymentSourceHash; uint256 public issueTimestamp;//申请发债时间 bool public supportRedeem;//是否支持赎回 bool public supportPutback;//是否支持回售 //分批清算的参数设置,设置最后剩余清算额度为1000单位,当最后剩余清算额度<1000时,用户需一次性清算完毕。 uint256 public partialLiquidateAmount; uint256 public discount; //清算折扣,系统设定,非发行方提交 uint256 public liquidateLine = 7e17;//质押资产价值下跌30%时进行清算 1-0.3 = 0.7 uint256 public gracePeriod = 1 days; //债务宽限期 uint256 public depositMultiple; /** 债券状态时间线 */ uint256 public voteExpired; //债券投票截止时间 uint256 public investExpired; //用户购买债券截止时间 uint256 public bondExpired; //债券到期日 /** 债券创建者/投资者信息 */ struct Balance { //发行者: //amountGive: 质押的token数量,项目方代币 //amountGet: 募集的token数量,USDT,USDC //投资者: //amountGive: 投资的token数量,USDT,USDC //amountGet: 债券凭证数量 uint256 amountGive; uint256 amountGet; } //1个发行人 uint256 public issuerBalanceGive; //多个投资人 mapping(address => Balance) public supplyMap; //usr->supply /** 债券配置对象 */ uint256 public fee; uint256 public sysProfit;//平台盈利,为手续费的分成 //债务加利息 uint256 public liability; uint256 public originLiability; //状态: uint256 public bondStage; uint256 public issuerStage; function setLogics(address _logic, address _voteLogic) external auth { logic = _logic; voteLogic = _voteLogic; } function setBondParam(bytes32 k, uint256 v) external auth { if (k == bytes32("discount")) { discount = v; } if (k == bytes32("liquidateLine")) { liquidateLine = v; } if (k == bytes32("depositMultiple")) { depositMultiple = v; } if (k == bytes32("gracePeriod")) { gracePeriod = v; } if (k == bytes32("voteExpired")) { voteExpired = v; } if (k == bytes32("investExpired")) { investExpired = v; } if (k == bytes32("bondExpired")) { bondExpired = v; } if (k == bytes32("partialLiquidateAmount")) { partialLiquidateAmount = v; } if (k == bytes32("fee")) { fee = v; } if (k == bytes32("sysProfit")) { sysProfit = v; } if (k == bytes32("originLiability")) { originLiability = v; } if (k == bytes32("liability")) { liability = v; } if (k == bytes32("totalWeights")) { totalWeights = v; } if (k == bytes32("totalProfits")) { totalProfits = v; } if (k == bytes32("borrowAmountGive")) { issuerBalanceGive = v; } if (k == bytes32("bondStage")) { bondStage = v; } if (k == bytes32("issuerStage")) { issuerStage = v; } } function setBondParamAddress(bytes32 k, address v) external auth { if (k == bytes32("gov")) { gov = v; } if (k == bytes32("top")) { top = v; } } function getSupplyAmount(address who) external view returns (uint256, uint256) { return (supplyMap[who].amountGive, supplyMap[who].amountGet); } function getBorrowAmountGive() external view returns (uint256) { return issuerBalanceGive; } function setSupply(address who, uint256 amountGive, uint256 amountGet) external auth { supplyMap[who].amountGive = amountGive; supplyMap[who].amountGet = amountGet; } /** 清算记录流水号 */ uint256 public liquidateIndexes; /** 分批清算设置标记 */ bool public liquidating; function setLiquidating(bool _liquidating) external auth { liquidating = _liquidating; } /** 评级 */ address public voteLogic; struct what { address proposal; uint256 weight; } struct prwhat { address who; address proposal; uint256 reason; } mapping(address => uint256) public voteLedger; //who => amount mapping(address => what) public votes; //who => what mapping(address => uint256) public weights; //proposal => weight mapping(address => uint256) public profits; //who => profit uint256 public totalProfits; //累计已经被取走的投票收益, 用于对照 @fee. uint256 public totalWeights; address public gov; address public top; prwhat public pr; function setVotes(address who, address proposal, uint256 weight) external auth { votes[who].proposal = proposal; votes[who].weight = weight; } function setACL( address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } function setPr(address who, address proposal, uint256 reason) external auth { pr.who = who; pr.proposal = proposal; pr.reason = reason; } function setBondParamMapping(bytes32 name, address k, uint256 v) external auth { if (name == bytes32("weights")) { weights[k] = v; } if (name == bytes32("profits")) { profits[k] = v; } } function vote(address proposal, uint256 amount) external nonReentrant { IVote(voteLogic).cast(id, msg.sender, proposal, amount); voteLedger[msg.sender] = voteLedger[msg.sender].add(amount); IERC20(gov).safeTransferFrom(msg.sender, address(this), amount); ICore(logic).MonitorEventCallback(msg.sender, address(this), "vote", abi.encodePacked( proposal, amount, IERC20(gov).balanceOf(address(this)) )); } function take() external nonReentrant { uint256 amount = IVote(voteLogic).take(id, msg.sender); voteLedger[msg.sender] = voteLedger[msg.sender].sub(amount); IERC20(gov).safeTransfer(msg.sender, amount); ICore(logic).MonitorEventCallback(msg.sender, address(this), "take", abi.encodePacked( amount, IERC20(gov).balanceOf(address(this)) )); } function profit() external nonReentrant { uint256 _profit = IVote(voteLogic).profit(id, msg.sender); IERC20(crowdToken).safeTransfer(msg.sender, _profit); ICore(logic).MonitorEventCallback(msg.sender, address(this), "profit", abi.encodePacked( _profit, IERC20(crowdToken).balanceOf(address(this)) )); } function withdrawSysProfit() external nonReentrant auth { uint256 _sysProfit = ICore(logic).withdrawSysProfitCb(msg.sender, id); IERC20(crowdToken).safeTransfer(msg.sender, _sysProfit); ICore(logic).MonitorEventCallback(msg.sender, address(this), "withdrawSysProfit", abi.encodePacked( _sysProfit, IERC20(crowdToken).balanceOf(address(this)) )); } function safeTransferFrom( address token, address owner, address spender, address to, uint256 amount ) internal { require(amount > 0, "invalid safeTransferFrom amount"); if (owner != spender) { IERC20(token).safeTransferFrom(owner, to, amount); } else { IERC20(token).safeTransfer(to, amount); } } function burnBond(address who, uint256 amount) external auth { _burn(who, amount); actualBondIssuance = actualBondIssuance.sub(amount); } function mintBond(address who, uint256 amount) external auth { _mint(who, amount); mintCnt = mintCnt.add(amount); actualBondIssuance = actualBondIssuance.add(amount); } function transfer(address recipient, uint256 bondAmount) public override(IERC20, ERC20) returns (bool) { ICore(logic).updateBalance(id, msg.sender, recipient, bondAmount); ERC20.transfer(recipient, bondAmount); ICore(logic).MonitorEventCallback(msg.sender, address(this), "transfer", abi.encodePacked( recipient, bondAmount )); return true; } function transferFrom(address sender, address recipient, uint256 bondAmount) public override(IERC20, ERC20) returns (bool) { ICore(logic).updateBalance(id, sender, recipient, bondAmount); ERC20.transferFrom(sender, recipient, bondAmount); ICore(logic).MonitorEventCallback(sender, address(this), "transferFrom", abi.encodePacked( recipient, bondAmount )); return true; } mapping(address => uint256) public depositLedger; mapping(address => uint256) public investLedger; //可转出金额,募集到的总资金减去给所有投票人的手续费 function transferableAmount() public view returns (uint256) { uint256 baseDec = 18; uint256 delta = baseDec.sub( uint256(ERC20Detailed(crowdToken).decimals()) ); uint256 _1 = 1 ether; //principal * (1-0.05) * 1e18/(10** (18 - 6)) return actualBondIssuance.mul(par).mul((_1).sub(issueFee)).div( 10**delta ); } //追加抵押物 function deposit(uint256 amount) external nonReentrant { if (ICore(logic).depositCb(msg.sender, id, amount)) { depositLedger[msg.sender] = depositLedger[msg.sender].add(amount); safeTransferFrom( collateralToken, msg.sender, address(this), address(this), amount ); } ICore(logic).MonitorEventCallback(msg.sender, address(this), "deposit", abi.encodePacked( amount, IERC20(collateralToken).balanceOf(address(this)) )); } //首次加入抵押物 function initialDeposit(address who, uint256 amount) external auth nonReentrant { depositLedger[who] = depositLedger[who].add(amount); safeTransferFrom( collateralToken, msg.sender, address(this), address(this), amount ); ICore(logic).initialDepositCb(id, amount); ICore(logic).MonitorEventCallback(who, address(this), "initialDeposit", abi.encodePacked( amount, IERC20(collateralToken).balanceOf(address(this)) )); } function invest(uint256 amount) external nonReentrant { if (ICore(logic).investCb(msg.sender, id, amount)) { investLedger[msg.sender] = investLedger[msg.sender].add(amount); //充值amount token到合约中,充值之前需要approve safeTransferFrom( crowdToken, msg.sender, address(this), address(this), amount ); } ICore(logic).MonitorEventCallback(msg.sender, address(this), "invest", abi.encodePacked( amount, IERC20(crowdToken).balanceOf(address(this)) )); } function txOutCrowd() external nonReentrant { uint256 balance = ICore(logic).txOutCrowdCb(msg.sender, id); require(balance <= transferableAmount(), "exceed max tx amount"); safeTransferFrom( crowdToken, address(this), address(this), msg.sender, balance ); ICore(logic).MonitorEventCallback(msg.sender, address(this), "txOutCrowd", abi.encodePacked( balance, IERC20(crowdToken).balanceOf(address(this)) )); } function overdue() external { ICore(logic).overdueCb(id); } function repay() external nonReentrant { uint repayAmount = ICore(logic).repayCb(msg.sender, id); safeTransferFrom( crowdToken, msg.sender, address(this), address(this), repayAmount ); ICore(logic).MonitorEventCallback(msg.sender, address(this), "repay", abi.encodePacked( repayAmount, IERC20(crowdToken).balanceOf(address(this)) )); } function withdrawPawn() external nonReentrant { uint amount = ICore(logic).withdrawPawnCb(msg.sender, id); require(amount <= depositLedger[msg.sender], "exceed max pawn amount"); depositLedger[msg.sender] = depositLedger[msg.sender].sub(amount); safeTransferFrom( collateralToken, address(this), address(this), msg.sender, amount ); ICore(logic).MonitorEventCallback(msg.sender, address(this), "withdrawPawn", abi.encodePacked( amount, IERC20(collateralToken).balanceOf(address(this)) )); } function withdrawPrincipal() external nonReentrant { uint256 supplyGive = ICore(logic).withdrawPrincipalCb(msg.sender, id); require(supplyGive <= investLedger[msg.sender], "exceed max principal amount"); investLedger[msg.sender] = investLedger[msg.sender].sub(supplyGive); safeTransferFrom( crowdToken, address(this), address(this), msg.sender, supplyGive ); ICore(logic).MonitorEventCallback(msg.sender, address(this), "withdrawPrincipal", abi.encodePacked( supplyGive, IERC20(crowdToken).balanceOf(address(this)) )); } function withdrawPrincipalAndInterest() external nonReentrant { uint256 amount = ICore(logic).withdrawPrincipalAndInterestCb(msg.sender, id); uint256 _1 = 1 ether; uint256 maxAmount = investLedger[msg.sender].mul(_1.add(couponRate)).div(_1); require(amount <= maxAmount && investLedger[msg.sender] != 0, "exceed max invest amount or not an invester"); investLedger[msg.sender] = 0; safeTransferFrom( crowdToken, address(this), address(this), msg.sender, amount ); ICore(logic).MonitorEventCallback(msg.sender, address(this), "withdrawPrincipalAndInterest", abi.encodePacked( amount, IERC20(crowdToken).balanceOf(address(this)) )); } //分批清算,y为债务 function liquidate(uint liquidateAmount) external nonReentrant { (uint y1, uint x1, uint y, uint x) = ICore(logic).liquidateCb(msg.sender, id, liquidateAmount); safeTransferFrom( collateralToken, address(this), address(this), msg.sender, x1 ); safeTransferFrom( crowdToken, msg.sender, address(this), address(this), y1 ); ICore(logic).MonitorEventCallback(msg.sender, address(this), "liquidate", abi.encodePacked( liquidateIndexes, x1, y1, x, y, now, IERC20(collateralToken).balanceOf(address(this)), IERC20(crowdToken).balanceOf(address(this)) )); liquidateIndexes = liquidateIndexes.add(1); } } /* * Copyright (c) The Force Protocol Development Team */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IRouter.sol"; import "./BondData.sol"; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20Detailed { function symbol() external view returns (string memory); } interface INameGen { function gen(string calldata symbol, uint id) external view returns (string memory); } interface IVerify { function verify(address[2] calldata, uint256[8] calldata) external view returns (bool); } contract BondFactory { using SafeERC20 for IERC20; address public router; address public verify; address public vote; address public core; address public nameGen; address public ACL; constructor( address _ACL, address _router, address _verify, address _vote, address _core, address _nameGen ) public { ACL = _ACL; router = _router; verify = _verify; vote = _vote; core = _core; nameGen = _nameGen; } function setACL(address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } //提交发债信息,new BondData //tokens[0]: _collateralToken //tokens[1]: _crowdToken //info[0]: _totalBondIssuance //info[1]: _couponRate, //一期的利率 //info[2]: _maturity, //秒数 //info[3]: _issueFee //info[4]: _minIssueRatio //info[5]: _financePurposeHash,//融资用途hash //info[6]: _paymentSourceHash,//还款来源hash //info[7]: _issueTimestamp,//发债时间 //_redeemPutback[0]: _supportRedeem, //_redeemPutback[1]: _supportPutback function issue( address[2] calldata tokens, uint256 _minCollateralAmount, uint256[8] calldata info, bool[2] calldata _redeemPutback ) external returns (uint256) { require(IVerify(verify).verify(tokens, info), "verify error"); uint256 nr = IRouter(router).bondNr(); string memory bondName = INameGen(nameGen).gen(IERC20Detailed(tokens[0]).symbol(), nr); BondData b = new BondData( ACL, nr, bondName, msg.sender, tokens[0], tokens[1], info, _redeemPutback ); IRouter(router).setDefaultContract(nr, address(b)); IRouter(router).setBondNr(nr + 1); IACL(ACL).enableany(address(this), address(b)); IACL(ACL).enableboth(core, address(b)); IACL(ACL).enableboth(vote, address(b)); b.setLogics(core, vote); //合约划转用户的币到用户的bondData合约中 IERC20(tokens[0]).safeTransferFrom(msg.sender, address(this), _minCollateralAmount); IERC20(tokens[0]).safeApprove(address(b), _minCollateralAmount); b.initialDeposit(msg.sender, _minCollateralAmount); return nr; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IACL { function accessible(address sender, address to, bytes4 sig) external view returns (bool); } contract Oracle { address public ACL; constructor (address _ACL) public { ACL = _ACL; } modifier auth { require(IACL(ACL).accessible(msg.sender, address(this), msg.sig), "access unauthorized"); _; } function setACL( address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } struct Price { uint price; uint expiration; } mapping (address => Price) public prices; function getExpiration(address token) external view returns (uint) { return prices[token].expiration; } function getPrice(address token) external view returns (uint) { return prices[token].price; } function get(address token) external view returns (uint, bool) { return (prices[token].price, valid(token)); } function valid(address token) public view returns (bool) { return now < prices[token].expiration; } // 设置价格为 @val, 保持有效时间为 @exp second. function set(address token, uint val, uint exp) external auth { prices[token].price = val; prices[token].expiration = now + exp; } //批量设置,减少gas使用 function batchSet(address[] calldata tokens, uint[] calldata vals, uint[] calldata exps) external auth { uint nToken = tokens.length; require(nToken == vals.length && vals.length == exps.length, "invalid array length"); for (uint i = 0; i < nToken; ++i) { prices[tokens[i]].price = vals[i]; prices[tokens[i]].expiration = now + exps[i]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ERC20lib.sol"; import "./IRouter.sol"; import "./StageDefine.sol"; import "./IBondData.sol"; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20Detailed { function decimals() external view returns (uint8); function symbol() external view returns (string memory); } interface IOracle { function get(address t) external view returns (uint, bool); } contract CoreUtils { using SafeMath for uint256; address public router; address public oracle; constructor (address _router, address _oracle) public { router = _router; oracle = _oracle; } function d(uint256 id) public view returns (address) { return IRouter(router).defaultDataContract(id); } function bondData(uint256 id) public view returns (IBondData) { return IBondData(d(id)); } //principal + interest = principal * (1 + couponRate); function calcPrincipalAndInterest(uint256 principal, uint256 couponRate) public pure returns (uint256) { uint256 _1 = 1 ether; return principal.mul(_1.add(couponRate)).div(_1); } //可转出金额,募集到的总资金减去给所有投票人的手续费 function transferableAmount(uint256 id) external view returns (uint256) { IBondData b = bondData(id); uint256 baseDec = 18; uint256 delta = baseDec.sub( uint256(ERC20Detailed(b.crowdToken()).decimals()) ); uint256 _1 = 1 ether; //principal * (1-0.05) * 1e18/(10** (18 - 6)) return b.actualBondIssuance().mul(b.par()).mul((_1).sub(b.issueFee())).div( 10**delta ); } //总的募集资金量 function debt(uint256 id) external view returns (uint256) { IBondData b = bondData(id); uint256 crowdDec = ERC20Detailed(b.crowdToken()).decimals(); return b.actualBondIssuance().mul(b.par()).mul(10**crowdDec); } //总的募集资金量 function totalInterest(uint256 id) external view returns (uint256) { IBondData b = bondData(id); uint256 crowdDec = ERC20Detailed(b.crowdToken()).decimals(); return b .actualBondIssuance() .mul(b.par()) .mul(10**crowdDec) .mul(b.couponRate()) .div(1e18); } function debtPlusTotalInterest(uint256 id) public view returns (uint256) { IBondData b = bondData(id); uint256 crowdDec = ERC20Detailed(b.crowdToken()).decimals(); uint256 _1 = 1 ether; return b .actualBondIssuance() .mul(b.par()) .mul(10**crowdDec) .mul(_1.add(b.couponRate())) .div(1e18); } //可投资的剩余份数 function remainInvestAmount(uint256 id) external view returns (uint256) { IBondData b = bondData(id); uint256 crowdDec = ERC20Detailed(b.crowdToken()).decimals(); return b.totalBondIssuance().div(10**crowdDec).div(b.par()).sub( b.actualBondIssuance() ); } function calcMinCollateralTokenAmount(uint256 id) external view returns (uint256) { IBondData b = bondData(id); uint256 CollateralDec = ERC20Detailed(b.collateralToken()).decimals(); uint256 crowdDec = ERC20Detailed(b.crowdToken()).decimals(); uint256 unitCollateral = 10**CollateralDec; uint256 unitCrowd = 10**crowdDec; return b .totalBondIssuance() .mul(b.depositMultiple()) .mul(crowdPrice(id)) .mul(unitCollateral) .div(pawnPrice(id)) .div(unitCrowd); } function pawnBalanceInUsd(uint256 id) public view returns (uint256) { IBondData b = bondData(id); uint256 unitPawn = 10 ** uint256(ERC20Detailed(b.collateralToken()).decimals()); uint256 pawnUsd = pawnPrice(id).mul(b.getBorrowAmountGive()).div(unitPawn); //1e18 return pawnUsd; } function disCountPawnBalanceInUsd(uint256 id) public view returns (uint256) { uint256 _1 = 1 ether; IBondData b = bondData(id); return pawnBalanceInUsd(id).mul(b.discount()).div(_1); } function crowdBalanceInUsd(uint256 id) public view returns (uint256) { IBondData b = bondData(id); uint256 unitCrowd = 10 ** uint256(ERC20Detailed(b.crowdToken()).decimals()); return crowdPrice(id).mul(b.liability()).div(unitCrowd); } //资不抵债判断,资不抵债时,为true,否则为false function isInsolvency(uint256 id) public view returns (bool) { return disCountPawnBalanceInUsd(id) < crowdBalanceInUsd(id); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } //获取质押的代币价格 function pawnPrice(uint256 id) public view returns (uint256) { IBondData b = bondData(id); (uint256 price, bool pawnPriceOk) = IOracle(oracle).get(b.collateralToken()); require(pawnPriceOk, "invalid pawn price"); return price; } //获取募资的代币价格 function crowdPrice(uint256 id) public view returns (uint256) { IBondData b = bondData(id); (uint256 price, bool crowdPriceOk) = IOracle(oracle).get(b.crowdToken()); require(crowdPriceOk, "invalid crowd price"); return price; } //要清算的质押物数量 //X = (AC*price - PCR*PD)/(price*(1-PCR*Discount)) //X = (PCR*PD - AC*price)/(price*(PCR*Discount-1)) function X(uint256 id) public view returns (uint256 res) { IBondData b = bondData(id); if (!isUnsafe(id)) { return 0; } //若质押资产不能清偿债务,全额清算 if (isInsolvency(id)) { return b.getBorrowAmountGive(); } //逾期未还款 if (now >= b.bondExpired().add(b.gracePeriod())) { return calcLiquidatePawnAmount(id); } uint256 _1 = 1 ether; uint256 price = pawnPrice(id); //1e18 uint256 pawnUsd = pawnBalanceInUsd(id); uint256 debtUsd = crowdBalanceInUsd(id).mul(b.depositMultiple()); uint256 gap = pawnUsd >= debtUsd ? pawnUsd.sub(debtUsd) : debtUsd.sub(pawnUsd); uint256 pcrXdis = b.depositMultiple().mul(b.discount()); //1e18 require(pcrXdis != _1, "PCR*Discout == 1 error"); pcrXdis = pawnUsd >= debtUsd ? _1.sub(pcrXdis) : pcrXdis.sub(_1); uint256 denominator = price.mul(pcrXdis).div(_1); //1e18 uint256 unitPawn = 10 ** uint256(ERC20Detailed(b.collateralToken()).decimals()); res = gap.mul(unitPawn).div(denominator); //1e18/1e18*1e18 == 1e18 res = min(res, b.getBorrowAmountGive()); } //清算额,减少的债务 //X*price(collater)*Discount/price(crowd) function Y(uint256 id) public view returns (uint256 res) { IBondData b = bondData(id); if (!isUnsafe(id)) { return 0; } uint256 _1 = 1 ether; uint256 unitPawn = 10 ** uint256(ERC20Detailed(b.collateralToken()).decimals()); uint256 xp = X(id).mul(pawnPrice(id)).div(unitPawn); xp = xp.mul(b.discount()).div(_1); uint256 unitCrowd = 10 ** uint256(ERC20Detailed(b.crowdToken()).decimals()); res = xp.mul(unitCrowd).div(crowdPrice(id)); res = min(res, b.liability()); } //到期后,由系统债务算出需要清算的抵押物数量 function calcLiquidatePawnAmount(uint256 id) public view returns (uint256) { IBondData b = bondData(id); return calcLiquidatePawnAmount(id, b.liability()); } //return ((a + m - 1) / m) * m; function ceil(uint256 a, uint256 m) public pure returns (uint256) { return (a.add(m).sub(1)).div(m).mul(m); } function precision(uint256 id) public view returns (uint256) { IBondData b = bondData(id); uint256 decCrowd = uint256(ERC20Detailed(b.crowdToken()).decimals()); uint256 decPawn = uint256(ERC20Detailed(b.collateralToken()).decimals()); if (decPawn != decCrowd) { return 10 ** (abs(decPawn, decCrowd).add(1)); } return 10; } function ceilPawn(uint256 id, uint256 a) public view returns (uint256) { IBondData b = bondData(id); uint256 decCrowd = uint256(ERC20Detailed(b.crowdToken()).decimals()); uint256 decPawn = uint256(ERC20Detailed(b.collateralToken()).decimals()); if (decPawn != decCrowd) { a = ceil(a, 10 ** abs(decPawn, decCrowd).sub(1)); } else { a = ceil(a, 10); } return a; } //到期后,由系统债务算出需要清算的抵押物数量 function calcLiquidatePawnAmount(uint256 id, uint256 liability) public view returns (uint256) { IBondData b = bondData(id); uint256 _crowdPrice = crowdPrice(id); uint256 _pawnPrice = pawnPrice(id); uint256 x = liability .mul(_crowdPrice) .mul(1 ether) .mul(10**uint256(ERC20Detailed(b.collateralToken()).decimals())) .div(10**uint256(ERC20Detailed(b.crowdToken()).decimals())) .div(_pawnPrice.mul(b.discount())); uint256 decCrowd = uint256(ERC20Detailed(b.crowdToken()).decimals()); uint256 decPawn = uint256(ERC20Detailed(b.collateralToken()).decimals()); if (decPawn != decCrowd) { x = ceil(x, 10 ** abs(decPawn, decCrowd).sub(1)); } else { x = ceil(x, 10); } x = min(x, b.getBorrowAmountGive()); if (x < b.getBorrowAmountGive()) { if (abs(x, b.getBorrowAmountGive()) <= precision(id)) { x = b.getBorrowAmountGive();//资不抵债情况 } } return x; } function investPrincipalWithInterest(uint256 id, address who) external view returns (uint256) { require(d(id) != address(0), "invalid address"); IBondData bond = bondData(id); address give = bond.crowdToken(); (uint256 supplyGive, uint256 _) = bond.getSupplyAmount(who); uint256 bondAmount = convert2BondAmount( address(bond), give, supplyGive ); uint256 crowdDec = IERC20Detailed(bond.crowdToken()).decimals(); uint256 unrepayAmount = bond.liability(); //未还的债务 uint256 actualRepay; if (unrepayAmount == 0) { actualRepay = calcPrincipalAndInterest( bondAmount.mul(1e18), bond.couponRate() ); actualRepay = actualRepay.mul(bond.par()).mul(10**crowdDec).div( 1e18 ); } else { //计算投资占比分之一,投资人亏损情况,从已还款(总债务-未还债务)中按比例分 uint256 debtTotal = debtPlusTotalInterest(id); require( debtTotal >= unrepayAmount, "debtPlusTotalInterest < borrowGet, overflow" ); actualRepay = debtTotal .sub(unrepayAmount) .mul(bondAmount) .div(bond.actualBondIssuance()); } return actualRepay; } //bond: function convert2BondAmount(address b, address t, uint256 amount) public view returns (uint256) { IERC20Detailed erc20 = IERC20Detailed(t); uint256 dec = uint256(erc20.decimals()); uint256 _par = IBondData(b).par(); uint256 minAmount = _par.mul(10**dec); require(amount.mod(minAmount) == 0, "invalid amount"); //投资时,必须按份买 return amount.div(minAmount); } function abs(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a >= b ? a.sub(b) : b.sub(a); } //bond: function convert2GiveAmount(uint256 id, uint256 bondAmount) external view returns (uint256) { IBondData b = bondData(id); ERC20Detailed erc20 = ERC20Detailed(b.crowdToken()); uint256 dec = uint256(erc20.decimals()); return bondAmount.mul(b.par()).mul(10**dec); } //判断是否回到原始质押率(400%),回到后,设置为false,否则为true function isDepositMultipleUnsafe(uint256 id) external view returns (bool unsafe) { IBondData b = bondData(id); if (b.liability() == 0 || b.getBorrowAmountGive() == 0) { return false; } if (b.bondStage() == uint(BondStage.CrowdFundingSuccess) || b.bondStage() == uint(BondStage.UnRepay) || b.bondStage() == uint(BondStage.Overdue)) { if (now >= b.bondExpired().add(b.gracePeriod())) { return true; } uint256 _1 = 1 ether; uint256 crowdUsdxLeverage = crowdBalanceInUsd(id) .mul(b.depositMultiple()) .div(_1); //CCR < 4 //pawnUsd/crowdUsd < 4 //unsafe = pawnBalanceInUsd(id) < crowdUsdxLeverage; uint256 _ceilPawn = ceilPawn(id, pawnBalanceInUsd(id)); uint256 _crowdPrice = crowdPrice(id); uint256 decCrowd = uint256(ERC20Detailed(b.crowdToken()).decimals()); uint256 minCrowdInUsd = _crowdPrice.div(10 ** decCrowd); unsafe = _ceilPawn < crowdUsdxLeverage; if (abs(_ceilPawn, crowdUsdxLeverage) <= minCrowdInUsd && _ceilPawn < crowdUsdxLeverage) { unsafe = false; } return unsafe; } return false; } function isUnsafe(uint256 id) public view returns (bool unsafe) { IBondData b = bondData(id); uint256 decCrowd = uint256(ERC20Detailed(b.crowdToken()).decimals()); uint256 _crowdPrice = crowdPrice(id); //1e15 is 0.001$ if (b.liability().mul(_crowdPrice).div(10 ** decCrowd) <= 1e15 || b.getBorrowAmountGive() == 0) { return false; } if (b.liquidating()) { return true; } if (b.bondStage() == uint(BondStage.CrowdFundingSuccess) || b.bondStage() == uint(BondStage.UnRepay) || b.bondStage() == uint(BondStage.Overdue)) { if (now >= b.bondExpired().add(b.gracePeriod())) { return true; } uint256 _1 = 1 ether; uint256 crowdUsdxLeverage = crowdBalanceInUsd(id) .mul(b.depositMultiple()) .mul(b.liquidateLine()) .div(_1); //CCR < 0.7 * 4 //pawnUsd/crowdUsd < 0.7*4 //unsafe = pawnBalanceInUsd(id) < crowdUsdxLeverage; uint256 _ceilPawn = ceilPawn(id, pawnBalanceInUsd(id)); uint256 minCrowdInUsd = _crowdPrice.div(10 ** decCrowd); unsafe = _ceilPawn < crowdUsdxLeverage; if (abs(_ceilPawn, crowdUsdxLeverage) <= minCrowdInUsd && _ceilPawn < crowdUsdxLeverage) { unsafe = false; } return unsafe; } return false; } //获取实际需要的清算数量 function getLiquidateAmount(uint id, uint y1) external view returns (uint256, uint256) { uint256 y2 = y1;//y2为实际清算额度 uint256 y = Y(id);//y为剩余清算额度 require(y1 <= y, "exceed max liquidate amount"); //剩余额度小于一次清算量,将剩余额度全部清算 IBondData b = bondData(id); uint decUnit = 10 ** uint(IERC20Detailed(b.crowdToken()).decimals()); if (y <= b.partialLiquidateAmount()) { y2 = y; } else { require(y1 >= decUnit, "below min liquidate amount");//设置最小清算额度为1单位 } uint256 x = calcLiquidatePawnAmount(id, y2); return (y2, x); } }pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IACL { function accessible(address from, address to, bytes4 sig) external view returns (bool); } interface IReplaceACL { function setACL(address _ACL) external; } contract ACL { //系统停机控制 bool public locked; //系统维护者 address public admin; struct ownerset { address[] addresses; mapping(address => uint256) indexes; } ownerset private _owners_set; uint public owners_size; address public pending_admin; address public pending_owner; //控制签名串的重放攻击 uint public nonce; //访问控制列表(函数级别) mapping(address => mapping(address => mapping(bytes4 => bool))) public facl; //访问控制列表(合约级别) mapping(address => mapping(address => bool)) public cacl; modifier auth { require( accessible(msg.sender, address(this), msg.sig), "access unauthorized" ); _; } function owners() public view returns (address[] memory) { return _owners_set.addresses; } constructor(address[] memory _owners, uint _owners_size) public { for (uint256 i = 0; i < _owners.length; ++i) { require(_add(_owners[i]), "added address is already an owner"); } admin = msg.sender; owners_size = _owners_size; } function unlock() external auth { locked = false; } function lock() external auth { locked = true; } function accessible(address sender, address to, bytes4 sig) public view returns (bool) { if (msg.sender == admin) return true; if (_indexof(sender) != 0) return true; if (locked) return false; if (cacl[sender][to]) return true; if (facl[sender][to][sig]) return true; return false; } function mulsigauth( bytes32 _hash, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, address who) public { uint256 _size = _size(); uint256 weights = _size / 2 + 1; require(_indexof(who) != 0, "msg.sender must be owner"); require(v.length == r.length && r.length == s.length, "invalid signatures"); require(v.length <= _size && v.length >= weights, "invalid length"); uint256[] memory unique = new uint256[](_size); for (uint256 i = 0; i < v.length; ++i) { address owner = ecrecover(_hash, v[i], r[i], s[i]); uint256 _i = _indexof(owner); require(_i != 0, "is not owner"); require(unique[_i - 1] == 0, "duplicate signature"); unique[_i - 1] = 1; } uint256 _weights = 0; for (uint256 i = 0; i < _size; ++i) { _weights += unique[i]; } require(_weights >= weights, "insufficient weights"); } function multiSigSetACLs( uint8[] memory v, bytes32[] memory r, bytes32[] memory s, address[] memory execTargets, address newACL) public { bytes32 inputHash = keccak256(abi.encode(newACL, msg.sender, nonce)); bytes32 totalHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", inputHash)); mulsigauth(totalHash, v, r, s, msg.sender); nonce += 1; for (uint i = 0; i < execTargets.length; ++i) { IReplaceACL(execTargets[i]).setACL(newACL); } } //预设置 @who 具有owner权限. function proposeOwner( uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s, address who ) external { bytes32 inputHash = keccak256(abi.encode(who, msg.sender, nonce)); bytes32 totalHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", inputHash)); mulsigauth(totalHash, v, r, s, msg.sender); pending_owner = who; nonce += 1; } function confirmOwner() external { require(msg.sender == pending_owner, "sender is not pending_owner"); require(_add(msg.sender), "added address is already an owner"); pending_owner = address(0); } //最高级别owner修改admin function proposeAdmin(address who) external { require(_indexof(msg.sender) != 0, "msg.sender is not sys owner"); pending_admin = who; } function confirmAdmin() external { require(msg.sender == pending_admin, "sender is not pending_admin"); admin = msg.sender; pending_admin = address(0); } function replace(address who) external { require(msg.sender == pending_owner, "sender is not pending_owner"); require(_add(msg.sender), "added address is already an owner"); require(_remove(who), "removed address is not owner"); pending_owner = address(0); } function remove( uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s, address who ) external { bytes32 inputHash = keccak256(abi.encode(who, msg.sender, nonce)); bytes32 totalHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", inputHash)); mulsigauth(totalHash, v, r, s, msg.sender); require(_remove(who), "removed address is not owner"); require(_size() >= owners_size, "invalid size and weights"); nonce += 1; } function updateOwnerSize( uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s, uint256 _owners_size ) external { bytes32 inputHash = keccak256(abi.encode(_owners_size, msg.sender, nonce)); bytes32 totalHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", inputHash)); mulsigauth(totalHash, v, r, s, msg.sender); nonce += 1; owners_size = _owners_size; require(_size() >= owners_size, "invalid size and weights"); } //添加访问控制: 允许 @who 访问 @code 的所有方法 function enable(address sender, address to, bytes4 sig) external auth { facl[sender][to][sig] = true; } function disable(address sender, address to, bytes4 sig) external auth { facl[sender][to][sig] = false; } function enableany(address sender, address to) external auth { cacl[sender][to] = true; } function enableboth(address sender, address to) external auth { cacl[sender][to] = true; cacl[to][sender] = true; } function disableany(address sender, address to) external auth { cacl[sender][to] = false; } function _add(address value) internal returns (bool) { if (_owners_set.indexes[value] != 0) return false; _owners_set.addresses.push(value); _owners_set.indexes[value] = _owners_set.addresses.length; return true; } function _remove(address value) internal returns (bool) { if (_owners_set.indexes[value] == 0) return false; uint256 _i = _owners_set.indexes[value]; address _popv = _owners_set.addresses[_size() - 1]; _owners_set.addresses[_i - 1] = _popv; _owners_set.addresses.pop(); _owners_set.indexes[_popv] = _i; delete _owners_set.indexes[value]; return true; } function _size() internal view returns (uint256) { return _owners_set.addresses.length; } function _indexof(address owner) internal view returns (uint256) { return _owners_set.indexes[owner]; } } pragma solidity ^0.6.0; interface IRouter { function f(uint id, bytes32 k) external view returns (address); function defaultDataContract(uint id) external view returns (address); function bondNr() external view returns (uint); function setBondNr(uint _bondNr) external; function setDefaultContract(uint id, address data) external; function addField(uint id, bytes32 field, address data) external; }pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IBondData { struct what { address proposal; uint256 weight; } struct prwhat { address who; address proposal; uint256 reason; } struct Balance { //发行者: //amountGive: 质押的token数量,项目方代币 //amountGet: 募集的token数量,USDT,USDC //投资者: //amountGive: 投资的token数量,USDT,USDC //amountGet: 债券凭证数量 uint256 amountGive; uint256 amountGet; } function issuer() external view returns (address); function collateralToken() external view returns (address); function crowdToken() external view returns (address); function getBorrowAmountGive() external view returns (uint256); function getSupplyAmount(address who) external view returns (uint256, uint256); function setSupplyAmountGet(address who, uint256) external; function par() external view returns (uint256); function mintBond(address who, uint256 amount) external; function burnBond(address who, uint256 amount) external; function transferableAmount() external view returns (uint256); function debt() external view returns (uint256); function actualBondIssuance() external view returns (uint256); function couponRate() external view returns (uint256); function depositMultiple() external view returns (uint256); function discount() external view returns (uint256); function voteExpired() external view returns (uint256); function investExpired() external view returns (uint256); function totalBondIssuance() external view returns (uint256); function maturity() external view returns (uint256); function config() external view returns (address); function weightOf(address who) external view returns (uint256); function totalWeight() external view returns (uint256); function bondExpired() external view returns (uint256); function interestBearingPeriod() external; function bondStage() external view returns (uint256); function issuerStage() external view returns (uint256); function issueFee() external view returns (uint256); function totalInterest() external view returns (uint256); function gracePeriod() external view returns (uint256); function liability() external view returns (uint256); function remainInvestAmount() external view returns (uint256); function supplyMap(address) external view returns (Balance memory); function setSupply(address who, uint256 amountGive, uint256 amountGet) external; function balanceOf(address account) external view returns (uint256); function setPar(uint256) external; function liquidateLine() external view returns (uint256); function setBondParam(bytes32 k, uint256 v) external; function setBondParamAddress(bytes32 k, address v) external; function minIssueRatio() external view returns (uint256); function partialLiquidateAmount() external view returns (uint256); function votes(address who) external view returns (what memory); function setVotes(address who, address proposal, uint256 amount) external; function weights(address proposal) external view returns (uint256); function setBondParamMapping(bytes32 name, address k, uint256 v) external; function top() external view returns (address); function voteLedger(address who) external view returns (uint256); function totalWeights() external view returns (uint256); function setPr(address who, address proposal, uint256 reason) external; function pr() external view returns (prwhat memory); function fee() external view returns (uint256); function profits(address who) external view returns (uint256); function totalProfits() external view returns (uint256); function originLiability() external view returns (uint256); function liquidating() external view returns (bool); function setLiquidating(bool _liquidating) external; function sysProfit() external view returns (uint256); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IACL { function accessible(address sender, address to, bytes4 sig) external view returns (bool); } /* * usr->logic(1,2,3)->route->data(1,2,3) */ contract Router { address public ACL; constructor(address _ACL) public { ACL = _ACL; } modifier auth { require( IACL(ACL).accessible(msg.sender, address(this), msg.sig), "access unauthorized" ); _; } function setACL( address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } struct RouterData { address defaultDataContract; mapping(bytes32 => address) fields; } uint public bondNr;//total bond count mapping(uint => RouterData) public routerDataMap; function defaultDataContract(uint id) external view returns (address) { return routerDataMap[id].defaultDataContract; } function setDefaultContract(uint id, address _defaultDataContract) external auth { routerDataMap[id].defaultDataContract = _defaultDataContract; } function addField(uint id, bytes32 field, address data) external auth { routerDataMap[id].fields[field] = data; } function setBondNr(uint _bondNr) external auth { bondNr = _bondNr; } //根据field找出合约地址 function f(uint id, bytes32 field) external view returns (address) { if (routerDataMap[id].fields[field] != address(0)) { return routerDataMap[id].fields[field]; } return routerDataMap[id].defaultDataContract; } } pragma solidity ^0.6.0; enum BondStage { //无意义状态 DefaultStage, //评级 RiskRating, RiskRatingFail, //募资 CrowdFunding, CrowdFundingSuccess, CrowdFundingFail, UnRepay,//待还款 RepaySuccess, Overdue, //由清算导致的债务结清 DebtClosed } //状态标签 enum IssuerStage { DefaultStage, UnWithdrawCrowd, WithdrawCrowdSuccess, UnWithdrawPawn, WithdrawPawnSuccess } /* * Copyright (c) The Force Protocol Development Team */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract NameGen { function append(string memory a, string memory b, string memory c) public pure returns (string memory) { return string(abi.encodePacked(a, b, c)); } function uint2str(uint _i) public pure returns (string memory _uintAsString) { 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(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function gen(string memory symbol, uint id) public pure returns (string memory) { return append("Bond", symbol, uint2str(id)); } }pragma solidity ^0.6.0; interface IConfig { function depositTokenCandidates(address token) external view returns (bool); function issueTokenCandidates(address token) external view returns (bool); function issueFeeCandidates(uint256 issueFee) external view returns (bool); function interestRateCandidates(uint256 interestRate) external view returns (bool); function maturityCandidates(uint256 maturity) external view returns (bool); function minIssueRatioCandidates(uint256 minIssueRatio) external view returns (bool); function maxIssueAmount(address depositToken, address issueToken) external view returns (uint256); function minIssueAmount(address depositToken, address issueToken) external view returns (uint256); } contract Verify { address public config; constructor(address _config) public { config = _config; } //tokens[0]: _collateralToken //tokens[1]: _crowdToken //arguments[0]: _totalBondIssuance //arguments[1]: _couponRate, //一期的利率 //arguments[2]: _maturity, //秒数 //arguments[3]: _issueFee // //arguments[4]: _minIssueRatio //arguments[5]: _financePurposeHash,//融资用途hash //arguments[6]: _paymentSourceHash, //还款来源hash //arguments[7]: _issueTimestamp, //发债时间 function verify(address[2] calldata tokens, uint256[8] calldata arguments) external view returns (bool) { address depositToken = tokens[0]; address issueToken = tokens[1]; uint256 totalIssueAmount = arguments[0]; uint256 interestRate = arguments[1]; uint256 maturity = arguments[2]; uint256 issueFee = arguments[3]; uint256 minIssueRatio = arguments[4]; IConfig _config = IConfig(config); return _config.depositTokenCandidates(depositToken) && _config.issueTokenCandidates(issueToken) && totalIssueAmount <= _config.maxIssueAmount(depositToken, issueToken) && totalIssueAmount >= _config.minIssueAmount(depositToken, issueToken) && _config.interestRateCandidates(interestRate) && _config.maturityCandidates(maturity) && _config.issueFeeCandidates(issueFee) && _config.minIssueRatioCandidates(minIssueRatio); } } pragma solidity >=0.6.0; contract Rating { string public name; uint256 public risk; bool public fine; constructor(string memory _name, uint256 _risk, bool _fine) public { name = _name; risk = _risk; fine = _fine; } } /* * Copyright (c) The Force Protocol Development Team */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IRouter.sol"; import "./StageDefine.sol"; import "./ERC20lib.sol"; import "./IBondData.sol"; interface ICoreUtils { function d(uint256 id) external view returns (address); function bondData(uint256 id) external view returns (IBondData); //principal + interest = principal * (1 + couponRate); function calcPrincipalAndInterest(uint256 principal, uint256 couponRate) external pure returns (uint256); //可转出金额,募集到的总资金减去给所有投票人的手续费 function transferableAmount(uint256 id) external view returns (uint256); //总的募集资金量 function debt(uint256 id) external view returns (uint256); //总的募集资金量 function totalInterest(uint256 id) external view returns (uint256); function debtPlusTotalInterest(uint256 id) external view returns (uint256); //可投资的剩余份数 function remainInvestAmount(uint256 id) external view returns (uint256); function calcMinCollateralTokenAmount(uint256 id) external view returns (uint256); function pawnBalanceInUsd(uint256 id) external view returns (uint256); function disCountPawnBalanceInUsd(uint256 id) external view returns (uint256); function crowdBalanceInUsd(uint256 id) external view returns (uint256); //资不抵债判断,资不抵债时,为true,否则为false function isInsolvency(uint256 id) external view returns (bool); //获取质押的代币价格 function pawnPrice(uint256 id) external view returns (uint256); //获取募资的代币价格 function crowdPrice(uint256 id) external view returns (uint256); //要清算的质押物数量 //X = (AC*price - PCR*PD)/(price*(1-PCR*Discount)) //X = (PCR*PD - AC*price)/(price*(PCR*Discount-1)) function X(uint256 id) external view returns (uint256 res); //清算额,减少的债务 //X*price(collater)*Discount/price(crowd) function Y(uint256 id) external view returns (uint256 res); //到期后,由系统债务算出需要清算的抵押物数量 function calcLiquidatePawnAmount(uint256 id) external view returns (uint256); function calcLiquidatePawnAmount(uint256 id, uint256 liability) external view returns (uint256); function investPrincipalWithInterest(uint256 id, address who) external view returns (uint256); //bond: function convert2BondAmount(address b, address t, uint256 amount) external view returns (uint256); //bond: function convert2GiveAmount(uint256 id, uint256 bondAmount) external view returns (uint256); function isUnsafe(uint256 id) external view returns (bool unsafe); function isDepositMultipleUnsafe(uint256 id) external view returns (bool unsafe); function getLiquidateAmount(uint id, uint y1) external view returns (uint256, uint256); function precision(uint256 id) external view returns (uint256); } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20Detailed { function decimals() external view returns (uint8); function symbol() external view returns (string memory); } interface IOracle { function get(address t) external view returns (uint, bool); } interface IConfig { function voteDuration() external view returns (uint256); function investDuration() external view returns (uint256); function depositDuration() external view returns (uint256); function discount(address token) external view returns (uint256); function depositMultiple(address token) external view returns (uint256); function liquidateLine(address token) external view returns (uint256); function gracePeriod() external view returns (uint256); function partialLiquidateAmount(address token) external view returns (uint256); function gov() external view returns(address); function ratingFeeRatio() external view returns (uint256); } interface IACL { function accessible(address from, address to, bytes4 sig) external view returns (bool); } contract Core { using SafeERC20 for IERC20; using SafeMath for uint256; address public ACL; address public router; address public config; address public oracle; ICoreUtils public coreUtils; address public nameGen; modifier auth { IACL _ACL = IACL(ACL); require(_ACL.accessible(msg.sender, address(this), msg.sig), "core: access unauthorized"); _; } constructor( address _ACL, address _router, address _config, address _coreUtils, address _oracle, address _nameGen ) public { ACL = _ACL; router = _router; config = _config; coreUtils = ICoreUtils(_coreUtils); oracle = _oracle; nameGen = _nameGen; } function setCoreParamAddress(bytes32 k, address v) external auth { if (k == bytes32("router")) { router = v; } if (k == bytes32("config")) { config = v; } if (k == bytes32("coreUtils")) { coreUtils = ICoreUtils(v); } if (k == bytes32("oracle")) { oracle = v; } } function setACL( address _ACL) external { require(msg.sender == ACL, "require ACL"); ACL = _ACL; } function f(uint256 id, bytes32 k) public view returns (address) { return IRouter(router).f(id, k); } function d(uint256 id) public view returns (address) { return IRouter(router).defaultDataContract(id); } function bondData(uint256 id) public view returns (IBondData) { return IBondData(d(id)); } event MonitorEvent(address indexed who, address indexed bond, bytes32 indexed funcName, bytes); function MonitorEventCallback(address who, address bond, bytes32 funcName, bytes calldata payload) external { emit MonitorEvent(who, bond, funcName, payload); } function initialDepositCb(uint256 id, uint256 amount) external auth { IBondData b = bondData(id); b.setBondParam("depositMultiple", IConfig(config).depositMultiple(b.collateralToken())); require(amount >= ICoreUtils(coreUtils).calcMinCollateralTokenAmount(id), "invalid deposit amount"); b.setBondParam("bondStage", uint256(BondStage.RiskRating)); b.setBondParamAddress("gov", IConfig(config).gov()); uint256 voteDuration = IConfig(config).voteDuration(); //s b.setBondParam("voteExpired", now + voteDuration); b.setBondParam("gracePeriod", IConfig(config).gracePeriod()); b.setBondParam("discount", IConfig(config).discount(b.collateralToken())); b.setBondParam("liquidateLine", IConfig(config).liquidateLine(b.collateralToken())); b.setBondParam("partialLiquidateAmount", IConfig(config).partialLiquidateAmount(b.crowdToken())); b.setBondParam("borrowAmountGive", b.getBorrowAmountGive().add(amount)); } //发债方追加资金, amount为需要转入的token数 function depositCb(address who, uint256 id, uint256 amount) external auth returns (bool) { require(d(id) != address(0) && bondData(id).issuer() == who, "invalid address or issuer"); IBondData b = bondData(id); // //充值amount token到合约中,充值之前需要approve // safeTransferFrom(b.collateralToken(), msg.sender, address(this), address(this), amount); b.setBondParam("borrowAmountGive",b.getBorrowAmountGive().add(amount)); return true; } //投资债券接口 //id: 发行的债券id,唯一标志债券 //amount: 投资的数量 function investCb(address who, uint256 id, uint256 amount) external auth returns (bool) { IBondData b = bondData(id); require(d(id) != address(0) && who != b.issuer() && now <= b.investExpired() && b.bondStage() == uint(BondStage.CrowdFunding), "forbidden self invest, or invest is expired"); address give = b.crowdToken(); uint256 bondAmount = coreUtils.convert2BondAmount(address(b), give, amount); //投资不能超过剩余可投份数 require( bondAmount > 0 && bondAmount <= coreUtils.remainInvestAmount(id), "invalid bondAmount" ); b.mintBond(who, bondAmount); // //充值amount token到合约中,充值之前需要approve // safeTransferFrom(give, msg.sender, address(this), address(this), amount); (uint256 _amountGive, uint256 _amountGet) = b.getSupplyAmount(who); b.setSupply(who, _amountGive.add(amount), _amountGet.add(bondAmount) ); require(coreUtils.remainInvestAmount(id) >= 0, "bond overflow"); return true; } //停止融资, 开始计息 function interestBearingPeriod(uint256 id) external { IBondData b = bondData(id); //设置众筹状态, 调用的前置条件必须满足债券投票完成并且通过. //@auth 仅允许 @Core 合约调用. require(d(id) != address(0) && b.bondStage() == uint256(BondStage.CrowdFunding) && (now > b.investExpired() || coreUtils.remainInvestAmount(id) == 0), "already closed invest"); //计算融资进度. if ( b.totalBondIssuance().mul(b.minIssueRatio()).div(1e18) <= coreUtils.debt(id) ) { uint sysDebt = coreUtils.debtPlusTotalInterest(id); b.setBondParam("liability", sysDebt); b.setBondParam("originLiability", sysDebt); uint256 _1 = 1 ether; uint256 crowdUsdxLeverage = coreUtils.crowdBalanceInUsd(id) .mul(b.depositMultiple()) .mul(b.liquidateLine()) .div(_1); //CCR < 0.7 * 4 //pawnUsd/crowdUsd < 0.7*4 bool unsafe = coreUtils.pawnBalanceInUsd(id) < crowdUsdxLeverage; if (unsafe) { b.setBondParam("bondStage", uint256(BondStage.CrowdFundingFail)); b.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawPawn)); } else { b.setBondParam("bondExpired", now + b.maturity()); b.setBondParam("bondStage", uint256(BondStage.CrowdFundingSuccess)); b.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawCrowd)); //根据当前融资额度获取投票手续费. uint256 baseDec = 18; uint256 delta = baseDec.sub( uint256(ERC20Detailed(b.crowdToken()).decimals()) ); uint256 denominator = 10**delta; uint256 principal = b.actualBondIssuance().mul(b.par()); //principal * (0.05) * 1e18/(10** (18 - 6)) uint256 totalFee = principal.mul(b.issueFee()).div(denominator); uint256 voteFee = totalFee.mul(IConfig(config).ratingFeeRatio()).div(_1); b.setBondParam("fee", voteFee); b.setBondParam("sysProfit", totalFee.sub(voteFee)); } } else { b.setBondParam("bondStage", uint256(BondStage.CrowdFundingFail)); b.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawPawn)); } emit MonitorEvent(msg.sender, address(b), "interestBearingPeriod", abi.encodePacked()); } //转出募集到的资金,只有债券发行者可以转出资金 function txOutCrowdCb(address who, uint256 id) external auth returns (uint) { IBondData b = IBondData(bondData(id)); require(d(id) != address(0) && b.issuerStage() == uint(IssuerStage.UnWithdrawCrowd) && b.issuer() == who, "only txout crowd once or require issuer"); uint256 balance = coreUtils.transferableAmount(id); // safeTransferFrom(crowd, address(this), address(this), msg.sender, balance); b.setBondParam("issuerStage", uint256(IssuerStage.WithdrawCrowdSuccess)); b.setBondParam("bondStage", uint256(BondStage.UnRepay)); return balance; } function overdueCb(uint256 id) external auth { IBondData b = IBondData(bondData(id)); require(now >= b.bondExpired().add(b.gracePeriod()) && (b.bondStage() == uint(BondStage.UnRepay) || b.bondStage() == uint(BondStage.CrowdFundingSuccess) ), "invalid overdue call state"); b.setBondParam("bondStage", uint256(BondStage.Overdue)); emit MonitorEvent(msg.sender, address(b), "overdue", abi.encodePacked()); } //发债方还款 //id: 发行的债券id,唯一标志债券 //get: 募集的token地址 //amount: 还款数量 function repayCb(address who, uint256 id) external auth returns (uint) { require(d(id) != address(0) && bondData(id).issuer() == who, "invalid address or issuer"); IBondData b = bondData(id); //募资成功,起息后即可还款,只有未还款或者逾期中可以还款,债务被关闭或者抵押物被清算完,不用还款 require( b.bondStage() == uint(BondStage.UnRepay) || b.bondStage() == uint(BondStage.Overdue), "invalid state" ); //充值repayAmount token到合约中,充值之前需要approve //使用amountGet进行计算 uint256 repayAmount = b.liability(); b.setBondParam("liability", 0); //safeTransferFrom(crowd, msg.sender, address(this), address(this), repayAmount); b.setBondParam("bondStage", uint256(BondStage.RepaySuccess)); b.setBondParam("issuerStage", uint256(IssuerStage.UnWithdrawPawn)); //清算一部分后,正常还款,需要设置清算中为false if (b.liquidating()) { b.setLiquidating(false); } return repayAmount; } //发债方取回质押token,在发债方已还清贷款的情况下,可以取回质押品 //id: 发行的债券id,唯一标志债券 //pawn: 抵押的token地址 //amount: 取回数量 function withdrawPawnCb(address who, uint256 id) external auth returns (uint) { IBondData b = bondData(id); require(d(id) != address(0) && b.issuer() == who && b.issuerStage() == uint256(IssuerStage.UnWithdrawPawn), "invalid issuer, txout state or address"); b.setBondParam("issuerStage", uint256(IssuerStage.WithdrawPawnSuccess)); uint256 borrowGive = b.getBorrowAmountGive(); //刚好结清债务和抵押物均为0(b.issuerStage() == uint256(IssuerStage.DebtClosed))时,不能取回抵押物 require(borrowGive > 0, "invalid give amount"); b.setBondParam("borrowAmountGive", 0);//更新抵押品数量为0 return borrowGive; } //募资失败,投资人凭借"债券"取回本金 function withdrawPrincipalCb(address who, uint256 id) external auth returns (uint256) { IBondData b = bondData(id); address give = b.crowdToken(); //募资完成, 但是未募资成功. require(d(id) != address(0) && b.bondStage() == uint(BondStage.CrowdFundingFail), "must crowdfunding failure" ); (uint256 supplyGive, uint256 _) = b.getSupplyAmount(who); b.setSupply(who, 0, 0); //safeTransferFrom(give, address(this), address(this), msg.sender, supplyGive); uint256 bondAmount = coreUtils.convert2BondAmount( address(b), give, supplyGive ); b.burnBond(who, bondAmount); return supplyGive; } //债券到期, 投资人取回本金和收益 function withdrawPrincipalAndInterestCb(address who, uint256 id) external auth returns (uint256) { require(d(id) != address(0), "invalid address"); IBondData b = bondData(id); //募资成功,并且债券到期 require( b.bondStage() == uint(BondStage.RepaySuccess) || b.bondStage() == uint(BondStage.DebtClosed), "unrepay or unliquidate" ); address give = b.crowdToken(); (uint256 supplyGive, uint256 _) = b.getSupplyAmount(who); uint256 bondAmount = coreUtils.convert2BondAmount( address(b), give, supplyGive ); uint256 actualRepay = coreUtils.investPrincipalWithInterest(id, who); b.setSupply(who, 0, 0); //safeTransferFrom(give, address(this), address(this), msg.sender, actualRepay); b.burnBond(who, bondAmount); return actualRepay; } function abs(uint256 a, uint256 b) internal pure returns (uint c) { c = a >= b ? a.sub(b) : b.sub(a); } function liquidateInternal(address who, uint256 id, uint y1, uint x1) internal returns (uint256, uint256, uint256, uint256) { IBondData b = bondData(id); require(b.issuer() != who, "can't self-liquidate"); //当前已经处于清算中状态 if (b.liquidating()) { bool depositMultipleUnsafe = coreUtils.isDepositMultipleUnsafe(id); require(depositMultipleUnsafe, "in depositMultiple safe state"); } else { require(coreUtils.isUnsafe(id), "in safe state"); //设置为清算中状态 b.setLiquidating(true); } uint256 balance = IERC20(b.crowdToken()).balanceOf(who); uint256 y = coreUtils.Y(id); uint256 x = coreUtils.X(id); require(balance >= y1 && y1 <= y, "insufficient y1 or balance"); if (y1 == b.liability() || abs(y1, b.liability()) <= uint256(1) || x1 == b.getBorrowAmountGive() || abs(x1, b.getBorrowAmountGive()) <= coreUtils.precision(id)) { b.setBondParam("bondStage", uint(BondStage.DebtClosed)); b.setLiquidating(false); } if (y1 == b.liability() || abs(y1, b.liability()) <= uint256(1)) { if (!(x1 == b.getBorrowAmountGive() || abs(x1, b.getBorrowAmountGive()) <= coreUtils.precision(id))) { b.setBondParam("issuerStage", uint(IssuerStage.UnWithdrawPawn)); } } //对债务误差为1的处理 if (abs(y1, b.liability()) <= uint256(1)) { b.setBondParam("liability", 0); } else { b.setBondParam("liability", b.liability().sub(y1)); } if (abs(x1, b.getBorrowAmountGive()) <= coreUtils.precision(id)) { b.setBondParam("borrowAmountGive", 0); } else { b.setBondParam("borrowAmountGive", b.getBorrowAmountGive().sub(x1)); } if (!coreUtils.isDepositMultipleUnsafe(id)) { b.setLiquidating(false); } return (y1, x1, y, x); } //分批清算债券接口 //id: 债券发行id,同上 function liquidateCb(address who, uint256 id, uint256 y1) external auth returns (uint256, uint256, uint256, uint256) { (uint y, uint x) = coreUtils.getLiquidateAmount(id, y1); return liquidateInternal(who, id, y, x); } function updateBalance( uint256 id, address sender, address recipient, uint256 bondAmount ) external auth { IBondData b = bondData(id); uint256 txAmount = coreUtils.convert2GiveAmount(id, bondAmount); require(b.balanceOf(sender) >= bondAmount && bondAmount > 0, "invalid tx amount"); (uint256 _amoutSenderGive, uint256 _amountSenderGet) = b.getSupplyAmount(sender); (uint256 _amoutRecipientGive, uint256 _amountRecipientGet) = b.getSupplyAmount(recipient); b.setSupply(sender, _amoutSenderGive.sub(txAmount), _amountSenderGet.sub(bondAmount)); b.setSupply(recipient, _amoutRecipientGive.add(txAmount), _amountRecipientGet.add(bondAmount)); } //取回系统盈利 function withdrawSysProfitCb(address who, uint256 id) external auth returns (uint256) { IBondData b = bondData(id); uint256 _sysProfit = b.sysProfit(); require(_sysProfit > 0, "no withdrawable sysProfit"); b.setBondParam("sysProfit", 0); return _sysProfit; } }
1 SmartContractSecurityAuditReport11.ExecutiveSummary...............................................................................................................................................1 2.AuditMethodology.................................................................................................................................................2 3.ProjectBackground(Context).............................................................................................................................3 3.1ProjectIntroduction......................................................................................................................................3 4.CodeOverview........................................................................................................................................................5 4.1Infrastructure.................................................................................................................................................5 4.1.1FileHash.............................................................................................................................................5 4.1.2ContractsDescription......................................................................................................................6 4.2CodeAudit......................................................................................................................................................6 4.2.1Variablesarenotchecked..............................................................................................................6 4.2.2Permissioncontroldefect...............................................................................................................7 4.2.3Multi-Signverificationdefects......................................................................................................8 4.2.4Validationcanbebypassed........................................................................................................10 4.2.5Reentrancyattackrisk..................................................................................................................10 4.2.6Redundantcode.............................................................................................................................12 4.2.7Eventfunctionpermissioncontroldefect................................................................................13 4.2.8Eventandreturnvaluesaremissing........................................................................................13 4.2.9Codelogicerror..............................................................................................................................16 4.2.10Possiblecompatibilityissues....................................................................................................16 4.2.11Excessiveauditingauthority.....................................................................................................1824.2.12MultipleRating..............................................................................................................................18 5.AuditResult............................................................................................................................................................18 5.1High-riskvulnerabilities............................................................................................................................18 5.2Medium-riskVulnerability........................................................................................................................19 5.3Low-riskVulnerability................................................................................................................................19 5.4EnhancementSuggestions.....................................................................................................................19 5.5Conclusion...................................................................................................................................................20 6.Statement...............................................................................................................................................................2211.ExecutiveSummary OnMay14,2020,theSlowMistsecurityteamreceivedtheForTubeteam'ssecurityauditapplication forForTube2.0_Bond,developedtheauditplanaccordingtotheagreementofbothpartiesandthe characteristicsoftheproject,andfinallyissuedthesecurityauditreport. TheSlowMistsecurityteamadoptsthestrategyof“whiteboxlead,black,greyboxassists"to conductacompletesecuritytestontheprojectinthewayclosesttotherealattack. SlowMistSmartContractDeFiprojecttestmethod: Blackbox testingConductsecuritytestsfromanattacker'sperspectiveexternally. Greybox testingConductsecuritytestingoncodemodulethroughthescriptingtool,observing theinternalrunningstatus,miningweaknesses. Whitebox testingBasedontheopensourcecode,non-opensourcecode,todetectwetherthere arevulnerabilitiesinprogramssuckasnodes,SDK,etc. SlowMistSmartContractDeFiprojectrisklevel: Critical vulnerabilitiesCriticalvulnerabilitieswillhaveasignificantimpactonthesecurityoftheDeFi project,anditisstronglyrecommendedtofixthecriticalvulnerabilities. High-risk vulnerabilitiesHigh-riskvulnerabilitieswillaffectthenormaloperationofDeFiproject.Itis stronglyrecommendedtofixhigh-riskvulnerabilities. Medium-riskMediumvulnerabilitywillaffecttheoperationofDeFiproject.Itisrecommended2vulnerablitiestofixmedium-riskvulnerabilities. Low-risk vulnerabilitiesLow-riskvulnerabilitiesmayaffecttheoperationofDeFiprojectincertain scenarios.Itissuggestedthattheprojectpartyshouldevaluateandconsider whetherthesevulnerabilitiesneedtobefixed. WeaknessesTherearesafetyriskstheoretically,butitisextremelydifficulttoreproducein engineering. Enhancement SuggestionsTherearebetterpracticesforcodingorarchitecture. 2.AuditMethodology Oursecurityauditprocessforsmartcontractincludestwosteps: Smartcontractcodesarescanned/testedforcommonlyknownandmorespecific vulnerabilitiesusingpublicandin-houseautomatedanalysistools. Manualauditofthecodesforsecurityissues.Thecontractsaremanuallyanalyzedtolook foranypotentialproblems. Followingisthelistofcommonlyknownvulnerabilitiesthatwasconsideredduringtheauditofthe smartcontract: ReentrancyattackandotherRaceConditions Replayattack Reorderingattack Shortaddressattack Denialofserviceattack TransactionOrderingDependenceattack3ConditionalCompletionattack AuthorityControlattack IntegerOverflowandUnderflowattack TimeStampDependenceattack GasUsage,GasLimitandLoops Redundantfallbackfunction UnsafetypeInference Explicitvisibilityoffunctionsstatevariables LogicFlaws UninitializedStoragePointers FloatingPointsandNumericalPrecision tx.originAuthentication "Falsetop-up"Vulnerability ScopingandDeclarations 3.ProjectBackground(Context) 3.1ProjectIntroduction ForTubeisacryptoopenfinancialplatformdevelopedbyTheForceProtocol,relyingonblockchain technologytocarryoutinnovativeexperimentsaimedatpracticinginclusivefinanceandproviding appropriateandeffectivefinancialservicestoallusersoftheworld. Projectwebsite: https://www.for.tube/ Auditversioncode: https://github.com/thefortube/bond/tree/854527d0ea7ad2ddd3504b4d4ae3fcb57cb6445d Fixedversioncode: https://github.com/thefortube/bond/tree/f405c180c1c56c5b6282d34ee66a1446eec895c14ThedocumentsprovidedbytheForTubeteamareasfollows: BondTokensForTubewhitepaper.pdf: MD5:cd4385b4dd3193a935d69019493fc360 ForTube2.0(BetaVersion)userguide.pdf MD5:2ba33577b84895d5bed88e9a0cac1a45 BetaWebsite:https://beta.for.tube/bond/home Architecturediagram: 54.CodeOverview 4.1Infrastructure 4.1.1FileHash NO. FileName SHA-1Hash 1bond/contracts/Core.sol 061b58e95aaf9f5bb228d185898d93d90a157323 2bond/contracts/IRouter.sol e04ecec4b0a57b2874c3b445a7101188b199077b 3bond/contracts/StageDefine.sol32c1b0234d58288919120732549ba12d658351a4 4bond/contracts/ERC20lib.sol 7b967c3da1d259bf293dad506582a7cd4b67ee10 5bond/contracts/IBondData.sol 9ab49fbeb7fc05a838dbc8033c6b0b9316b0ff9e 6bond/contracts/ACL.sol a03577aa81cf45799911c08fdf47f0e2a65302a0 7bond/contracts/BondData.sol 20e4021cd19aefdeb1baad1c91c5dc470d8b5211 8bond/contracts/ReentrancyGuard.sol37f776802f7f14812d1bb9591d6ae8040ae4356b 9bond/contracts/BondFactory.solb1e9b483a0b6a6d16862cf9ec585491add2f9bb6 10bond/contracts/Config.sol acc8fe9ce80ef30c061417bd6804c9570cb9485a 11bond/contracts/Vote.sol a38259ab873b2e65795de2f3a097ea7cecbd1dd4 12bond/contracts/SafeERC20.solf3c73010d14659b987660919dda0011898d63387 13bond/contracts/CoreUtils.sol bcad885be6ff37e0a3ba73eedcd6537fd7c56131 14bond/contracts/PRA.sol 37650e50e19a1ceeaf7e8122e5b01e8d26b730f5615bond/contracts/Migrations.sol 507804b63af00ee80a92a5d5bacd5c98e3e3dce8 16bond/contracts/Rating.sol 3f2401fe3c97db2add8a7e4dfed2262967b9f80c 17bond/contracts/SafeMath.sol d228dfbe81530eb2399a4eec2987cfdbc8655795 18bond/contracts/NameGen.sol c36aec52f0d36c776c4b796a0390d5b1c4e1f93c 19bond/contracts/Oracle.sol 3b683a4ad911890d6a5d6be48c2be2cf6aaadc99 20bond/contracts/Router.sol 930927462eda6cb3f815adb1a7529c839559ea70 21bond/contracts/Verify.sol 97a1965b7e192c87b62ac19412364a6c8df936ec 4.1.2ContractsDescription Reference:ContractsDescription.pdf 4.2CodeAudit 4.2.1Variablesarenotchecked _owners_sizeisnotchecked,Itisrecommendedtoaddrequire(_owners.length>=_owners_size); ACL.sol constructor(address[]memory_owners,uint_owners_size)public{ for(uint256i=0;i<_owners.length;++i){ require(_add(_owners[i]),"addedaddressisalreadyanowner"); } admin=msg.sender; owners_size=_owners_size; }74.2.2Permissioncontroldefect Whenthesendercanpassvalidationifitmeetsoneofthefollowingfourconditions,theaccess controlpolicyfortheotherthreeconditionswillbebypassed.Therefore,theauthorizedaddresscan alsobeverifiedbyauthmodifierandcontinuetousethesefunctiontoauthorizeotherusers.Itis recommendedtodecouplethispartofthecodeintomultiplemodifiersfortargetedaccesscontrol. Othercodethatusestheauthmodifierhasasimilarrisk ACL.sol functionaccessible(addresssender,addressto,bytes4sig) public view returns(bool){ if(msg.sender==admin)returntrue; if(_indexof(sender)!=0)returntrue; if(locked)returnfalse; if(cacl[sender][to])returntrue; if(facl[sender][to][sig])returntrue; returnfalse; } ...... functionunlock()externalauth{ locked=false; } functionlock()externalauth{ locked=true; } ...... functionenable(addresssender,addressto,bytes4sig)externalauth{ facl[sender][to][sig]=true; } functiondisable(addresssender,addressto,bytes4sig)externalauth{ facl[sender][to][sig]=false;8} functionenableany(addresssender,addressto)externalauth{ cacl[sender][to]=true; } functionenableboth(addresssender,addressto)externalauth{ cacl[sender][to]=true; cacl[to][sender]=true; } functiondisableany(addresssender,addressto)externalauth{ cacl[sender][to]=false; } 4.2.3Multi-Signverificationdefects multiSigSetACLs,proposeOwner,remove,updateOwnerSizefunctionsareusemulsigauthfunction formulti-signverification.ButthereisaMulti-Signverificationdefects.Thereisnodistinctionmade inthefunctionforthepurposeofexecutingmulti-signverification,Itisrecommendedtoaddflagto eachfunctionandthencomputehash. ACL.sol functionmultiSigSetACLs( uint8[]memoryv, bytes32[]memoryr, bytes32[]memorys, address[]memoryexecTargets, addressnewACL)public{ bytes32inputHash=keccak256(abi.encode(newACL,msg.sender,nonce)); bytes32totalHash=keccak256(abi.encodePacked("\x19EthereumSignedMessage:\n32",inputHash)); mulsigauth(totalHash,v,r,s,msg.sender); nonce+=1; for(uinti=0;i<execTargets.length;++i){ IReplaceACL(execTargets[i]).setACL(newACL); } } functionproposeOwner( uint8[]calldatav, bytes32[]calldatar,9bytes32[]calldatas, addresswho )external{ bytes32inputHash=keccak256(abi.encode(who,msg.sender,nonce)); bytes32totalHash=keccak256(abi.encodePacked("\x19EthereumSignedMessage:\n32",inputHash)); mulsigauth(totalHash,v,r,s,msg.sender); pending_owner=who; nonce+=1; } functionremove( uint8[]calldatav, bytes32[]calldatar, bytes32[]calldatas, addresswho )external{ bytes32inputHash=keccak256(abi.encode(who,msg.sender,nonce)); bytes32totalHash=keccak256(abi.encodePacked("\x19EthereumSignedMessage:\n32",inputHash)); mulsigauth(totalHash,v,r,s,msg.sender); require(_remove(who),"removedaddressisnotowner"); require(_size()>=owners_size,"invalidsizeandweights"); nonce+=1; } functionupdateOwnerSize( uint8[]calldatav, bytes32[]calldatar, bytes32[]calldatas, uint256_owners_size )external{ bytes32inputHash=keccak256(abi.encode(_owners_size,msg.sender,nonce)); bytes32totalHash=keccak256(abi.encodePacked("\x19EthereumSignedMessage:\n32",inputHash)); mulsigauth(totalHash,v,r,s,msg.sender); nonce+=1; owners_size=_owners_size; require(_size()>=owners_size,"invalidsizeandweights"); }104.2.4Validationcanbebypassed Whenthecontractisconstructingthecodeisnull,sosoaccountHash==codehash== 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470,Ifyouwantto useiscontracttodeterminethattheaddressisnotacontract,isContractcanbebypassed. Inthiscaseyoucanadd:require(tx.origin==msg.sender);tofixit. ERC20lib.sol,SafeERC20.sol functionisContract(addressaccount)internalviewreturns(bool){ //AccordingtoEIP-1052,0x0isthevaluereturnedfornot-yetcreatedaccounts //and0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470isreturned //foraccountswithoutcode,i.e.`keccak256('')` bytes32codehash; bytes32accountHash=0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //solhint-disable-next-lineno-inline-assembly assembly{codehash:=extcodehash(account)} return(codehash!=accountHash&&codehash!=0x0); } 4.2.5Reentrancyattackrisk Usedexternalcallsbeforechangingthiscontractvariable"deposits[who].amount=line;",Ifthegov contracthasbeenmodified,Thegovcontractneedstobeserurityaudited. PRA.sol functionlock()external{ addresswho=msg.sender; require(deposits[who].amount==0,"senderalreadylocked"); require( IERC20(gov).allowance(who,address(this))>=line, "insufficientallowancetolock" ); require( IERC20(gov).balanceOf(who)>=line,11"insufficientbalancetolock" ); deposits[who].amount=line; IERC20(gov).safeTransferFrom(who,address(this),line); emitMonitorEvent(who,address(0),"lock",abi.encodePacked(line)); } ThenonReentrantmodifierisnotused,TheICore(logic).updatebalancecallhasReentrancyattack risk. BondData.sol functiontransfer(addressrecipient,uint256bondAmount) publicoverride(IERC20,ERC20) returns(bool) { ICore(logic).updateBalance(id,msg.sender,recipient,bondAmount); ERC20.transfer(recipient,bondAmount); ICore(logic).MonitorEventCallback(msg.sender,address(this),"transfer",abi.encodePacked( recipient, bondAmount )); returntrue; } functiontransferFrom(addresssender,addressrecipient,uint256bondAmount) publicoverride(IERC20,ERC20) returns(bool) { ICore(logic).updateBalance(id,sender,recipient,bondAmount); ERC20.transferFrom(sender,recipient,bondAmount); ICore(logic).MonitorEventCallback(sender,address(this),"transferFrom",abi.encodePacked( recipient, bondAmount )); ThenonReentrantmodifierisnotused,TheExternalcontractcallhasReentrancyattackrisk.12Vote.sol functionprcast(uint256id,addressproposal,uint256reason)external{ IBondDatadata=IBondData(IRouter(router).defaultDataContract(id)); require(data.voteExpired()>now,"voteisexpired"); require( IPRA(PRA).raters(msg.sender), "senderisnotaprofessionalrater" ); IBondData.prwhatmemorypr=data.pr(); require(pr.proposal==address(0),"alreadyprofessionalrating"); IBondData.whatmemory_what=data.votes(msg.sender); require(_what.proposal==address(0),"alreadycommunityrating"); require(data.issuer()!=msg.sender,"issuercan'tvoteforselfbond"); require( IConfig(config).ratingCandidates(proposal), "proposalisnotpermissive" ); data.setPr(msg.sender,proposal,reason); emitMonitorEvent( msg.sender, address(data), "prcast", abi.encodePacked(proposal) ); } 4.2.6Redundantcode ArgumentsintheVerifymethodisoftypeuint256[8],buttheactualcodeusesonlythevalues0-4, Itisrecommendedtochangeuint256[8]touint256[5]. Verify.sol functionverify(address[2]calldatatokens,uint256[8]calldataarguments) external view returns(bool) { addressdepositToken=tokens[0];13addressissueToken=tokens[1]; uint256totalIssueAmount=arguments[0]; uint256interestRate=arguments[1]; uint256maturity=arguments[2]; uint256issueFee=arguments[3]; uint256minIssueRatio=arguments[4]; IConfig_config=IConfig(config); return _config.depositTokenCandidates(depositToken)&& _config.issueTokenCandidates(issueToken)&& totalIssueAmount<=_config.maxIssueAmount(depositToken,issueToken)&& totalIssueAmount>=_config.minIssueAmount(depositToken,issueToken)&& _config.interestRateCandidates(interestRate)&& _config.maturityCandidates(maturity)&& _config.issueFeeCandidates(issueFee)&& _config.minIssueRatioCandidates(minIssueRatio); } 4.2.7Eventfunctionpermissioncontroldefect Thisfunctionwithoutauthentication,iftheattackerkeepscalling"MonitorEventCallback"functionin "core.sol"and"vote.sol"togeneratemaliciousevents,thewebserverwillchecktheaccountsand performglobalshutdown,leadtoDoS. Core.sol,Vote.sol functionMonitorEventCallback(addresswho,addressbond,bytes32funcName,bytescalldatapayload) external{ emitMonitorEvent(who,bond,funcName,payload); } 4.2.8Eventandreturnvaluesaremissing Theeventandreturnvaluesaremissing,Itisrecommendedthatyouaddareturnvalueanduse14eventtologtheexecuteresult. BondData.sol functionsetBondParam(bytes32k,uint256v)externalauth{ if(k==bytes32("discount")){ discount=v; } if(k==bytes32("liquidateLine")){ liquidateLine=v; } if(k==bytes32("depositMultiple")){ depositMultiple=v; } if(k==bytes32("gracePeriod")){ gracePeriod=v; } if(k==bytes32("voteExpired")){ voteExpired=v; } if(k==bytes32("investExpired")){ investExpired=v; } if(k==bytes32("bondExpired")){ bondExpired=v; } if(k==bytes32("partialLiquidateAmount")){ partialLiquidateAmount=v; } if(k==bytes32("fee")){ fee=v; } if(k==bytes32("sysProfit")){15sysProfit=v; } if(k==bytes32("originLiability")){ originLiability=v; } if(k==bytes32("liability")){ liability=v; } if(k==bytes32("totalWeights")){ totalWeights=v; } if(k==bytes32("totalProfits")){ totalProfits=v; } if(k==bytes32("borrowAmountGive")){ issuerBalanceGive=v; } if(k==bytes32("bondStage")){ bondStage=v; } if(k==bytes32("issuerStage")){ issuerStage=v; } } functionsetBondParamAddress(bytes32k,addressv)externalauth{ if(k==bytes32("gov")){ gov=v; } if(k==bytes32("top")){ top=v; } } functionsetBondParamMapping(bytes32name,addressk,uint256v)externalauth{16if(name==bytes32("weights")){ weights[k]=v; } if(name==bytes32("profits")){ profits[k]=v; } } 4.2.9Codelogicerror Theeventlogisoutsidetheifcode,soeitherdepositCbfunctionreturn"true"or"false"willexecute MonitorEventCallback,Itisrecommendedtochange"if"to"require". BondData.sol functiondeposit(uint256amount)externalnonReentrant{ if(ICore(logic).depositCb(msg.sender,id,amount)){ depositLedger[msg.sender]=depositLedger[msg.sender].add(amount); safeTransferFrom( collateralToken, msg.sender, address(this), address(this), amount ); } ICore(logic).MonitorEventCallback(msg.sender,address(this),"deposit",abi.encodePacked( amount, IERC20(collateralToken).balanceOf(address(this)) )); } 4.2.10Possiblecompatibilityissues BondFactorygeneratesbondcontractsbasedonthetokensaddressparameter,notethe17compatibilityoftheERC777. Reference:https://mp.weixin.qq.com/s/tps3EvxyWWTLHYzxsa9ffw BondFactory.sol functionissue( address[2]calldatatokens, uint256_minCollateralAmount, uint256[8]calldatainfo, bool[2]calldata_redeemPutback )externalreturns(uint256){ require(IVerify(verify).verify(tokens,info),"verifyerror"); uint256nr=IRouter(router).bondNr(); stringmemorybondName=INameGen(nameGen).gen(IERC20Detailed(tokens[0]).symbol(),nr); BondDatab=newBondData( ACL, nr, bondName, msg.sender, tokens[0], tokens[1], info, _redeemPutback ); IRouter(router).setDefaultContract(nr,address(b)); IRouter(router).setBondNr(nr+1); IACL(ACL).enableany(address(this),address(b)); IACL(ACL).enableboth(core,address(b)); IACL(ACL).enableboth(vote,address(b)); b.setLogics(core,vote); IERC20(tokens[0]).safeTransferFrom(msg.sender,address(this),_minCollateralAmount); IERC20(tokens[0]).safeApprove(address(b),_minCollateralAmount); b.initialDeposit(msg.sender,_minCollateralAmount); returnnr; }184.2.11Excessiveauditingauthority Addresswhichpassestheauthvalidationcanunlimitedexecutethe"burnBond"and"mintBond" functions. functionburnBond(addresswho,uint256amount)externalauth{ _burn(who,amount); actualBondIssuance=actualBondIssuance.sub(amount); } functionmintBond(addresswho,uint256amount)externalauth{ _mint(who,amount); mintCnt=mintCnt.add(amount); actualBondIssuance=actualBondIssuance.add(amount); } 4.2.12MultipleRating Everyaddresscanchangetheratingofthevotebyratingmultipletimes,andtheresultoftherating issubjecttothelasttime. Attackerscantakeadvantageofthisissuestomaliciouslychangetheratingandmaliciously manipulatetheoperationoftheproject. 5.AuditResult 5.1High-riskvulnerabilities Permissioncontroldefect19Multi-Signverificationdefects Note:Ithasbeenfixedinthefixedversioncode. Reentrancyattackrisk Note:Ithasbeenfixedinthefixedversioncode. 5.2Medium-riskVulnerability Eventfunctionpermissioncontroldefect Note:Ithasbeenfixedinthefixedversioncode. Eventandreturnvaluesaremissing Note:Ithasbeenfixedinthefixedversioncode. Codelogicerror Note:Ithasbeenfixedinthefixedversioncode. MultipleRating Excessiveauditingauthority 5.3Low-riskVulnerability Possiblecompatibilityissues 5.4EnhancementSuggestions Variablesarenotchecked Note:Ithasbeenfixedinthefixedversioncode.20Validationcanbebypassed Redundantcode 5.5Conclusion AuditResult:Somevulnerabilityshasbefixedinthefixedversioncode FixedCommit:f405c180c1c56c5b6282d34ee66a1446eec895c1 AuditNumber:0X002005310001 AuditDate:May31,2020 AuditTeam:SlowMistSecurityTeam Summaryconclusion:AftercommunicationandfeedbackwiththeForTubeteam,Thefollowing vulnerabilitieshavebeenfixedinthefixedversioncode. Multi-Signverificationdefects Reentrancyattackrisk Eventfunctionpermissioncontroldefect Eventandreturnvaluesaremissing Codelogicerror Variablesarenotchecked Aftercommunicationandfeedback,theactualriskofthefollowingissuesislimited,theseissueswill notbefixed. Permissioncontroldefect21Thepermissionmanagementin"ACL.sol"isthattheadministratorand"owner"aretogether. Eveniftwo"modifiers"areusedseparatelyin"ACL.sol",bothmodifiersneedtobeusedallthe timewheretheyarecalled,sothisissueswillnotbefixed. MultipleRating Thisisinlinewiththeoriginaldesign,anduserscanmodifythepreviousvotingoptions. Excessiveauditingauthority Ifthispermissionissubdivided,itwillincreasethecomplexityofthesystem.Underthecurrent design,evenifthe"Auth"privatekeyislost,thelost"Auth"privatekeycanstillbedisabledby Multi-Sign,andthispermissionhasnorighttousetheuser'sfunds,sotheuser'sfundsarestill safe. Possiblecompatibilityissues Thisiscurrentlynotfoundtohaveanimpactonthecontract. Validationcanbebypassed ThisshouldbeanIDissues.Whenthesystemisaffectedbythiskindofproblem,youcan disablethecorresponding"validation"byMulti-Signandrestoretheoriginallogic. Redundantcode Theunverifiedparametersareunimportantparametersandhavelittleimpactonthecontract. Sothisissuewillnotbefixed.226.Statement SlowMistissuesthisreportwithreferencetothefactsthathaveoccurredorexistedbeforethe issuanceofthisreport,andonlyassumescorrespondingresponsibilitybaseonthese. Forthefactsthatoccurredorexistedaftertheissuance,SlowMistisnotableto judgethesecuritystatusofthisproject,andisnotresponsibleforthem.Thesecurityauditanalysis andothercontentsofthisreportarebasedonthedocumentsandmaterialsprovidedtoSlowMistby theinformationprovidertillthedateoftheinsurancethisreport(referredtoas"provided information").SlowMistassumes:Theinformationprovidedisnotmissing,tamperedwith,deletedor concealed.Iftheinformationprovidedismissing,tamperedwith,deleted,concealed,orinconsistent withtheactualsituation,theSlowMistshallnotbeliableforanylossoradverseeffectresulting therefrom.SlowMistonlyconductstheagreedsecurityauditonthesecuritysituationoftheproject andissuesthisreport.SlowMistisnotresponsibleforthebackgroundandotherconditionsofthe project.1
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 Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 4 Major: 2 Critical: 1 Minor Issues: 2.a Problem: Variables are not checked 2.b Fix: Check variables before use Moderate Issues: 3.a Problem: Permission control defect 3.b Fix: Add permission control 3.c Problem: Multi-Sign verification defects 3.d Fix: Add multi-sign verification 3.e Problem: Validation can be bypassed 3.f Fix: Add validation 3.g Problem: Reentrancy attack risk 3.h Fix: Add reentrancy protection Major Issues: 4.a Problem: Redundant code 4.b Fix: Remove redundant code 4.c Problem: Event function permission control defect 4.d Fix: Add permission control Critical Issue: 5.a Problem: Event and return values are missing 5.b Fix: Add event and return values Observations: The SlowMist security team adopted the strategy of “whitebox lead, black, greybox assists" to conduct a complete
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./base/BasePool.sol"; import "./interfaces/ITimeLockPool.sol"; contract TimeLockPool is BasePool, ITimeLockPool { using Math for uint256; using SafeERC20 for IERC20; uint256 public immutable maxBonus; uint256 public immutable maxLockDuration; uint256 public constant MIN_LOCK_DURATION = 10 minutes; mapping(address => Deposit[]) public depositsOf; struct Deposit { uint256 amount; uint64 start; uint64 end; } constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) { require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration"); maxBonus = _maxBonus; maxLockDuration = _maxLockDuration; } event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from); event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount); function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant { require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address"); require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0"); // Don't allow locking > maxLockDuration uint256 duration = _duration.min(maxLockDuration); // Enforce min lockup duration to prevent flash loan or MEV transaction ordering duration = duration.max(MIN_LOCK_DURATION); depositToken.safeTransferFrom(_msgSender(), address(this), _amount); depositsOf[_receiver].push(Deposit({ amount: _amount, start: uint64(block.timestamp), end: uint64(block.timestamp) + uint64(duration) })); uint256 mintAmount = _amount * getMultiplier(duration) / 1e18; _mint(_receiver, mintAmount); emit Deposited(_amount, duration, _receiver, _msgSender()); } function withdraw(uint256 _depositId, address _receiver) external { require(_receiver != address(0), "TimeLockPool.withdraw: receiver cannot be zero address"); require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist"); Deposit memory userDeposit = depositsOf[_msgSender()][_depositId]; require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon"); // No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18; // remove Deposit depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1]; depositsOf[_msgSender()].pop(); // burn pool shares _burn(_msgSender(), shareAmount); // return tokens depositToken.safeTransfer(_receiver, userDeposit.amount); emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount); } function getMultiplier(uint256 _lockDuration) public view returns(uint256) { return 1e18 + (maxBonus * _lockDuration / maxLockDuration); } function getTotalDeposit(address _account) public view returns(uint256) { uint256 total; for(uint256 i = 0; i < depositsOf[_account].length; i++) { total += depositsOf[_account][i].amount; } return total; } function getDepositsOf(address _account) public view returns(Deposit[] memory) { return depositsOf[_account]; } function getDepositsOfLength(address _account) public view returns(uint256) { return depositsOf[_account].length; } }// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./LiquidityMiningManager.sol"; import "./TimeLockPool.sol"; /// @dev reader contract to easily fetch all relevant info for an account contract View { struct Data { uint256 pendingRewards; Pool[] pools; Pool escrowPool; uint256 totalWeight; } struct Deposit { uint256 amount; uint64 start; uint64 end; uint256 multiplier; } struct Pool { address poolAddress; uint256 totalPoolShares; address depositToken; uint256 accountPendingRewards; uint256 accountClaimedRewards; uint256 accountTotalDeposit; uint256 accountPoolShares; uint256 weight; Deposit[] deposits; } LiquidityMiningManager public immutable liquidityMiningManager; TimeLockPool public immutable escrowPool; constructor(address _liquidityMiningManager, address _escrowPool) { liquidityMiningManager = LiquidityMiningManager(_liquidityMiningManager); escrowPool = TimeLockPool(_escrowPool); } function fetchData(address _account) external view returns (Data memory result) { uint256 rewardPerSecond = liquidityMiningManager.rewardPerSecond(); uint256 lastDistribution = liquidityMiningManager.lastDistribution(); uint256 pendingRewards = rewardPerSecond * (block.timestamp - lastDistribution); result.totalWeight = liquidityMiningManager.totalWeight(); LiquidityMiningManager.Pool[] memory pools = liquidityMiningManager.getPools(); result.pools = new Pool[](pools.length); for(uint256 i = 0; i < pools.length; i ++) { TimeLockPool poolContract = TimeLockPool(address(pools[i].poolContract)); result.pools[i] = Pool({ poolAddress: address(pools[i].poolContract), totalPoolShares: poolContract.totalSupply(), depositToken: address(poolContract.depositToken()), accountPendingRewards: poolContract.withdrawableRewardsOf(_account), accountClaimedRewards: poolContract.withdrawnRewardsOf(_account), accountTotalDeposit: poolContract.getTotalDeposit(_account), accountPoolShares: poolContract.balanceOf(_account), weight: pools[i].weight, deposits: new Deposit[](poolContract.getDepositsOfLength(_account)) }); TimeLockPool.Deposit[] memory deposits = poolContract.getDepositsOf(_account); for(uint256 j = 0; j < result.pools[i].deposits.length; j ++) { TimeLockPool.Deposit memory deposit = deposits[j]; result.pools[i].deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: poolContract.getMultiplier(deposit.end - deposit.start) }); } } result.escrowPool = Pool({ poolAddress: address(escrowPool), totalPoolShares: escrowPool.totalSupply(), depositToken: address(escrowPool.depositToken()), accountPendingRewards: escrowPool.withdrawableRewardsOf(_account), accountClaimedRewards: escrowPool.withdrawnRewardsOf(_account), accountTotalDeposit: escrowPool.getTotalDeposit(_account), accountPoolShares: escrowPool.balanceOf(_account), weight: 0, deposits: new Deposit[](escrowPool.getDepositsOfLength(_account)) }); TimeLockPool.Deposit[] memory deposits = escrowPool.getDepositsOf(_account); for(uint256 j = 0; j < result.escrowPool.deposits.length; j ++) { TimeLockPool.Deposit memory deposit = deposits[j]; result.escrowPool.deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: escrowPool.getMultiplier(deposit.end - deposit.start) }); } } }// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IBasePool.sol"; import "./base/TokenSaver.sol"; contract LiquidityMiningManager is TokenSaver { using SafeERC20 for IERC20; bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE"); bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE"); uint256 public MAX_POOL_COUNT = 10; IERC20 immutable public reward; address immutable public rewardSource; uint256 public rewardPerSecond; //total reward amount per second uint256 public lastDistribution; //when rewards were last pushed uint256 public totalWeight; mapping(address => bool) public poolAdded; Pool[] public pools; struct Pool { IBasePool poolContract; uint256 weight; } modifier onlyGov { require(hasRole(GOV_ROLE, _msgSender()), "LiquidityMiningManager.onlyGov: permission denied"); _; } modifier onlyRewardDistributor { require(hasRole(REWARD_DISTRIBUTOR_ROLE, _msgSender()), "LiquidityMiningManager.onlyRewardDistributor: permission denied"); _; } event PoolAdded(address indexed pool, uint256 weight); event PoolRemoved(uint256 indexed poolId, address indexed pool); event WeightAdjusted(uint256 indexed poolId, address indexed pool, uint256 newWeight); event RewardsPerSecondSet(uint256 rewardsPerSecond); event RewardsDistributed(address _from, uint256 indexed _amount); constructor(address _reward, address _rewardSource) { require(_reward != address(0), "LiquidityMiningManager.constructor: reward token must be set"); require(_rewardSource != address(0), "LiquidityMiningManager.constructor: rewardSource token must be set"); reward = IERC20(_reward); rewardSource = _rewardSource; } function addPool(address _poolContract, uint256 _weight) external onlyGov { distributeRewards(); require(_poolContract != address(0), "LiquidityMiningManager.addPool: pool contract must be set"); require(!poolAdded[_poolContract], "LiquidityMiningManager.addPool: Pool already added"); require(pools.length < MAX_POOL_COUNT, "LiquidityMiningManager.addPool: Max amount of pools reached"); // add pool pools.push(Pool({ poolContract: IBasePool(_poolContract), weight: _weight })); poolAdded[_poolContract] = true; // increase totalWeight totalWeight += _weight; // Approve max token amount reward.safeApprove(_poolContract, type(uint256).max); emit PoolAdded(_poolContract, _weight); } function removePool(uint256 _poolId) external onlyGov { require(_poolId < pools.length, "LiquidityMiningManager.removePool: Pool does not exist"); distributeRewards(); address poolAddress = address(pools[_poolId].poolContract); // decrease totalWeight totalWeight -= pools[_poolId].weight; // remove pool pools[_poolId] = pools[pools.length - 1]; pools.pop(); poolAdded[poolAddress] = false; // Approve 0 token amount reward.safeApprove(poolAddress, 0); emit PoolRemoved(_poolId, poolAddress); } function adjustWeight(uint256 _poolId, uint256 _newWeight) external onlyGov { require(_poolId < pools.length, "LiquidityMiningManager.adjustWeight: Pool does not exist"); distributeRewards(); Pool storage pool = pools[_poolId]; totalWeight -= pool.weight; totalWeight += _newWeight; pool.weight = _newWeight; emit WeightAdjusted(_poolId, address(pool.poolContract), _newWeight); } function setRewardPerSecond(uint256 _rewardPerSecond) external onlyGov { distributeRewards(); rewardPerSecond = _rewardPerSecond; emit RewardsPerSecondSet(_rewardPerSecond); } function distributeRewards() public onlyRewardDistributor { uint256 timePassed = block.timestamp - lastDistribution; uint256 totalRewardAmount = rewardPerSecond * timePassed; lastDistribution = block.timestamp; // return if pool length == 0 if(pools.length == 0) { return; } // return if accrued rewards == 0 if(totalRewardAmount == 0) { return; } reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount); for(uint256 i = 0; i < pools.length; i ++) { Pool memory pool = pools[i]; uint256 poolRewardAmount = totalRewardAmount * pool.weight / totalWeight; // Ignore tx failing to prevent a single pool from halting reward distribution address(pool.poolContract).call(abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, poolRewardAmount)); } uint256 leftOverReward = reward.balanceOf(address(this)); // send back excess but ignore dust if(leftOverReward > 1) { reward.safeTransfer(rewardSource, leftOverReward); } emit RewardsDistributed(_msgSender(), totalRewardAmount); } function getPools() external view returns(Pool[] memory result) { return pools; } }// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./TimeLockPool.sol"; contract TimeLockNonTransferablePool is TimeLockPool { constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) TimeLockPool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration, _maxBonus, _maxLockDuration) { } // disable transfers function _transfer(address _from, address _to, uint256 _amount) internal override { revert("NON_TRANSFERABLE"); } }
January 8th 2022— Quantstamp Verified Vault.Inc This audit report was prepared by Quantstamp, the leader in blockchain security. Executive Summary Type DeFi Protocol Auditors Jan Gorzny , Blockchain ResearcherRoman Rohleder , Research EngineerPoming Lee , Research EngineerTimeline 2021-12-13 through 2022-01-07 EVM London Languages Solidity Methods Architecture Review, Unit Testing, Functional Testing, Computer-Aided Verification, Manual Review. Specification None Documentation Quality Low Test Quality High Source Code Repository Commit vault-tec-core a0cd3ec Total Issues 8 (6 Resolved)High Risk Issues 1 (1 Resolved)Medium Risk Issues 1 (1 Resolved)Low Risk Issues 4 (2 Resolved)Informational Risk Issues 1 (1 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 reviewed the Vault.Inc "vault-tec-core" repository. Quantstamp found several issues. Some issues were unavoidable due to the design of the system, while others were fixed. All issues have been resolved or acknowledged. The code is accompanied by tests with fairly high coverage. ID Description Severity Status QSP- 1 Critically Low Test Coverage High Fixed QSP- 2 Maximum Approve Medium Mitigated QSP- 3 Privileged Roles and Ownership Low Acknowledged QSP- 4 Unknown Code in the Contract Low Acknowledged QSP- 5 Use of Insecure Casting Operation Low Fixed QSP- 6 Missing Input Validation Low Fixed QSP- 7 Events Not Emitted on State Change Informational Fixed QSP- 8 Potential Re-Entrancy 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 . Setup Tool Setup: v0.6.6 • SlitherSteps taken to run the tools: Installed the Slither tool: Run Slither from the project directory: pip install slither-analyzer slither . FindingsQSP-1 Critically Low Test Coverage Severity: High Risk Fixed Status: File(s) affected: all There are no tests, and as such, the test coverage is 0%. Description: Add (many) tests to increase coverage to the highest possible amount: as close to 100% coverage as possible. Recommendation: The team has added tests. Update: QSP-2 Maximum Approve Severity: Medium Risk Mitigated Status: File(s) affected: LiquidityMiningManager.sol Line 62 calls which means unlimited funds can be moved if something goes wrong. Description: approve(_poolContract, type(uint256).max); Design this out, or make sure users are aware of this requirement. Recommendation: This has been partially mitigated by leaving the “unlimited” approval, but resetting it to zero when removing the pool. Update: QSP-3 Privileged Roles and Ownership Severity: Low Risk Acknowledged Status: , , , File(s) affected: LiquidityMiningManager.sol TimeLockPool.sol TimeLockNonTransferablePool.sol BasePool.sol Certain contracts have special roles, which provide certain addresses with privileged roles. Such roles may pose a risk to end-users. Description: The owner of the or contracts may perform the following privileged actions: TimeLockPool.sol TimeLockNonTransferablePool.sol 1. Give or revoke the role ofto any arbitrary address. TOKEN_SAVER_ROLE 2. Call, thereby transferring an arbitrary amount of an arbitrary token from the current contract to an arbitrary address. saveToken() 3. Renounce ownership, by calling, thereby preventing the change of the currently set role. renounceOwnership() TOKEN_SAVER_ROLE 4. Transfer ownership (the role of) to an arbitrary address. DEFAULT_ADMIN_ROLE The owner of the contract may perform the following privileged actions: LiquidityMiningManager.sol 1. Give or revoke the role ofto any arbitrary address. TOKEN_SAVER_ROLE 2. Call, thereby transferring an arbitrary amount of an arbitrary token of the contract to an arbitrary address. saveToken() LiquidityMiningManager.sol 3. Give or revoke the role ofto any arbitrary address. GOV_ROLE 4. Add or remove pools, change pool weights or, by calling , , and respectively. rewardPerSecond addPool() removePool() adjustWeight() setRewardPerSecond() 5. Give or revoke the role ofto any arbitrary address. REWARD_DISTRIBUTOR_ROLE 6. Distribute rewards by calling distributeRewards()`.7. Renounce ownership, by callingthereby preventing the change of the currently set , and roles. renounceOwnership(),TOKEN_SAVER_ROLE GOV_ROLE REWARD_DISTRIBUTOR_ROLE 8. Transfer ownership (the role of) to an arbitrary address. DEFAULT_ADMIN_ROLE Note: As functions , and call , which is only callable by a reward distributor role holding account, it entails that the holding account will also hold the role of . addPool()removePool() adjustWeight() distributeRewards() GOV_ROLE REWARD_DISTRIBUTOR_ROLE Clarify the impact of these privileged actions to the end-users via publicly facing documentation. Recommendation: The team has acknowledged this issue: "We will be adding a note in the frontend regarding the admin role.". Update: QSP-4 Unknown Code in the Contract Severity: Low Risk Acknowledged Status: The constructor of utilizes code unknown (variables of function type) during the audit period to initialize the implementation of two functions, that are: and . This could cause the contracts to result in very different behavior from what was expected. Description:contracts\base\AbstractRewards.sol getSharesOf getTotalShares Hard code the intended logic of those two functions into the contract and have them audited. Or provide comments that explain why this is intended and should not be changed. Recommendation:The team has acknowledged this issue: "The calculation of reward distribution requires the ERC20 functions and we don’t want to add that dependency to AbstractRewards contract. It’s only called in BasePool’s constructor and we always pass in the standard ERC20 functions as the parameters so we think the behavior is predictable." Update:QSP-5 Use of Insecure Casting Operation Severity: Low Risk FixedStatus: File(s) affected: AbstractRewards.sol Related Issue(s): SWC-101 In the insecure primitive casting operation is used. For sufficiently large positive or negative values this cast may wrap around, without leading to a revert and therefore lead to unexpected behaviour. Description:AbstractRewards._correctPoints() int256() Replace the use of this insecure cast operation with for example its secure counterpart of . Recommendation: .toInt256() OpenZeppelins SafeCast library This has been resolved by changing the primitive cast operation to its safe counterpart of OpenZeppelins library, as suggested. Update: .toInt256() SafeCast QSP-6 Missing Input Validation Severity: Low Risk Fixed Status: , File(s) affected: AbstractRewards.sol TimeLockPool.sol It is important to validate inputs, even if they only come from trusted addresses, to avoid human error. The following functions do not have a proper validation of input parameters: Description: 1. does not check that parameter is different from . AbstractRewards._prepareCollect() _account address(0) 2. does not check that parameters and are different from or is non-zero. AbstractRewards._correctPointsForTransfer() _from _to address(0) _shares 3. does not check that parameter is different from or is non-zero. AbstractRewards._correctPoints() _account address(0) _shares 4. does not check that parameter is different from . TimeLockPool.deposit() _receiver address(0) 5. does not check that parameter is different from . TimeLockPool.withdraw() _receiver address(0) Add corresponding checks on the listed parameters, i.e. via statements. Recommendation: require This issue has been resolved, by adding corresponding parameter checks, as suggested. Update: QSP-7 Events Not Emitted on State Change Severity: Informational Fixed Status: File(s) affected: AbstractRewards.sol An event should always be emitted when a state change is performed in order to facilitate smart contract monitoring by other systems which want to integrate with the smart contract. This is not the case for the functions: Description:1. does not emit any event upon a successful change of the state variables and . AbstractRewards._correctPointsForTransfer()pointsCorrection[_from] pointsCorrection[_to] 2. does not emit any event upon a successful change of the state variable . AbstractRewards._correctPoints() pointsCorrection[_account] Emit an event in the aforementioned functions. Recommendation: This issue has been resolved by adding a new event and emitting it where needed, as suggested Update: PointsCorrectionUpdated QSP-8 Potential Re-Entrancy Severity: Undetermined Fixed Status: , File(s) affected: BasePool.sol TimeLockPool.sol Related Issue(s): SWC-107 The following functions do not follow the pattern, as they perform calls to external contracts before changing state variables, while at the same time not being protected through i.e. a modifier: Description:Checks-Effects-Interactions nonReentrant • TimeLockPool.deposit()• BasePool.distributeRewards()Note that a re-entrancy would be also possible for seemingly benign or tokens, in case those are based on the ERC777 standard, allowing to hook transfers . rewardTokendepositToken and divert control flow Use the modifier, as was already used in i.e. . Recommendation: OpenZeppelin ReentrancyGuard.nonReentrant Vault._deposit() This issue has been resolved by making use of the modifier at said functions, as suggested. Update: nonReentrant Automated Analyses Slither Slither's results were filtered and either added in the report, or omitted as false positives. Code Documentation 1.Theerror message in line 48 of states , which seems to be a copy-and-paste of the previous line and should have been as it is seems to be a non-token address. requireLiquidityMiningManager.sol rewardSource token must be set rewardSource address must be set Adherence to Best Practices 1. For improved readabilityto have a maximum line length of 79 or 99. Therefore L31, L36, L47, L48, L55, L57, L91 and L131 of , L17 of , L36, L37, L42, L43, L67, L71, L72 and L75 of , L53 and L59 of , L26 and L84 of and L13, L16 and L24 of , which exceed these limits, should be shortened accordingly. it is recommendedLiquidityMiningManager.sol TimeLockNonTransferablePool.sol TimeLockPool.sol AbstractRewards.sol BasePool.sol TokenSaver.sol 2. To prevent confusion it is recommended to avoid re-using the same/similar names for different variables, functions or structures. Contractdefines structures and , which however are different from the structures in and from and should therefore be renamed. View.solDeposit Pool Deposit TimeLockPool.sol Pool LiquidityMiningManager.sol 3. For clarity and consistency magic numbers should be declared once, commented and then used throughout. In this regard the numberis used in L60, L72 and L87 of and L37 and L72 of , without being declared or commented. To conform to best practices consider declaring this constant, i.e. in and comment it. 1e18TimeLockPool.sol BasePool.sol BasePool.sol 4. , line 41: Consider checking that if , should revert if . contracts\base\BasePool.sol _escrowPortion > 0 _escrowPool == 0x0 5. According to best practices address parameters of events should always be indexed to facilitate logging and monitoring. The address parameterin L44 of is however lacking the keyword and should therefore be added. _fromLiquidityMiningManager.sol indexed 6. : could be made constant. LiquidityMiningManager MAX_POOL_COUNT 7. ignores by (Line 134). This is noted as intentional in a comment, but perhaps should be handled in the code itself. LiquidityMiningManager.distributeRewards()return value address(pool.poolContract).call() Test Results Test Suite Results BasePool distributeRewards ✓ Should fail when there are no shares ✓ Should fail when tokens are not approved (221ms) ✓ Should work (497ms) claimRewards ✓ First claim single holder (601ms) ✓ Claim multiple holders (940ms) ✓ Multiple claims, distribution and holders (1301ms) ✓ Zero escrow (289ms) ✓ Full escrow (792ms) LiquidityMiningManager Adding pools ✓ Adding a single pool (46ms) ✓ Adding multiple pools (87ms) ✓ Adding a pool twice should fail (39ms) ✓ Adding a pool from a non gov address should fail Removing pools ✓ Removing last pool in list (104ms) ✓ Removing a pool in the beginning of the list (162ms) ✓ Removing all pools (786ms) ✓ Removing a pool from a non gov address should fail Distributing rewards ✓ Distributing rewards from an address which does not have the REWARD_DISTRIBUTOR_ROLE ✓ Distributing zero rewards ✓ Should return any excess rewards (1344ms) ✓ Should work (1073ms) Adjusting weight ✓ Adjust weight up (59ms) ✓ Adjust weight down (213ms) ✓ Should fail from non gov address Setting reward per second ✓ Should work (53ms) ✓ Should fail from non gov address TimeLockNonTransferablePool ✓ transfer ✓ transferFrom TimeLockPool deposit ✓ Depositing with no lock should lock it for 10 minutes to prevent flashloans (390ms) ✓ Deposit with no lock (378ms) ✓ Trying to lock for longer than max duration should lock for max duration (297ms) ✓ Multiple deposits (522ms) ✓ Should fail when transfer fails (73ms) withdraw ✓ Withdraw before expiry should fail ✓ Should work (238ms) TokenSaver saveToken ✓ Should fail when called fron non whitelised address ✓ Should work (245ms) 36 passing (18s) Code Coverage File Statements Branches Functions Lines contracts/ 80.2% 101 81/66.67% 36 24/90% 2018/80.58% 103 83/contracts/ base/ 82.46% 57 47/56.67% 30 17/88.24% 17 15/82.76% 58 48/contracts/ interfaces/ 100% 00/100% 00/100% 00/100% 00/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 757a1cc3ae7908d3bb5ba544d2d1cdafcb206fbf3a9c32c7097a9a3c057aecb7 ./contracts/LiquidityMiningManager.sol 65d66fa08c13c10901a59a4c3c19d9c1075396715491e8b4f48d659bf5dd77c5 ./contracts/TimeLockNonTransferablePool.sol c30f39df9841ca892efefe97ff5b95af63fc4775ce10a02cef2a754a79600140 ./contracts/TimeLockPool.sol c8c79af8a80a435b466588e5291d154bf31285aba868d30b0bc44326c1bcdaf9 ./contracts/View.sol 44129dc0fb197cdc38891d05da506588492794f89f6de83902a96f3b6d621281 ./contracts/test/TestBasePool.sol 34b79e96ba58a220965725b4f4c3b3350f06ef6330242b07e5ec80101cc20106 ./contracts/test/TestFaucetToken.sol dc79250ac1a086a86e43daa8d7e5a0833f01013ea94298b933c1f6165b56872a ./contracts/test/TestToken.sol e4d54710f7d465f7b264f10c571373c078dce11e2c677bf334220fcd97f68d0b ./contracts/interfaces/IAbstractRewards.sol 0a3671d77736ec30404857a50b6e7d3d4654beb58e3e3108b63b5360c309d2d9 ./contracts/interfaces/IBasePool.sol cd806c0f1dc6637bb3e147b94e53d5af24089be02868f92152cc382f7431558d ./contracts/interfaces/ITimeLockPool.sol 8b3eb8c8026bdc84b7fea6601b73a188daca604aba2d5b81adce3f8da8295bff ./contracts/base/AbstractRewards.sol f7363171e902f916f35b57a1c102890a8b7ae6b84aaf11129afc995c32ea4f34 ./contracts/base/BasePool.sol 4df1f949bfcddf7305dfba1ef6021842105ebd1c793a5c440217af60f69743b2 ./contracts/base/TokenSaver.sol Tests 9f0de342cf41c8b92dbb62b0ac1f38b2c21d0f49772c6a642a0203812e50429d ./test/BasePool.ts f6f9a85335a9e82dabac2fbf4f3701ba117dc1eb10403e2a5fc4ad8278ea5372 ./test/LiquidityMiningManager.ts fcf0835789d668fb0c08cef4bec813750973efea1752f3cb0bd210f3f08a9919 ./test/TimeLockNonTransferablePool.ts 0d8fdac6533eb46dc25a37a4f1e74a3d78645ed1a638de370a84db3ba5b6fd2b ./test/TimeLockPool.ts a837563927a505dbd90499489111b95898caefdcf292df9865d7202e1602e65c ./test/TokenSaver.ts Changelog 2021-12-22 - Initial report [ ] • b1c3e04 2022-01-07 - Revised report [ ] • a0cd3ec 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. Vault.Inc Audit
Issues Count of Minor/Moderate/Major/Critical - Minor Issues: 4 (2 Resolved) - Moderate Issues: 1 (1 Resolved) - Major Issues: 1 (1 Resolved) - Critical Issues: 1 (1 Resolved) - Informational Issues: 1 (1 Resolved) - Undetermined Issues: 1 (1 Resolved) Minor Issues 2.a Problem: Unchecked return value in the function transferFrom() (line 545) 2.b Fix: Added a check for the return value (line 545) Moderate Issues 3.a Problem: Unchecked return value in the function transfer() (line 545) 3.b Fix: Added a check for the return value (line 545) Major Issues 4.a Problem: Unchecked return value in the function transfer() (line 545) 4.b Fix: Added a check for the return value (line 545) Critical Issues 5.a Problem: Unchecked return value in the function transfer() (line 545) 5.b Fix: Added a check for the return value (line 545) Informational Issues Count of Minor/Moderate/Major/Critical: Minor: 2 Moderate: 1 Major: 0 Critical: 1 Minor Issues: 2.a Problem: Maximum Approve Medium (QSP-2) 2.b Fix: Mitigated (QSP-2) Moderate: 3.a Problem: Privileged Roles and Ownership Low (QSP-3) 3.b Fix: Acknowledged (QSP-3) Critical: 5.a Problem: Critically Low Test Coverage High (QSP-1) 5.b Fix: Fixed (QSP-1) Observations: • The code is accompanied by tests with fairly high coverage. • The Quantstamp auditing process follows a routine series of steps: code review, testing and automated analysis, best practices review, and specific, itemized, and actionable recommendations. • The toolset used for the audit includes Slither v0.6.6. Conclusion: The audit of the repository was successful in identifying and addressing security-related issues, code quality, and adherence to specification and best practices. The audit process was conducted using Issues Count of Minor/Moderate/Major/Critical: Minor: 1 Moderate: 1 Major: 0 Critical: 1 Minor Issues: 2.a Problem: Certain contracts have special roles, which provide certain addresses with privileged roles. 2.b Fix: Design this out, or make sure users are aware of this requirement. Moderate: 3.a Problem: Line 62 calls approve(_poolContract, type(uint256).max); which means unlimited funds can be moved if something goes wrong. 3.b Fix: This has been partially mitigated by leaving the “unlimited” approval, but resetting it to zero when removing the pool. Critical: 5.a Problem: The owner of the LiquidityMiningManager.sol, TimeLockPool.sol, TimeLockNonTransferablePool.sol, and BasePool.sol contracts may perform privileged actions. 5.b Fix: Design this out, or make sure users are aware of this requirement. Observations: The team has added tests to increase coverage to the highest possible amount. Conclusion: The team has taken steps to mitigate the risks posed by