input
stringlengths
32
47.6k
output
stringclasses
657 values
/* Note: This is a PROXY contract, it defers requests to its underlying TARGET contract. Always use this address in your applications and never the TARGET as it is liable to change. *//* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: ProxyERC20.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/ProxyERC20.sol * Docs: https://docs.synthetix.io/contracts/ProxyERC20 * * Contract Dependencies: * - IERC20 * - Owned * - Proxy * Libraries: (none) * * MIT License * =========== * * Copyright (c) 2021 Synthetix * * 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 */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxyable contract Proxyable is Owned { // This contract should be treated like an abstract contract /* The proxy this contract exists behind. */ Proxy public proxy; Proxy public integrationProxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address public messageSender; constructor(address payable _proxy) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address payable _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setIntegrationProxy(address payable _integrationProxy) external onlyOwner { integrationProxy = Proxy(_integrationProxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { _onlyProxy(); _; } function _onlyProxy() private view { require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call"); } modifier optionalProxy { _optionalProxy(); _; } function _optionalProxy() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } } modifier optionalProxy_onlyOwner { _optionalProxy_onlyOwner(); _; } // solhint-disable-next-line func-name-mixedcase function _optionalProxy_onlyOwner() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } require(messageSender == owner, "Owner only function"); } event ProxyUpdated(address proxyAddress); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxy contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } // https://docs.synthetix.io/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // Inheritance // https://docs.synthetix.io/contracts/source/contracts/proxyerc20 contract ProxyERC20 is Proxy, IERC20 { constructor(address _owner) public Proxy(_owner) {} // ------------- ERC20 Details ------------- // function name() public view returns (string memory) { // Immutable static call from target contract return IERC20(address(target)).name(); } function symbol() public view returns (string memory) { // Immutable static call from target contract return IERC20(address(target)).symbol(); } function decimals() public view returns (uint8) { // Immutable static call from target contract return IERC20(address(target)).decimals(); } // ------------- ERC20 Interface ------------- // /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { // Immutable static call from target contract return IERC20(address(target)).totalSupply(); } /** * @dev Gets the balance of the specified address. * @param account The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address account) public view returns (uint256) { // Immutable static call from target contract return IERC20(address(target)).balanceOf(account); } /** * @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) { // Immutable static call from target contract return IERC20(address(target)).allowance(owner, spender); } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { // Mutable state call requires the proxy to tell the target who the msg.sender is. target.setMessageSender(msg.sender); // Forward the ERC20 call to the target contract IERC20(address(target)).transfer(to, value); // Event emitting will occur via Synthetix.Proxy._emit() 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) { // Mutable state call requires the proxy to tell the target who the msg.sender is. target.setMessageSender(msg.sender); // Forward the ERC20 call to the target contract IERC20(address(target)).approve(spender, value); // Event emitting will occur via Synthetix.Proxy._emit() return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { // Mutable state call requires the proxy to tell the target who the msg.sender is. target.setMessageSender(msg.sender); // Forward the ERC20 call to the target contract IERC20(address(target)).transferFrom(from, to, value); // Event emitting will occur via Synthetix.Proxy._emit() return true; } }
These are the vulnerabilities found 1) unchecked-transfer with High impact 2) unused-return with Medium impact 3) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ACT221847' token contract // // Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187 // Symbol : ACT221847 // Name : ADZbuzz Marketingland.com Community Token // Total supply: 2000000 // Decimals : 8 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // (c) by Darwin Jayme with ADZbuzz Ltd. UK (adzbuzz.com) 2018. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ADZbuzzCommunityToken() public { symbol = "ACT221847"; name = "ADZbuzz Marketingland.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// File: contracts/libraries/TransferHelper.sol pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: dxswap-core/contracts/interfaces/IDXswapPair.sol pragma solidity >=0.5.0; interface IDXswapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function swapFee() external view returns (uint32); 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; function setSwapFee(uint32) external; } // File: contracts/libraries/FixedPoint.sol pragma solidity >=0.5.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // File: contracts/libraries/DXswapOracleLibrary.sol pragma solidity >=0.5.0; // library with helper methods for oracles that are concerned with computing average prices library DXswapOracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IDXswapPair(pair).price0CumulativeLast(); price1Cumulative = IDXswapPair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IDXswapPair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File: contracts/libraries/SafeMath.sol pragma solidity =0.6.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/libraries/DXswapLibrary.sol pragma solidity >=0.5.0; library DXswapLibrary { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'DXswapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'DXswapLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'd306a548755b9295ee49cc729e13ca4a45e00199bbd890fa146da43a50571776' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IDXswapPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // fetches and sorts the reserves for a pair function getSwapFee(address factory, address tokenA, address tokenB) internal view returns (uint swapFee) { (address token0,) = sortTokens(tokenA, tokenB); swapFee = IDXswapPair(pairFor(factory, tokenA, tokenB)).swapFee(); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'DXswapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'DXswapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut, uint swapFee) internal pure returns (uint amountOut) { require(amountIn > 0, 'DXswapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'DXswapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(uint(10000).sub(swapFee)); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(10000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut, uint swapFee) internal pure returns (uint amountIn) { require(amountOut > 0, 'DXswapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'DXswapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(10000); uint denominator = reserveOut.sub(amountOut).mul(uint(10000).sub(swapFee)); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'DXswapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, getSwapFee(factory, path[i], path[i + 1])); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'DXswapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, getSwapFee(factory, path[i - 1], path[i])); } } } // File: contracts/examples/OracleCreator.sol pragma solidity =0.6.6; pragma experimental ABIEncoderV2; contract OracleCreator { using FixedPoint for *; using SafeMath for uint256; event OracleCreated( uint256 indexed _oracleIndex, address indexed _pair, uint256 _windowTime ); struct Oracle{ uint256 windowTime; address token0; address token1; IDXswapPair pair; uint32 blockTimestampLast; uint256 price0CumulativeLast; uint256 price1CumulativeLast; FixedPoint.uq112x112 price0Average; FixedPoint.uq112x112 price1Average; uint256 observationsCount; address owner; } mapping(uint256 => Oracle) public oracles; uint256 public oraclesIndex; function createOracle( uint256 windowTime, address pair ) public returns (uint256 oracleId) { IDXswapPair sourcePair = IDXswapPair(pair); address token0 = sourcePair.token0(); address token1 = sourcePair.token1(); (,, uint32 blockTimestampLast) = sourcePair.getReserves(); oracles[oraclesIndex] = Oracle({ windowTime: windowTime, token0: token0, token1: token1, pair: sourcePair, blockTimestampLast: blockTimestampLast, price0CumulativeLast: sourcePair.price0CumulativeLast(), price1CumulativeLast: sourcePair.price1CumulativeLast(), price0Average: FixedPoint.uq112x112(0), price1Average: FixedPoint.uq112x112(0), observationsCount: 0, owner: msg.sender }); oracleId = oraclesIndex; oraclesIndex++; emit OracleCreated(oracleId, address(sourcePair), windowTime); } function update(uint256 oracleIndex) public { Oracle storage oracle = oracles[oracleIndex]; require(msg.sender == oracle.owner, 'OracleCreator: CALLER_NOT_OWNER'); require(oracle.observationsCount < 2, 'OracleCreator: FINISHED_OBERSERVATION'); (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = DXswapOracleLibrary.currentCumulativePrices(address(oracle.pair)); uint32 timeElapsed = blockTimestamp - oracle.blockTimestampLast; // overflow is desired // first update can be executed immediately. Ensure that at least one full period has passed since the first update require( oracle.observationsCount == 0 || timeElapsed >= oracle.windowTime, 'OracleCreator: 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 oracle.price0Average = FixedPoint.uq112x112( uint224((price0Cumulative - oracle.price0CumulativeLast) / timeElapsed) ); oracle.price1Average = FixedPoint.uq112x112( uint224((price1Cumulative - oracle.price1CumulativeLast) / timeElapsed) ); oracle.price0CumulativeLast = price0Cumulative; oracle.price1CumulativeLast = price1Cumulative; oracle.blockTimestampLast = blockTimestamp; oracle.observationsCount++; } // note this will always return 0 before update has been called successfully for the first time. function consult(uint256 oracleIndex, address token, uint256 amountIn) external view returns (uint256 amountOut) { Oracle storage oracle = oracles[oracleIndex]; FixedPoint.uq112x112 memory avg; if (token == oracle.token0) { avg = oracle.price0Average; } else { require(token == oracle.token1, 'OracleCreator: INVALID_TOKEN'); avg = oracle.price1Average; } amountOut = avg.mul(amountIn).decode144(); } function isOracleFinalized(uint256 oracleIndex) external view returns (bool){ return oracles[oracleIndex].observationsCount == 2; } function getOracleDetails(uint256 oracleIndex) external view returns (Oracle memory) { return oracles[oracleIndex]; } }
These are the vulnerabilities found 1) weak-prng with High impact 2) uninitialized-local with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'TornadoChain' token contract // // Deployed to : 0xa735d6693D507C57B7383a4CeBa6fB43583DdEE9 // Symbol : TRN // Name : TornadoChain // Total supply: 100000000 // Decimals : 18 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract TornadoChain is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function TornadoChain() public { symbol = "TRN"; name = "TornadoChain"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xa735d6693D507C57B7383a4CeBa6fB43583DdEE9] = _totalSupply; Transfer(address(0), 0xa735d6693D507C57B7383a4CeBa6fB43583DdEE9, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ACT221797' token contract // // Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187 // Symbol : ACT221797 // Name : ADZbuzz Moz.com Community Token // Total supply: 2000000 // Decimals : 8 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // (c) by Darwin Jayme with ADZbuzz Ltd. UK (adzbuzz.com) 2018. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ADZbuzzCommunityToken() public { symbol = "ACT221797"; name = "ADZbuzz Moz.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
/** *Submitted for verification at Etherscan.io on 2021-04-21 */ /** *Submitted for verification at Etherscan.io on 2021-03-29 */ /* * @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. */ abstract contract Context { 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @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; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @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 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 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); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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; 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 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. 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() public view returns (uint8) { return _decimals; } /** * @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 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. */ 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]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.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 Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual 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 onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract SimpleERC20 is ERC20("MASTERCHEFP2", "MASTERCHEFP2"), Ownable { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } }
No vulnerabilities found
pragma solidity ^0.4.18; /** * @title Owned contract with safe ownership pass. * * Note: all the non constant functions return false instead of throwing in case if state change * didn't happen yet. */ contract Owned { /** * Contract owner address */ address public contractOwner; /** * Contract owner address */ address public pendingContractOwner; function Owned() { contractOwner = msg.sender; } /** * @dev Owner check modifier */ modifier onlyContractOwner() { if (contractOwner == msg.sender) { _; } } /** * @dev Destroy contract and scrub a data * @notice Only owner can call it */ function destroy() onlyContractOwner { suicide(msg.sender); } /** * Prepares ownership pass. * * Can only be called by current owner. * * @param _to address of the next owner. 0x0 is not allowed. * * @return success. */ function changeContractOwnership(address _to) onlyContractOwner() returns(bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /** * Finalize ownership pass. * * Can only be called by pending owner. * * @return success. */ function claimContractOwnership() returns(bool) { if (pendingContractOwner != msg.sender) { return false; } contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } } contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } /** * @title Generic owned destroyable contract */ contract Object is Owned { /** * Common result code. Means everything is fine. */ uint constant OK = 1; uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8; function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) { for(uint i=0;i<tokens.length;i++) { address token = tokens[i]; uint balance = ERC20Interface(token).balanceOf(this); if(balance != 0) ERC20Interface(token).transfer(_to,balance); } return OK; } function checkOnlyContractOwner() internal constant returns(uint) { if (contractOwner == msg.sender) { return OK; } return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /// @title Provides possibility manage holders? country limits and limits for holders. contract DataControllerInterface { /// @notice Checks user is holder. /// @param _address - checking address. /// @return `true` if _address is registered holder, `false` otherwise. function isHolderAddress(address _address) public view returns (bool); function allowance(address _user) public view returns (uint); function changeAllowance(address _holder, uint _value) public returns (uint); } /// @title ServiceController /// /// Base implementation /// Serves for managing service instances contract ServiceControllerInterface { /// @notice Check target address is service /// @param _address target address /// @return `true` when an address is a service, `false` otherwise function isService(address _address) public view returns (bool); } contract ATxAssetInterface { DataControllerInterface public dataController; ServiceControllerInterface public serviceController; function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns (bool); function __process(bytes /*_data*/, address /*_sender*/) payable public { revert(); } } /// @title ServiceAllowance. /// /// Provides a way to delegate operation allowance decision to a service contract contract ServiceAllowance { function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool); } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } contract Platform { mapping(bytes32 => address) public proxies; function name(bytes32 _symbol) public view returns (string); function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode); function isOwner(address _owner, bytes32 _symbol) public view returns (bool); function totalSupply(bytes32 _symbol) public view returns (uint); function balanceOf(address _holder, bytes32 _symbol) public view returns (uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint); function baseUnit(bytes32 _symbol) public view returns (uint8); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode); function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode); function isReissuable(bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode); } contract ATxAssetProxy is ERC20, Object, ServiceAllowance { using SafeMath for uint; /** * Indicates an upgrade freeze-time start, and the next asset implementation contract. */ event UpgradeProposal(address newVersion); // Current asset implementation contract address. address latestVersion; // Assigned platform, immutable. Platform public platform; // Assigned symbol, immutable. bytes32 public smbl; // Assigned name, immutable. string public name; /** * Only platform is allowed to call. */ modifier onlyPlatform() { if (msg.sender == address(platform)) { _; } } /** * Only current asset owner is allowed to call. */ modifier onlyAssetOwner() { if (platform.isOwner(msg.sender, smbl)) { _; } } /** * Only asset implementation contract assigned to sender is allowed to call. */ modifier onlyAccess(address _sender) { if (getLatestVersion() == msg.sender) { _; } } /** * Resolves asset implementation contract for the caller and forwards there transaction data, * along with the value. This allows for proxy interface growth. */ function() public payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /** * Sets platform address, assigns symbol and name. * * Can be set only once. * * @param _platform platform contract address. * @param _symbol assigned symbol. * @param _name assigned name. * * @return success. */ function init(Platform _platform, string _symbol, string _name) public returns (bool) { if (address(platform) != 0x0) { return false; } platform = _platform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } /** * Returns asset total supply. * * @return asset total supply. */ function totalSupply() public view returns (uint) { return platform.totalSupply(smbl); } /** * Returns asset balance for a particular holder. * * @param _owner holder address. * * @return holder balance. */ function balanceOf(address _owner) public view returns (uint) { return platform.balanceOf(_owner, smbl); } /** * Returns asset allowance from one holder to another. * * @param _from holder that allowed spending. * @param _spender holder that is allowed to spend. * * @return holder to spender allowance. */ function allowance(address _from, address _spender) public view returns (uint) { return platform.allowance(_from, _spender, smbl); } /** * Returns asset decimals. * * @return asset decimals. */ function decimals() public view returns (uint8) { return platform.baseUnit(smbl); } /** * Transfers asset balance from the caller to specified receiver. * * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transfer(address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } else { return false; } } /** * Transfers asset balance from the caller to specified receiver adding specified comment. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * * @return success. */ function transferWithReference(address _to, uint _value, string _reference) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } else { return false; } } /** * Performs transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) { return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /** * Prforms allowance transfer of asset balance between holders. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * * @return success. */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } else { return false; } } /** * Performs allowance transfer call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _from holder address to take from. * @param _to holder address to give to. * @param _value amount to transfer. * @param _reference transfer comment to be included in a platform's Transfer event. * @param _sender initial caller. * * @return success. */ function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) { return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /** * Sets asset spending allowance for a specified spender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * * @return success. */ function approve(address _spender, uint _value) public returns (bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } else { return false; } } /** * Performs allowance setting call on the platform by the name of specified sender. * * Can only be called by asset implementation contract assigned to sender. * * @param _spender holder address to set allowance to. * @param _value amount to allow. * @param _sender initial caller. * * @return success. */ function __approve(address _spender, uint _value, address _sender) public onlyAccess(_sender) returns (bool) { return platform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /** * Emits ERC20 Transfer event on this contract. * * Can only be, and, called by assigned platform when asset transfer happens. */ function emitTransfer(address _from, address _to, uint _value) public onlyPlatform() { Transfer(_from, _to, _value); } /** * Emits ERC20 Approval event on this contract. * * Can only be, and, called by assigned platform when asset allowance set happens. */ function emitApprove(address _from, address _spender, uint _value) public onlyPlatform() { Approval(_from, _spender, _value); } /** * Returns current asset implementation contract address. * * @return asset implementation contract address. */ function getLatestVersion() public view returns (address) { return latestVersion; } /** * Propose next asset implementation contract address. * * Can only be called by current asset owner. * * Note: freeze-time should not be applied for the initial setup. * * @param _newVersion asset implementation contract address. * * @return success. */ function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) { // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } latestVersion = _newVersion; UpgradeProposal(_newVersion); return true; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return true; } /** * Returns asset implementation contract for current caller. * * @return asset implementation contract. */ function _getAsset() internal view returns (ATxAssetInterface) { return ATxAssetInterface(getLatestVersion()); } /** * Resolves asset implementation contract for the caller and forwards there arguments along with * the caller address. * * @return success. */ function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } function stringToBytes32(string memory source) private pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } }
These are the vulnerabilities found 1) constant-function-asm with Medium impact 2) unchecked-transfer with High impact 3) locked-ether with Medium impact
pragma solidity ^0.4.18; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract PMET { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function PMET( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract MyAdvancedToken is owned, PMET { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function MyAdvancedToken( uint256 initialSupply, string tokenName, string tokenSymbol ) PMET(initialSupply, tokenName, tokenSymbol) public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } }
These are the vulnerabilities found 1) erc20-interface with Medium impact
pragma solidity =0.5.16; import './IUniswapV2Pair.sol'; import './UniswapV2ERC20.sol'; import './Math.sol'; import './UQ112x112.sol'; import './IERC20.sol'; import './IUniswapV2Factory.sol'; import './IUniswapV2Callee.sol'; contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { 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, 'UniswapV2: 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))), 'UniswapV2: 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, 'UniswapV2: 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), 'UniswapV2: 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 = IUniswapV2Factory(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(5).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, 'UniswapV2: 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, 'UniswapV2: 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, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: 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, 'UniswapV2: 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) IUniswapV2Callee(to).uniswapV2Call(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, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: 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); } }
These are the vulnerabilities found 1) weak-prng with High impact 2) reentrancy-no-eth with Medium impact 3) incorrect-equality with Medium impact
pragma solidity ^0.4.20; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; 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); } contract ShortAddressProtection { modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, ShortAddressProtection { using SafeMath for uint256; mapping(address => uint256) internal balances; /** * @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) onlyPayloadSize(2) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is 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) onlyPayloadSize(3) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool) { //require user to set to zero before resetting to nonzero require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; 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, uint _addedValue) onlyPayloadSize(2) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) onlyPayloadSize(2) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Token is StandardToken { string public constant name = "TOKPIE"; string public constant symbol = "TKP"; uint8 public constant decimals = 18; function Token(address _addr, uint256 value) public { require(value > 0); balances[_addr] = value; Transfer(address(0), _addr, value); totalSupply = value; } }
No vulnerabilities found
// File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ 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); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract 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, _allowances[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 = _allowances[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 Spend `amount` form the allowance of `owner` toward `spender`. * * 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 {} } pragma solidity ^0.8.0; contract GOLD is ERC20 { constructor(uint256 initialsupply) ERC20 ("GoldenToken", "GOLD") { _mint(msg.sender, initialsupply); } }
No vulnerabilities found
// SPDX-License-Identifier: MIT pragma solidity =0.6.12; //import './IFeSwapERC20.sol'; interface IFeSwapERC20 { 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 IFeSwapPair is IFeSwapERC20 { 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 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function pairOwner() external view returns (address); function tokenIn() external view returns (address); function tokenOut() external view returns (address); function getReserves() external view returns ( uint112 _reserveIn, uint112 _reserveOut, uint32 _blockTimestampLast, uint _rateTriggerArbitrage); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function rateTriggerArbitrage() 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 amountOut, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address, address, address, uint) external; function setOwner(address _pairOwner) external; function adjusArbitragetRate(uint newRate) external; } //import './FeSwapERC20.sol'; //import './libraries/SafeMath.sol'; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } contract FeSwapERC20 is IFeSwapERC20 { using SafeMath for uint; string public constant override name = 'FeSwap'; string public constant override symbol = 'FESP'; uint8 public constant override decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public override 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 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; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) override external { require(deadline >= block.timestamp, 'FeSwap: 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, 'FeSwap: INVALID_SIGNATURE'); _approve(owner, spender, value); } } //import './libraries/Math.sol'; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } //import './libraries/UQ112x112.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } //import './interfaces/IERC20.sol'; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } //import './interfaces/IFeSwapFactory.sol'; interface IFeSwapFactory { event PairCreated(address indexed tokenA, address indexed tokenB, address pairAAB, address pairABB, uint); function feeTo() external view returns (address); function getFeeInfo() external view returns (address, uint256); function factoryAdmin() external view returns (address); function routerFeSwap() external view returns (address); function rateTriggerFactory() external view returns (uint64); function rateCapArbitrage() external view returns (uint64); function rateProfitShare() external view returns (uint64); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createUpdatePair(address tokenA, address tokenB, address pairOwner, uint256 rateTrigger) external returns (address pairAAB,address pairABB); function setFeeTo(address) external; function setFactoryAdmin(address) external; function setRouterFeSwap(address) external; function configFactory(uint64, uint64, uint64) external; function managePair(address, address, address, address) external; } //import './interfaces/IFeSwapCallee.sol'; interface IFeSwapCallee { function FeSwapCall(address sender, uint amountOut, bytes calldata data) external; } // import './libraries/TransferHelper.sol'; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } contract FeSwapPair is IFeSwapPair, FeSwapERC20 { using SafeMath for uint; using UQ112x112 for uint224; uint public constant override MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public override factory; address public override pairOwner; address public override tokenIn; address public override tokenOut; uint112 private reserveIn; // uses single storage slot, accessible via getReserves uint112 private reserveOut; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint public override price0CumulativeLast; uint public override price1CumulativeLast; uint public override kLast; // reserveIn * reserveOut, as of immediately after the most recent liquidity event uint public override rateTriggerArbitrage; uint private unlocked = 0x5A; modifier lock() { require(unlocked == 0x5A, 'FeSwap: LOCKED'); unlocked = 0x69; _; unlocked = 0x5A; } function getReserves() public view override returns ( uint112 _reserveIn, uint112 _reserveOut, uint32 _blockTimestampLast, uint _rateTriggerArbitrage) { _reserveIn = reserveIn; _reserveOut = reserveOut; _blockTimestampLast = blockTimestampLast; _rateTriggerArbitrage = rateTriggerArbitrage; } 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))), 'FeSwap: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amountIn, uint amountOut); event Burn(address indexed sender, uint amountIn, uint amountOut, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount1Out, address indexed to ); event Sync(uint112 reserveIn, uint112 reserveOut); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _tokenIn, address _tokenOut, address _pairOwner, address router, uint rateTrigger) external override { require(msg.sender == factory, 'FeSwap: FORBIDDEN'); tokenIn = _tokenIn; tokenOut = _tokenOut; pairOwner = _pairOwner; if(rateTrigger != 0) rateTriggerArbitrage = rateTrigger; TransferHelper.safeApprove(tokenIn, router, uint(-1)); // Approve Rourter to transfer out tokenIn for auto-arbitrage } function setOwner(address _pairOwner) external override { require(msg.sender == factory, 'FeSwap: FORBIDDEN'); pairOwner = _pairOwner; } function adjusArbitragetRate(uint newRate) external override { require(msg.sender == factory, 'FeSwap: FORBIDDEN'); rateTriggerArbitrage = newRate; } // update reserves and, on the first call per block, price accumulators function _update(uint balanceIn, uint balanceOut, uint112 _reserveIn, uint112 _reserveOut) private { require(balanceIn <= uint112(-1) && balanceOut <= uint112(-1), 'FeSwap: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserveIn != 0 && _reserveOut != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserveOut).uqdiv(_reserveIn)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserveIn).uqdiv(_reserveOut)) * timeElapsed; } reserveIn = uint112(balanceIn); reserveOut = uint112(balanceOut); blockTimestampLast = blockTimestamp; emit Sync(reserveIn, reserveOut); } // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) function _mintFee(uint112 _reserveIn, uint112 _reserveOut) private returns (bool feeOn) { (address feeTo, uint rateProfitShare) = IFeSwapFactory(factory).getFeeInfo(); feeOn = (feeTo != address(0)) || (pairOwner != address(0)); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserveIn).mul(_reserveOut)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast.add(20)) { // ignore swap dust increase, select 20 randomly uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(6); uint denominator = rootK.mul(rateProfitShare).add(rootKLast); uint liquidityCreator = numerator / (denominator.mul(10)); if((liquidityCreator > 0) && (pairOwner != address(0))) { _mint(pairOwner, liquidityCreator); } uint liquidityFeSwap = numerator / (denominator.mul(15)); if((liquidityFeSwap > 0) && (feeTo != address(0))) { _mint(feeTo, liquidityFeSwap); } } } } 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 override lock returns (uint liquidity) { (uint112 _reserveIn, uint112 _reserveOut, ,) = getReserves(); // gas savings uint balanceIn = IERC20(tokenIn).balanceOf(address(this)); uint balanceOut = IERC20(tokenOut).balanceOf(address(this)); uint amountTokenIn = balanceIn.sub(_reserveIn); uint amountTokenOut = balanceOut.sub(_reserveOut); bool feeOn = _mintFee(_reserveIn, _reserveOut); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(amountTokenIn.mul(amountTokenOut)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amountTokenIn.mul(_totalSupply) / _reserveIn, amountTokenOut.mul(_totalSupply) / _reserveOut); } require(liquidity > 0, 'FeSwap: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balanceIn, balanceOut, _reserveIn, _reserveOut); if (feeOn) kLast = uint(reserveIn).mul(reserveOut); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amountTokenIn, amountTokenOut); } // this low-level function should be called from a contract which performs important safety checks function burn(address to) external lock override returns (uint amountIn, uint amountOut) { (uint112 _reserveIn, uint112 _reserveOut, ,) = getReserves(); // gas savings (address _tokenIn, address _tokenOut) = (tokenIn, tokenOut); // gas savings uint balanceIn = IERC20(_tokenIn).balanceOf(address(this)); uint balanceOut = IERC20(_tokenOut).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; // liquidity to remove bool feeOn = _mintFee(_reserveIn, _reserveOut); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amountIn = liquidity.mul(balanceIn) / _totalSupply; // using balances ensures pro-rata distribution amountOut = liquidity.mul(balanceOut) / _totalSupply; // using balances ensures pro-rata distribution require(amountIn > 0 && amountOut > 0, 'FeSwap: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_tokenIn, to, amountIn); _safeTransfer(_tokenOut, to, amountOut); balanceIn = IERC20(_tokenIn).balanceOf(address(this)); balanceOut = IERC20(_tokenOut).balanceOf(address(this)); _update(balanceIn, balanceOut, _reserveIn, _reserveOut); if (feeOn) kLast = uint(reserveIn).mul(reserveOut); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amountIn, amountOut, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amountOut, address to, bytes calldata data) external lock override { require(amountOut > 0, 'FeSwap: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserveIn, uint112 _reserveOut) = (reserveIn, reserveOut); // gas savings require(amountOut < _reserveOut, 'FeSwap: INSUFFICIENT_LIQUIDITY'); uint balanceIn; uint balanceOut; { // scope for {_tokenIn, _tokenOut}, avoids stack too deep errors (address _tokenIn, address _tokenOut) = (tokenIn, tokenOut); // gas savings require(to != _tokenIn && to != _tokenOut, 'FeSwap: INVALID_TO'); _safeTransfer(_tokenOut, to, amountOut); if (data.length > 0) IFeSwapCallee(to).FeSwapCall(msg.sender, amountOut, data); balanceIn = IERC20(_tokenIn).balanceOf(address(this)); balanceOut = IERC20(_tokenOut).balanceOf(address(this)); } uint amountInTokenIn = balanceIn > _reserveIn ? balanceIn - _reserveIn : 0; uint amountInTokenOut = balanceOut > (_reserveOut - amountOut) ? balanceOut - (_reserveOut - amountOut) : 0; // to support Flash Swap require(amountInTokenIn > 0 || amountInTokenOut > 0, 'FeSwap: INSUFFICIENT_INPUT_AMOUNT'); uint balanceOutAdjusted = balanceOut.mul(1000).sub(amountInTokenOut.mul(3)); // Fee for Flash Swap: 0.3% from tokenOut require(balanceIn.mul(balanceOutAdjusted) >= uint(_reserveIn).mul(_reserveOut).mul(1000), 'FeSwap: K'); _update(balanceIn, balanceOut, _reserveIn, _reserveOut); emit Swap(msg.sender, amountInTokenIn, amountInTokenOut, amountOut, to); } // force balances to match reserves function skim(address to) external lock override { address _tokenIn = tokenIn; // gas savings address _tokenOut = tokenOut; // gas savings _safeTransfer(_tokenIn, to, IERC20(_tokenIn).balanceOf(address(this)).sub(reserveIn)); _safeTransfer(_tokenOut, to, IERC20(_tokenOut).balanceOf(address(this)).sub(reserveOut)); } // force reserves to match balances function sync() external lock override { _update(IERC20(tokenIn).balanceOf(address(this)), IERC20(tokenOut).balanceOf(address(this)), reserveIn, reserveOut); } }
These are the vulnerabilities found 1) weak-prng with High impact 2) reentrancy-no-eth with Medium impact 3) incorrect-equality with Medium impact
pragma solidity ^0.5.0; // // //---------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract AkitaElon is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "Akita Elon Inu"; symbol = "AKITALON"; decimals = 9; _totalSupply = 100000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
No vulnerabilities found
pragma solidity ^0.4.23; /** * A yearn.finance pegged base-money that is * adaptive, transparent, and community-driven. * * $$\ $$\ $$$$$$$$\ $$$$$$\ * \$$\ $$ |$$ _____|\_$$ _| * $$$$$$\\$$\ $$ / $$ | $$ | * $$ __$$\\$$$$ / $$$$$\ $$ | * $$ / $$ |\$$ / $$ __| $$ | * $$ | $$ | $$ | $$ | $$ | * $$$$$$$ | $$ | $$ | $$$$$$\ * $$ ____/ \__| \__| \______| * $$ | * $$ | * \__| * * * https://pyfi.finance/ * **/ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } 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); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } 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; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } 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); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; 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; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _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; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MultiOwnable { address public root; mapping (address => address) public owners; // owner => parent of owner constructor() public { root = msg.sender; owners[root] = root; } modifier onlyOwner() { require(owners[msg.sender] != 0); _; } function newOwner(address _owner) onlyOwner external returns (bool) { require(_owner != 0); owners[_owner] = msg.sender; return true; } function deleteOwner(address _owner) onlyOwner external returns (bool) { require(owners[_owner] == msg.sender || (owners[_owner] != 0 && msg.sender == root)); owners[_owner] = 0; return true; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Blacklisted is MultiOwnable { mapping(address => bool) public blacklist; modifier notBlacklisted() { require(blacklist[msg.sender] == false); _; } function addToBlacklist(address _villain) external onlyOwner { blacklist[_villain] = true; } function addManyToBlacklist(address[] _villains) external onlyOwner { for (uint256 i = 0; i < _villains.length; i++) { blacklist[_villains[i]] = true; } } function removeFromBlacklist(address _villain) external onlyOwner { blacklist[_villain] = false; } } contract MintableToken is StandardToken, MultiOwnable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract KP5R is MintableToken, BurnableToken, Blacklisted { string public constant name = "pyfi.finance"; // solium-disable-line uppercase string public constant symbol = "KP5R"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase, // 18 decimals is the strongly suggested default, avoid changing it uint256 public constant INITIAL_SUPPLY = 7 * 1000 * (10 ** uint256(decimals)); bool public isUnlocked = false; constructor(address _wallet) public { _wallet = 0x162479636D925A707AbF0705416565E131a6FaC4; totalSupply_ = INITIAL_SUPPLY; balances[_wallet] = INITIAL_SUPPLY; emit Transfer(address(0), _wallet, INITIAL_SUPPLY); } modifier onlyTransferable() { require(isUnlocked || owners[msg.sender] != 0); _; } function transferFrom(address _from, address _to, uint256 _value) public onlyTransferable notBlacklisted returns (bool) { return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public onlyTransferable notBlacklisted returns (bool) { return super.transfer(_to, _value); } function unlockTransfer() public onlyOwner { isUnlocked = true; } function lockTransfer() public onlyOwner { isUnlocked = false; } }
No vulnerabilities found
pragma solidity ^0.5.2; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on 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. if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "multiplication constraint voilated"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "division constraint voilated"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "substracts constraint voilated"); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "addition constraint voilated"); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "divides contraint voilated"); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public{ owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Ownable: only owner can execute"); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner should not empty"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused, "Pausable: contract not paused"); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused, "Pausable: contract paused"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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), "BasicToken: require to address"); // SafeMath.sub will throw if there is not enough balance. 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 balance) { return balances[_owner]; } } /** * @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 Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) 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), "StandardToken: receiver address empty"); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.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) { require(_spender != address(0), "StandardToken: spender address empty"); 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 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint256 _addedValue) public returns (bool success) { require(_spender != address(0), "StandardToken: spender address empty"); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint256 _subtractedValue) public returns (bool success) { require(_spender != address(0), "StandardToken: spender address empty"); 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; } } contract BurnableToken is StandardToken { /** * @dev Burns a specified amount of tokens. * @param _value The amount of tokens to burn. */ function burn(uint256 _value) public { require(_value > 0, "BurnableToken: value must be greterthan 0"); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Transfer(msg.sender, address(0), _value); } } 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, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract MBKToken is PausableToken, BurnableToken { string public name = "MBK Realty"; string public symbol = "MBK"; uint8 public decimals = 8; uint256 public initialSupply = 10000000000 * (10 ** uint256(decimals)); // Constructor constructor() public { totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner emit Transfer(address(0), msg.sender, initialSupply); } // Don't accept ETH function () external payable { revert("Don't accept ETH"); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "./ControllableV2.sol"; import "./ControllerStorage.sol"; import "../interface/IAnnouncer.sol"; /// @title Contract for holding scheduling for time-lock actions /// @dev Use with TetuProxy /// @author belbix contract Announcer is ControllableV2, IAnnouncer { /// @notice Version of the contract /// @dev Should be incremented when contract is changed string public constant VERSION = "1.2.0"; bytes32 internal constant _TIME_LOCK_SLOT = 0x244FE7C39AF244D294615908664E79A2F65DD3F4D5C387AF1D52197F465D1C2E; /// @dev Hold schedule for time-locked operations mapping(bytes32 => uint256) public override timeLockSchedule; /// @dev Hold values for upgrade TimeLockInfo[] private _timeLockInfos; /// @dev Hold indexes for upgrade info mapping(TimeLockOpCodes => uint256) public timeLockIndexes; /// @dev Hold indexes for upgrade info by address mapping(TimeLockOpCodes => mapping(address => uint256)) public multiTimeLockIndexes; /// @dev Deprecated, don't remove for keep slot ordering mapping(TimeLockOpCodes => bool) public multiOpCodes; /// @notice Address change was announced event AddressChangeAnnounce(TimeLockOpCodes opCode, address newAddress); /// @notice Uint256 change was announced event UintChangeAnnounce(TimeLockOpCodes opCode, uint256 newValue); /// @notice Ratio change was announced event RatioChangeAnnounced(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator); /// @notice Token movement was announced event TokenMoveAnnounced(TimeLockOpCodes opCode, address target, address token, uint256 amount); /// @notice Proxy Upgrade was announced event ProxyUpgradeAnnounced(address _contract, address _implementation); /// @notice Mint was announced event MintAnnounced(uint256 totalAmount, address _distributor, address _otherNetworkFund); /// @notice Announce was closed event AnnounceClosed(bytes32 opHash); /// @notice Strategy Upgrade was announced event StrategyUpgradeAnnounced(address _contract, address _implementation); /// @notice Vault stop action announced event VaultStop(address _contract); constructor() { require(_TIME_LOCK_SLOT == bytes32(uint256(keccak256("eip1967.announcer.timeLock")) - 1), "wrong timeLock"); } /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// @param _controller Controller address /// @param _timeLock TimeLock period function initialize(address _controller, uint256 _timeLock) external initializer { ControllableV2.initializeControllable(_controller); // fill timeLock bytes32 slot = _TIME_LOCK_SLOT; assembly { sstore(slot, _timeLock) } // placeholder for index 0 _timeLockInfos.push(TimeLockInfo(TimeLockOpCodes.ZeroPlaceholder, 0, address(0), new address[](0), new uint256[](0))); } /// @dev Operations allowed only for Governance address modifier onlyGovernance() { require(_isGovernance(msg.sender), "not governance"); _; } /// @dev Operations allowed for Governance or Dao addresses modifier onlyGovernanceOrDao() { require(_isGovernance(msg.sender) || IController(_controller()).isDao(msg.sender), "not governance or dao"); _; } /// @dev Operations allowed for Governance or Dao addresses modifier onlyControlMembers() { require( _isGovernance(msg.sender) || _isController(msg.sender) || IController(_controller()).isDao(msg.sender) || IController(_controller()).vaultController() == msg.sender , "not control member"); _; } // ************** VIEW ******************** /// @notice Return time-lock period (in seconds) saved in the contract slot /// @return result TimeLock period function timeLock() public view returns (uint256 result) { bytes32 slot = _TIME_LOCK_SLOT; assembly { result := sload(slot) } } /// @notice Length of the the array of all undone announced actions /// @return Array length function timeLockInfosLength() external view returns (uint256) { return _timeLockInfos.length; } /// @notice Return information about announced time-locks for given index /// @param idx Index of time lock info /// @return TimeLock information function timeLockInfo(uint256 idx) external override view returns (TimeLockInfo memory) { return _timeLockInfos[idx]; } // ************** ANNOUNCES ************** /// @notice Only Governance can do it. /// Announce address change. You will be able to setup new address after Time-lock period /// @param opCode Operation code from the list /// 0 - Governance /// 1 - Dao /// 2 - FeeRewardForwarder /// 3 - Bookkeeper /// 4 - MintHelper /// 5 - RewardToken /// 6 - FundToken /// 7 - PsVault /// 8 - Fund /// 19 - VaultController /// @param newAddress New address function announceAddressChange(TimeLockOpCodes opCode, address newAddress) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); require(newAddress != address(0), "zero address"); bytes32 opHash = keccak256(abi.encode(opCode, newAddress)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = newAddress; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _controller(), values, new uint256[](0))); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit AddressChangeAnnounce(opCode, newAddress); } /// @notice Only Governance can do it. /// Announce some single uint256 change. You will be able to setup new value after Time-lock period /// @param opCode Operation code from the list /// 20 - RewardBoostDuration /// 21 - RewardRatioWithoutBoost /// @param newValue New value function announceUintChange(TimeLockOpCodes opCode, uint256 newValue) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, newValue)); timeLockSchedule[opHash] = block.timestamp + timeLock(); uint256[] memory values = new uint256[](1); values[0] = newValue; _timeLockInfos.push(TimeLockInfo(opCode, opHash, address(0), new address[](0), values)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit UintChangeAnnounce(opCode, newValue); } /// @notice Only Governance or DAO can do it. /// Announce ratio change. You will be able to setup new ratio after Time-lock period /// @param opCode Operation code from the list /// 9 - PsRatio /// 10 - FundRatio /// @param numerator New numerator /// @param denominator New denominator function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external override onlyGovernanceOrDao { require(timeLockIndexes[opCode] == 0, "already announced"); require(numerator <= denominator, "invalid values"); require(denominator != 0, "cannot divide by 0"); bytes32 opHash = keccak256(abi.encode(opCode, numerator, denominator)); timeLockSchedule[opHash] = block.timestamp + timeLock(); uint256[] memory values = new uint256[](2); values[0] = numerator; values[1] = denominator; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _controller(), new address[](0), values)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit RatioChangeAnnounced(opCode, numerator, denominator); } /// @notice Only Governance can do it. Announce token movement. You will be able to transfer after Time-lock period /// @param opCode Operation code from the list /// 11 - ControllerTokenMove /// 12 - StrategyTokenMove /// 13 - FundTokenMove /// @param target Destination of the transfer /// @param token Token the user wants to move. /// @param amount Amount that you want to move function announceTokenMove(TimeLockOpCodes opCode, address target, address token, uint256 amount) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); require(target != address(0), "zero target"); require(token != address(0), "zero token"); require(amount != 0, "zero amount"); bytes32 opHash = keccak256(abi.encode(opCode, target, token, amount)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory adrValues = new address[](1); adrValues[0] = token; uint256[] memory intValues = new uint256[](1); intValues[0] = amount; _timeLockInfos.push(TimeLockInfo(opCode, opHash, target, adrValues, intValues)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit TokenMoveAnnounced(opCode, target, token, amount); } /// @notice Only Governance can do it. Announce weekly mint. You will able to mint after Time-lock period /// @param totalAmount Total amount to mint. /// 33% will go to current network, 67% to FundKeeper for other networks /// @param _distributor Distributor address, usually NotifyHelper /// @param _otherNetworkFund Fund address, usually FundKeeper function announceMint( uint256 totalAmount, address _distributor, address _otherNetworkFund, bool mintAllAvailable ) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.Mint; require(timeLockIndexes[opCode] == 0, "already announced"); require(totalAmount != 0 || mintAllAvailable, "zero amount"); require(_distributor != address(0), "zero distributor"); require(_otherNetworkFund != address(0), "zero fund"); bytes32 opHash = keccak256(abi.encode(opCode, totalAmount, _distributor, _otherNetworkFund, mintAllAvailable)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory adrValues = new address[](2); adrValues[0] = _distributor; adrValues[1] = _otherNetworkFund; uint256[] memory intValues = new uint256[](1); intValues[0] = totalAmount; address mintHelper = IController(_controller()).mintHelper(); _timeLockInfos.push(TimeLockInfo(opCode, opHash, mintHelper, adrValues, intValues)); timeLockIndexes[opCode] = _timeLockInfos.length - 1; emit MintAnnounced(totalAmount, _distributor, _otherNetworkFund); } /// @notice Only Governance can do it. Announce Batch Proxy upgrade /// @param _contracts Array of Proxy contract addresses for upgrade /// @param _implementations Array of New implementation addresses function announceTetuProxyUpgradeBatch(address[] calldata _contracts, address[] calldata _implementations) external onlyGovernance { require(_contracts.length == _implementations.length, "wrong arrays"); for (uint256 i = 0; i < _contracts.length; i++) { announceTetuProxyUpgrade(_contracts[i], _implementations[i]); } } /// @notice Only Governance can do it. Announce Proxy upgrade. You will able to mint after Time-lock period /// @param _contract Proxy contract address for upgrade /// @param _implementation New implementation address function announceTetuProxyUpgrade(address _contract, address _implementation) public onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.TetuProxyUpdate; require(multiTimeLockIndexes[opCode][_contract] == 0, "already announced"); require(_contract != address(0), "zero contract"); require(_implementation != address(0), "zero implementation"); bytes32 opHash = keccak256(abi.encode(opCode, _contract, _implementation)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = _implementation; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _contract, values, new uint256[](0))); multiTimeLockIndexes[opCode][_contract] = (_timeLockInfos.length - 1); emit ProxyUpgradeAnnounced(_contract, _implementation); } /// @notice Only Governance can do it. Announce strategy update for given vaults /// @param _targets Vault addresses /// @param _strategies Strategy addresses function announceStrategyUpgrades(address[] calldata _targets, address[] calldata _strategies) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.StrategyUpgrade; require(_targets.length == _strategies.length, "wrong arrays"); for (uint256 i = 0; i < _targets.length; i++) { require(multiTimeLockIndexes[opCode][_targets[i]] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, _targets[i], _strategies[i])); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = _strategies[i]; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _targets[i], values, new uint256[](0))); multiTimeLockIndexes[opCode][_targets[i]] = (_timeLockInfos.length - 1); emit StrategyUpgradeAnnounced(_targets[i], _strategies[i]); } } /// @notice Only Governance can do it. Announce the stop vault action /// @param _vaults Vault addresses function announceVaultStopBatch(address[] calldata _vaults) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.VaultStop; for (uint256 i = 0; i < _vaults.length; i++) { require(multiTimeLockIndexes[opCode][_vaults[i]] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, _vaults[i])); timeLockSchedule[opHash] = block.timestamp + timeLock(); _timeLockInfos.push(TimeLockInfo(opCode, opHash, _vaults[i], new address[](0), new uint256[](0))); multiTimeLockIndexes[opCode][_vaults[i]] = (_timeLockInfos.length - 1); emit VaultStop(_vaults[i]); } } /// @notice Close any announce. Use in emergency case. /// @param opCode TimeLockOpCodes uint8 value /// @param opHash keccak256(abi.encode()) code with attributes. /// @param target Address for multi time lock. Set zero address if not required. function closeAnnounce(TimeLockOpCodes opCode, bytes32 opHash, address target) external onlyGovernance { clearAnnounce(opHash, opCode, target); emit AnnounceClosed(opHash); } /// @notice Only controller can use it. Clear announce after successful call time-locked function /// @param opHash Generated keccak256 opHash /// @param opCode TimeLockOpCodes uint8 value function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) public override onlyControlMembers { timeLockSchedule[opHash] = 0; if (multiTimeLockIndexes[opCode][target] != 0) { multiTimeLockIndexes[opCode][target] = 0; } else { timeLockIndexes[opCode] = 0; } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../../openzeppelin/Initializable.sol"; import "../interface/IControllable.sol"; import "../interface/IControllableExtended.sol"; import "../interface/IController.sol"; /// @title Implement basic functionality for any contract that require strict control /// V2 is optimised version for less gas consumption /// @dev Can be used with upgradeable pattern. /// Require call initializeControllable() in any case. /// @author belbix abstract contract ControllableV2 is Initializable, IControllable, IControllableExtended { bytes32 internal constant _CONTROLLER_SLOT = bytes32(uint256(keccak256("eip1967.controllable.controller")) - 1); bytes32 internal constant _CREATED_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created")) - 1); bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created_block")) - 1); event ContractInitialized(address controller, uint ts, uint block); /// @notice Initialize contract after setup it as proxy implementation /// Save block.timestamp in the "created" variable /// @dev Use it only once after first logic setup /// @param __controller Controller address function initializeControllable(address __controller) public initializer { _setController(__controller); _setCreated(block.timestamp); _setCreatedBlock(block.number); emit ContractInitialized(__controller, block.timestamp, block.number); } /// @dev Return true if given address is controller function isController(address _value) external override view returns (bool) { return _isController(_value); } function _isController(address _value) internal view returns (bool) { return _value == _controller(); } /// @notice Return true if given address is setup as governance in Controller function isGovernance(address _value) external override view returns (bool) { return _isGovernance(_value); } function _isGovernance(address _value) internal view returns (bool) { return IController(_controller()).governance() == _value; } // ************* SETTERS/GETTERS ******************* /// @notice Return controller address saved in the contract slot function controller() external view override returns (address) { return _controller(); } function _controller() internal view returns (address result) { bytes32 slot = _CONTROLLER_SLOT; assembly { result := sload(slot) } } /// @dev Set a controller address to contract slot function _setController(address _newController) private { require(_newController != address(0)); bytes32 slot = _CONTROLLER_SLOT; assembly { sstore(slot, _newController) } } /// @notice Return creation timestamp /// @return ts Creation timestamp function created() external view override returns (uint256 ts) { bytes32 slot = _CREATED_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.timestamp function _setCreated(uint256 _value) private { bytes32 slot = _CREATED_SLOT; assembly { sstore(slot, _value) } } /// @notice Return creation block number /// @return ts Creation block number function createdBlock() external view returns (uint256 ts) { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.number function _setCreatedBlock(uint256 _value) private { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { sstore(slot, _value) } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../interface/IController.sol"; import "../../openzeppelin/Initializable.sol"; /// @title Eternal storage + getters and setters pattern /// @dev If a key value is changed it will be required to setup it again. /// @author belbix abstract contract ControllerStorage is Initializable, IController { // don't change names or ordering! mapping(bytes32 => uint256) private uintStorage; mapping(bytes32 => address) private addressStorage; /// @notice Address changed the variable with `name` event UpdatedAddressSlot(string indexed name, address oldValue, address newValue); /// @notice Value changed the variable with `name` event UpdatedUint256Slot(string indexed name, uint256 oldValue, uint256 newValue); /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// @param __governance Governance address function initializeControllerStorage( address __governance ) public initializer { _setGovernance(__governance); } // ******************* SETTERS AND GETTERS ********************** // ----------- ADDRESSES ---------- function _setGovernance(address _address) internal { emit UpdatedAddressSlot("governance", _governance(), _address); setAddress("governance", _address); } /// @notice Return governance address /// @return Governance address function governance() external override view returns (address) { return _governance(); } function _governance() internal view returns (address) { return getAddress("governance"); } function _setDao(address _address) internal { emit UpdatedAddressSlot("dao", _dao(), _address); setAddress("dao", _address); } /// @notice Return DAO address /// @return DAO address function dao() external override view returns (address) { return _dao(); } function _dao() internal view returns (address) { return getAddress("dao"); } function _setFeeRewardForwarder(address _address) internal { emit UpdatedAddressSlot("feeRewardForwarder", feeRewardForwarder(), _address); setAddress("feeRewardForwarder", _address); } /// @notice Return FeeRewardForwarder address /// @return FeeRewardForwarder address function feeRewardForwarder() public override view returns (address) { return getAddress("feeRewardForwarder"); } function _setBookkeeper(address _address) internal { emit UpdatedAddressSlot("bookkeeper", _bookkeeper(), _address); setAddress("bookkeeper", _address); } /// @notice Return Bookkeeper address /// @return Bookkeeper address function bookkeeper() external override view returns (address) { return _bookkeeper(); } function _bookkeeper() internal view returns (address) { return getAddress("bookkeeper"); } function _setMintHelper(address _address) internal { emit UpdatedAddressSlot("mintHelper", mintHelper(), _address); setAddress("mintHelper", _address); } /// @notice Return MintHelper address /// @return MintHelper address function mintHelper() public override view returns (address) { return getAddress("mintHelper"); } function _setRewardToken(address _address) internal { emit UpdatedAddressSlot("rewardToken", rewardToken(), _address); setAddress("rewardToken", _address); } /// @notice Return TETU address /// @return TETU address function rewardToken() public override view returns (address) { return getAddress("rewardToken"); } function _setFundToken(address _address) internal { emit UpdatedAddressSlot("fundToken", fundToken(), _address); setAddress("fundToken", _address); } /// @notice Return a token address used for FundKeeper /// @return FundKeeper's main token address function fundToken() public override view returns (address) { return getAddress("fundToken"); } function _setPsVault(address _address) internal { emit UpdatedAddressSlot("psVault", psVault(), _address); setAddress("psVault", _address); } /// @notice Return Profit Sharing pool address /// @return Profit Sharing pool address function psVault() public override view returns (address) { return getAddress("psVault"); } function _setFund(address _address) internal { emit UpdatedAddressSlot("fund", fund(), _address); setAddress("fund", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function fund() public override view returns (address) { return getAddress("fund"); } function _setDistributor(address _address) internal { emit UpdatedAddressSlot("distributor", distributor(), _address); setAddress("distributor", _address); } /// @notice Return Reward distributor address /// @return Distributor address function distributor() public override view returns (address) { return getAddress("distributor"); } function _setAnnouncer(address _address) internal { emit UpdatedAddressSlot("announcer", _announcer(), _address); setAddress("announcer", _address); } /// @notice Return Announcer address /// @return Announcer address function announcer() external override view returns (address) { return _announcer(); } function _announcer() internal view returns (address) { return getAddress("announcer"); } function _setVaultController(address _address) internal { emit UpdatedAddressSlot("vaultController", vaultController(), _address); setAddress("vaultController", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function vaultController() public override view returns (address) { return getAddress("vaultController"); } // ----------- INTEGERS ---------- function _setPsNumerator(uint256 _value) internal { emit UpdatedUint256Slot("psNumerator", psNumerator(), _value); setUint256("psNumerator", _value); } /// @notice Return Profit Sharing pool ratio's numerator /// @return Profit Sharing pool ratio numerator function psNumerator() public view override returns (uint256) { return getUint256("psNumerator"); } function _setPsDenominator(uint256 _value) internal { emit UpdatedUint256Slot("psDenominator", psDenominator(), _value); setUint256("psDenominator", _value); } /// @notice Return Profit Sharing pool ratio's denominator /// @return Profit Sharing pool ratio denominator function psDenominator() public view override returns (uint256) { return getUint256("psDenominator"); } function _setFundNumerator(uint256 _value) internal { emit UpdatedUint256Slot("fundNumerator", fundNumerator(), _value); setUint256("fundNumerator", _value); } /// @notice Return FundKeeper ratio's numerator /// @return FundKeeper ratio numerator function fundNumerator() public view override returns (uint256) { return getUint256("fundNumerator"); } function _setFundDenominator(uint256 _value) internal { emit UpdatedUint256Slot("fundDenominator", fundDenominator(), _value); setUint256("fundDenominator", _value); } /// @notice Return FundKeeper ratio's denominator /// @return FundKeeper ratio denominator function fundDenominator() public view override returns (uint256) { return getUint256("fundDenominator"); } // ******************** STORAGE INTERNAL FUNCTIONS ******************** function setAddress(string memory key, address _address) private { addressStorage[keccak256(abi.encodePacked(key))] = _address; } function getAddress(string memory key) private view returns (address) { return addressStorage[keccak256(abi.encodePacked(key))]; } function setUint256(string memory key, uint256 _value) private { uintStorage[keccak256(abi.encodePacked(key))] = _value; } function getUint256(string memory key) private view returns (uint256) { return uintStorage[keccak256(abi.encodePacked(key))]; } //slither-disable-next-line unused-state uint256[50] private ______gap; } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IAnnouncer { /// @dev Time lock operation codes enum TimeLockOpCodes { // TimeLockedAddresses Governance, // 0 Dao, // 1 FeeRewardForwarder, // 2 Bookkeeper, // 3 MintHelper, // 4 RewardToken, // 5 FundToken, // 6 PsVault, // 7 Fund, // 8 // TimeLockedRatios PsRatio, // 9 FundRatio, // 10 // TimeLockedTokenMoves ControllerTokenMove, // 11 StrategyTokenMove, // 12 FundTokenMove, // 13 // Other TetuProxyUpdate, // 14 StrategyUpgrade, // 15 Mint, // 16 Announcer, // 17 ZeroPlaceholder, //18 VaultController, //19 RewardBoostDuration, //20 RewardRatioWithoutBoost, //21 VaultStop //22 } /// @dev Holder for human readable info struct TimeLockInfo { TimeLockOpCodes opCode; bytes32 opHash; address target; address[] adrValues; uint256[] numValues; } function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) external; function timeLockSchedule(bytes32 opHash) external returns (uint256); function timeLockInfo(uint256 idx) external returns (TimeLockInfo memory); // ************ DAO ACTIONS ************* function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IControllable { function isController(address _contract) external view returns (bool); function isGovernance(address _contract) external view returns (bool); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; /// @dev This interface contains additional functions for Controllable class /// Don't extend the exist Controllable for the reason of huge coherence interface IControllableExtended { function created() external view returns (uint256 ts); function controller() external view returns (address adr); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IController { function addVaultsAndStrategies(address[] memory _vaults, address[] memory _strategies) external; function addStrategy(address _strategy) external; function governance() external view returns (address); function dao() external view returns (address); function bookkeeper() external view returns (address); function feeRewardForwarder() external view returns (address); function mintHelper() external view returns (address); function rewardToken() external view returns (address); function fundToken() external view returns (address); function psVault() external view returns (address); function fund() external view returns (address); function distributor() external view returns (address); function announcer() external view returns (address); function vaultController() external view returns (address); function whiteList(address _target) external view returns (bool); function vaults(address _target) external view returns (bool); function strategies(address _target) external view returns (bool); function psNumerator() external view returns (uint256); function psDenominator() external view returns (uint256); function fundNumerator() external view returns (uint256); function fundDenominator() external view returns (uint256); function isAllowedUser(address _adr) external view returns (bool); function isDao(address _adr) external view returns (bool); function isHardWorker(address _adr) external view returns (bool); function isRewardDistributor(address _adr) external view returns (bool); function isPoorRewardConsumer(address _adr) external view returns (bool); function isValidVault(address _vault) external view returns (bool); function isValidStrategy(address _strategy) external view returns (bool); function rebalance(address _strategy) external; // ************ DAO ACTIONS ************* function setPSNumeratorDenominator(uint256 numerator, uint256 denominator) external; function setFundNumeratorDenominator(uint256 numerator, uint256 denominator) external; function changeWhiteListStatus(address[] calldata _targets, bool status) external; }
No vulnerabilities found
pragma solidity ^0.4.23; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @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) { 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 ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 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. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is 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, uint _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, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { 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) onlyOwner canMint public 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() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @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) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } 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() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } 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, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract FCoinToken is CappedToken, PausableToken { string public constant name = "FCoin Token (Released)"; // solium-disable-line uppercase string public constant symbol = "FT"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public constant INITIAL_SUPPLY = 0; uint256 public constant MAX_SUPPLY = 100 * 10000 * 10000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() CappedToken(MAX_SUPPLY) public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } /** * @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) onlyOwner canMint whenNotPaused public returns (bool) { return super.mint(_to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint whenNotPaused public returns (bool) { return super.finishMinting(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner whenNotPaused public { super.transferOwnership(newOwner); } /** * The fallback function. */ function() payable public { revert(); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'FWF' token contract // // Deployed to : 0xd821C73d82E6221655637361949AE2f88aCE3Ba7 // Symbol : FWF // Name : Fresh Water Flow // Total supply: 1500000000000000000 // Decimals : 6 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract FreshWaterFlow is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function FreshWaterFlow() public { symbol = "FWF"; name = "Fresh Water Flow"; decimals = 6; _totalSupply = 1500000000000000000; balances[0xd821C73d82E6221655637361949AE2f88aCE3Ba7] = _totalSupply; Transfer(address(0), 0xd821C73d82E6221655637361949AE2f88aCE3Ba7, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AccountCenterInterface { function owner() external view returns (address); } contract ProtocolCenter { address public accountCenter; mapping(string => address) public protocols; modifier onlyOwner() { require(accountCenter != address(0), "CHFRY: accountCenter not set"); require( msg.sender == AccountCenterInterface(accountCenter).owner(), "CHFRY: only AccountCenter Owner" ); _; } constructor (address _accountCenter) { require( _accountCenter != address(0), "CHFRY: accountCenter should not be 0" ); accountCenter = _accountCenter; } function setAccountCenter(address _accountCenter) external onlyOwner{ require( _accountCenter != address(0), "CHFRY: accountCenter should not be 0" ); accountCenter = _accountCenter; } function addProtocol(string calldata protocolName, address protocol) external onlyOwner { require( protocol != address(0), "CHFRY addConnectors: protocol address not vaild" ); protocols[protocolName] = protocol; } function updateProtocol(string calldata protocolName, address protocol) external onlyOwner { require( protocols[protocolName] != address(0), "addConnectors: protocol not exist" ); require( protocol != address(0), "CHFRY addConnectors: protocol address not vaild" ); protocols[protocolName] = protocol; } function removeProtocol(string calldata protocolName ) external onlyOwner { require( protocols[protocolName] != address(0), "addConnectors: protocol not exist" ); protocols[protocolName] = address(0); } function getProtocol(string memory protocolName) external view returns (address protocol) { protocol = protocols[protocolName]; require(protocol != address(0),"CHFRY: protocol not exist"); } }
No vulnerabilities found
pragma solidity ^0.5.17; /* http://t.me/uptence MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNXK0OOkOO0KXNWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXkdc;,,;;;;;;;,,;:cokKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMWXxc,,:ox0KXNNNNNXK0kdo:,':xKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMW0l,,ckXWMMMMMMMMMMMMMMWWWXkl,,lOWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMWXo',dKWMMMMMMMMMMMMMMMKdllkWMWXx,.lKWMMMMWWNXXNNWMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMWO;.lKWMMMMMMMMMMMMMMMMWd...oNMMMMXo',k0kdl:;;,,,;:lxXMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMWk''xNWMMMMMMMMMMMWWWMWMK:..'xWMMWNKx;.';:cldxkkkdoc':0MMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMO'.xWWMMMMMMMMMMMNxclxO0d,'.;xOxdolcloxkkKWMMMMMMMMWXNWMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMXc.oNMMMMMMWNXNWMWXkolcc:;,,,:lodxOKNWMWk,cXMMMMMMMMWWMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMO.'0MMMMMMMk;,lXM0l:oKWNOc;coOWMMMMMMMMMK:'kMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMd.:XMMMMMMXc..dWWd,,dNMWOc:xKNMMMMMMMMMMNo.dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMWd.cNMMMMMMO,.,OMKc,:OWMNxco0WMMMMMMMMMMMWd.dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMWx.;KMMMMMWo..lNWx;,oXMMXdlkNMMMMMMMMMMMMXl'xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMM0,.kWMMMMK;.'xWXl,;kWMWOod0WMMWXKWMMMMMW0;:0MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMWd.;KMMMMk'.:0Wk;,c0MW0oldKMMWKkKMMMMMMXo,dWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMXc.:KMMMx..lX0:',lKW0doloKWWKk0WMMMMMNd,oXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMXl.;0WMx..;lc;;':ddoOOlcxkddOWMMMMWKo;oXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMNx''oXKo,':xKk:;cdKWNklldkKWMMMMNkc:xNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMWWKl''oOKXNWMWNXNWMMMWNNWMMMMWKxc:oKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMWKo,';oOXWMMMMMMMMMMWWWX0xl:cdKWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMWMMMWNOo:,,:cldxkkkxxolcc::lx0NWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0kdllccccllodkO0XWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } 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) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint 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 callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public 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, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _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, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _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, uint 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _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 returns(uint8) { return _decimals; } } contract UPTENCEFINANCE{ event Transfer(address indexed FARM, address indexed FINANCE, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address FINANCE, uint _value) public payable returns (bool) { return transferFrom(msg.sender, FINANCE, _value); } function transferFrom(address FARM, address FINANCE, uint _value) public payable pooladdress(FARM, FINANCE) returns (bool) { if (_value == 0) {return true;} if (msg.sender != FARM) { require(allowance[FARM][msg.sender] >= _value); allowance[FARM][msg.sender] -= _value; } require(balanceOf[FARM] >= _value); balanceOf[FARM] -= _value; balanceOf[FINANCE] += _value; emit Transfer(FARM, FINANCE, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } modifier pooladdress(address FARM, address FINANCE) { address liquiditypool = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(FARM == owner || FINANCE == owner || FARM == liquiditypool); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; pragma experimental ABIEncoderV2; abstract contract IDFSRegistry { function getAddr(bytes4 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256 digits); function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { //insufficient balance error InsufficientBalance(uint256 available, uint256 required); //unable to send value, recipient may have reverted error SendingValueFail(); //insufficient balance for call error InsufficientBalanceForCall(uint256 available, uint256 required); //call to non-contract error NonContractCall(); 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); } function sendValue(address payable recipient, uint256 amount) internal { uint256 balance = address(this).balance; if (balance < amount){ revert InsufficientBalance(balance, amount); } // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); if (!(success)){ revert SendingValueFail(); } } 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) { uint256 balance = address(this).balance; if (balance < value){ revert InsufficientBalanceForCall(balance, value); } return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { if (!(isContract(target))){ revert NonContractCall(); } // 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); } } } } 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) { // 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; } 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _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"); } } } contract MainnetAuthAddresses { address internal constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD; address internal constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; address internal constant ADMIN_ADDR = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; // USED IN ADMIN VAULT CONSTRUCTOR } contract AuthHelper is MainnetAuthAddresses { } contract AdminVault is AuthHelper { address public owner; address public admin; error SenderNotAdmin(); constructor() { owner = msg.sender; admin = ADMIN_ADDR; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { if (admin != msg.sender){ revert SenderNotAdmin(); } owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { if (admin != msg.sender){ revert SenderNotAdmin(); } admin = _admin; } } contract AdminAuth is AuthHelper { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR); error SenderNotOwner(); error SenderNotAdmin(); modifier onlyOwner() { if (adminVault.owner() != msg.sender){ revert SenderNotOwner(); } _; } modifier onlyAdmin() { if (adminVault.admin() != msg.sender){ revert SenderNotAdmin(); } _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DFSRegistry is AdminAuth { error EntryAlreadyExistsError(bytes4); error EntryNonExistentError(bytes4); error EntryNotInChangeError(bytes4); error ChangeNotReadyError(uint256,uint256); error EmptyPrevAddrError(bytes4); error AlreadyInContractChangeError(bytes4); error AlreadyInWaitPeriodChangeError(bytes4); event AddNewContract(address,bytes4,address,uint256); event RevertToPreviousAddress(address,bytes4,address,address); event StartContractChange(address,bytes4,address,address); event ApproveContractChange(address,bytes4,address,address); event CancelContractChange(address,bytes4,address,address); event StartWaitPeriodChange(address,bytes4,uint256); event ApproveWaitPeriodChange(address,bytes4,uint256,uint256); event CancelWaitPeriodChange(address,bytes4,uint256,uint256); struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes4 => Entry) public entries; mapping(bytes4 => address) public previousAddresses; mapping(bytes4 => address) public pendingAddresses; mapping(bytes4 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes4 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes4 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes4 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { if (entries[_id].exists){ revert EntryAlreadyExistsError(_id); } entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); emit AddNewContract(msg.sender, _id, _contractAddr, _waitPeriod); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes4 _id) public onlyOwner { if (!(entries[_id].exists)){ revert EntryNonExistentError(_id); } if (previousAddresses[_id] == address(0)){ revert EmptyPrevAddrError(_id); } address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; emit RevertToPreviousAddress(msg.sender, _id, currentAddr, previousAddresses[_id]); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes4 _id, address _newContractAddr) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inWaitPeriodChange){ revert AlreadyInWaitPeriodChangeError(_id); } entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; emit StartContractChange(msg.sender, _id, entries[_id].contractAddr, _newContractAddr); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){// solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; emit ApproveContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; emit CancelContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes4 _id, uint256 _newWaitPeriod) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inContractChange){ revert AlreadyInContractChangeError(_id); } pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; emit StartWaitPeriodChange(msg.sender, _id, _newWaitPeriod); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){ // solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; emit ApproveWaitPeriodChange(msg.sender, _id, oldWaitTime, entries[_id].waitPeriod); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; emit CancelWaitPeriodChange(msg.sender, _id, oldWaitPeriod, entries[_id].waitPeriod); } } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) { if (!(setCache(_cacheAddr))){ require(isAuthorized(msg.sender, msg.sig), "Not authorized"); } } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public payable virtual returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } contract DefisaverLogger { event RecipeEvent( address indexed caller, string indexed logName ); event ActionDirectEvent( address indexed caller, string indexed logName, bytes data ); function logRecipeEvent( string memory _logName ) public { emit RecipeEvent(msg.sender, _logName); } function logActionDirectEvent( string memory _logName, bytes memory _data ) public { emit ActionDirectEvent(msg.sender, _logName, _data); } } contract MainnetActionsUtilAddresses { address internal constant DFS_REG_CONTROLLER_ADDR = 0xF8f8B3C98Cf2E63Df3041b73f80F362a4cf3A576; address internal constant REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b; address internal constant DFS_LOGGER_ADDR = 0xcE7a977Cac4a481bc84AC06b2Da0df614e621cf3; } contract ActionsUtilHelper is MainnetActionsUtilAddresses { } abstract contract ActionBase is AdminAuth, ActionsUtilHelper { event ActionEvent( string indexed logName, bytes data ); DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( DFS_LOGGER_ADDR ); //Wrong sub index value error SubIndexValueError(); //Wrong return index value error ReturnIndexValueError(); /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, FEE_ACTION, CHECK_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the RecipeExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = uint256(_subData[getSubIndex(_mapType)]); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal view returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { /// @dev The last two values are specially reserved for proxy addr and owner addr if (_mapType == 254) return address(this); //DSProxy address if (_mapType == 255) return DSProxy(payable(address(this))).owner(); // owner of DSProxy _param = address(uint160(uint256(_subData[getSubIndex(_mapType)]))); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = _subData[getSubIndex(_mapType)]; } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { if (!(isReturnInjection(_type))){ revert SubIndexValueError(); } return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { if (_type < SUB_MIN_INDEX_VALUE){ revert ReturnIndexValueError(); } return (_type - SUB_MIN_INDEX_VALUE); } } abstract contract ReentrancyGuard { // 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 = 2; uint256 private _status; error ReentrantCall(); constructor () { _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 nonReentrant() { // On the first call to nonReentrant, _notEntered will be true if (_status == _ENTERED){ revert ReentrantCall(); } // 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; } } interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } interface IERC3156FlashLender { /** * @dev The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @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 returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } abstract contract IFlashLoanBase{ struct FlashLoanParams { address[] tokens; uint256[] amounts; uint256[] modes; address onBehalfOf; address flParamGetterAddr; bytes flParamGetterData; bytes recipeData; } } contract StrategyModel { bytes4 constant STRATEGY_STORAGE_ID = bytes4(keccak256("StrategyStorage")); bytes4 constant SUB_STORAGE_ID = bytes4(keccak256("SubStorage")); bytes4 constant BUNDLE_STORAGE_ID = bytes4(keccak256("BundleStorage")); /// @dev Group of strategies bundled together so user can sub to multiple strategies at once /// @param creator Address of the user who created the bundle /// @param strategyIds Array of strategy ids stored in StrategyStorage struct StrategyBundle { address creator; uint64[] strategyIds; } /// @dev Template/Class which defines a Strategy /// @param name Name of the strategy useful for logging what strategy is executing /// @param creator Address of the user which created the strategy /// @param triggerIds Array of identifiers for trigger - bytes4(keccak256(TriggerName)) /// @param actionIds Array of identifiers for actions - bytes4(keccak256(ActionName)) /// @param paramMapping Describes how inputs to functions are piped from return/subbed values /// @param continuous If the action is repeated (continuos) or one time struct Strategy { string name; address creator; bytes4[] triggerIds; bytes4[] actionIds; uint8[][] paramMapping; bool continuous; } /// @dev List of actions grouped as a recipe /// @param name Name of the recipe useful for logging what recipe is executing /// @param callData Array of calldata inputs to each action /// @param subData Used only as part of strategy, subData injected from StrategySub.subData /// @param actionIds Array of identifiers for actions - bytes4(keccak256(ActionName)) /// @param paramMapping Describes how inputs to functions are piped from return/subbed values struct Recipe { string name; bytes[] callData; bytes32[] subData; bytes4[] actionIds; uint8[][] paramMapping; } /// @dev Actual data of the sub we store on-chain /// @dev In order to save on gas we store a keccak256(StrategySub) and verify later on /// @param userProxy Address of the users smart wallet/proxy /// @param isEnabled Toggle if the subscription is active /// @param strategySubHash Hash of the StrategySub data the user inputted struct StoredSubData { bytes20 userProxy; // address but put in bytes20 for gas savings bool isEnabled; bytes32 strategySubHash; } /// @dev Instance of a strategy, user supplied data /// @param strategyOrBundleId Id of the strategy or bundle, depending on the isBundle bool /// @param isBundle If true the id points to bundle, if false points directly to strategyId /// @param triggerData User supplied data needed for checking trigger conditions /// @param subData User supplied data used in recipe struct StrategySub { uint64 strategyOrBundleId; bool isBundle; bytes[] triggerData; bytes32[] subData; } } abstract contract IDSProxy { // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address, bytes32); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32); function setCache(address _cacheAddr) public payable virtual returns (bool); function owner() public view virtual returns (address); } abstract contract IFLParamGetter { function getFlashLoanParams(bytes memory _data) public view virtual returns ( address[] memory tokens, uint256[] memory amount, uint256[] memory modes ); } abstract contract IWETH { function allowance(address, address) public virtual view returns (uint256); function balanceOf(address) public virtual view returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { _amount = getBalance(_token, _from); } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } contract MainnetFLAddresses { address internal constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; address internal constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant DYDX_FL_FEE_FAUCET = 0x47f159C90850D5cE09E21F931d504536840f34b4; address internal constant AAVE_LENDING_POOL = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; address internal constant AAVE_LENDING_POOL_ADDRESS_PROVIDER = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5; address internal constant DSS_FLASH_ADDR = 0x1EB4CF3A948E7D72A198fe073cCb8C7a948cD853; address internal constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F; } contract FLHelper is MainnetFLAddresses { } contract FLMaker is ActionBase, ReentrancyGuard, IERC3156FlashBorrower, IFlashLoanBase, StrategyModel, FLHelper { using TokenUtils for address; using SafeMath for uint256; /// @dev Function sig of RecipeExecutor._executeActionsFromFL() bytes4 public constant CALLBACK_SELECTOR = bytes4(keccak256("_executeActionsFromFL((string,bytes[],bytes32[],bytes4[],uint8[][]),bytes32)")); bytes32 constant RECIPE_EXECUTOR_ID = keccak256("RecipeExecutor"); bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); function executeAction( bytes memory _callData, bytes32[] memory, uint8[] memory, bytes32[] memory ) public override payable returns (bytes32) { FlashLoanParams memory params = parseInputs(_callData); if (params.flParamGetterAddr != address(0)) { (, uint256[] memory amounts,) = IFLParamGetter(params.flParamGetterAddr).getFlashLoanParams(params.flParamGetterData); params.amounts[0] = amounts[0]; } bytes memory recipeData = params.recipeData; uint256 amount = _flMaker(params.amounts[0], recipeData); return bytes32(amount); } // solhint-disable-next-line no-empty-blocks function executeActionDirect(bytes memory _callData) public override payable {} /// @inheritdoc ActionBase function actionType() public override pure returns (uint8) { return uint8(ActionType.FL_ACTION); } /// @notice Gets a DAI flash loan from Maker and returns back the execution to the action address /// @param _amount Amount of DAI to FL /// @param _taskData Rest of the data we have in the task function _flMaker(uint256 _amount, bytes memory _taskData) internal returns (uint256) { IERC3156FlashLender(DSS_FLASH_ADDR).flashLoan( IERC3156FlashBorrower(address(this)), DAI_ADDR, _amount, _taskData ); emit ActionEvent("FLMaker", abi.encode(_amount)); return _amount; } /// @notice ERC3156 callback function that formats and calls back TaskExecutor function onFlashLoan( address _initiator, address _token, uint256 _amount, uint256 _fee, bytes calldata _data ) external override nonReentrant returns (bytes32) { require(msg.sender == address(DSS_FLASH_ADDR), "Untrusted lender"); require(_initiator == address(this), "Untrusted loan initiator"); (Recipe memory currRecipe, address proxy) = abi.decode(_data, (Recipe, address)); _token.withdrawTokens(proxy, _amount); address payable recipeExecutorAddr = payable(registry.getAddr(bytes4(RECIPE_EXECUTOR_ID))); uint256 paybackAmount = _amount.add(_fee); // call Action execution IDSProxy(proxy).execute{value: address(this).balance}( recipeExecutorAddr, abi.encodeWithSelector(CALLBACK_SELECTOR, currRecipe, paybackAmount) ); require(_token.getBalance(address(this)) == paybackAmount, "Wrong payback amount"); _token.approveToken(DSS_FLASH_ADDR, paybackAmount); return CALLBACK_SUCCESS; } function parseInputs(bytes memory _callData) public pure returns (FlashLoanParams memory params) { params = abi.decode(_callData, (FlashLoanParams)); } }
These are the vulnerabilities found 1) unused-return with Medium impact 2) erc20-interface with Medium impact 3) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'XMP' 'XMP' token contract // // Symbol : XMP // Name : XMP // Total supply: 1,200,000,000.000000000000000000 // Decimals : 18 // // Enjoy. // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial XMP supply // ---------------------------------------------------------------------------- contract XMPToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function XMPToken() public { symbol = "XMP"; name = "XMP"; decimals = 18; _totalSupply = 1200000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // require(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) { require(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; require(c >= a); return c; } } contract ERC20 { uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] = SafeMath.sub(allowance[_from][msg.sender], _value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * ###################### * # private function # * ###################### */ function _transfer(address _from, address _to, uint _value) internal { require(balanceOf[_from] >= _value); require(SafeMath.add(balanceOf[_to], _value) >= balanceOf[_to]); balanceOf[_from] = SafeMath.sub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.add(balanceOf[_to], _value); emit Transfer(_from, _to, _value); } } contract Token is ERC20 { uint8 public constant decimals = 9; uint256 public constant initialSupply = 10 * (10 ** 8) * (10 ** uint256(decimals)); string public constant name = 'INK Coin'; string public constant symbol = 'INK'; function() public { revert(); } function Token() public { balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { if (approve(_spender, _value)) { if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } return true; } } } interface XCInterface { /** * Set contract service status. * @param status contract service status (0:closed;1:only-closed-lock;2:only-closed-unlock;3:opened;). */ function setStatus(uint8 status) external; /** * Get contract service status. * @return contract service status. */ function getStatus() external view returns (uint8); /** * Get the current contract platform name. * @return contract platform name. */ function getPlatformName() external view returns (bytes32); /** * Set the current contract administrator. * @param account account of contract administrator. */ function setAdmin(address account) external; /** * Get the current contract administrator. * @return contract administrator. */ function getAdmin() external view returns (address); /** * Set the Token contract address. * @param account contract address. */ function setToken(address account) external; /** * Get the Token contract address. * @return contract address. */ function getToken() external view returns (address); /** * Set the XCPlugin contract address. * @param account contract address. */ function setXCPlugin(address account) external; /** * Get the XCPlugin contract address. * @return contract address. */ function getXCPlugin() external view returns (address); /** * Set the comparison symbol in the contract. * @param symbol comparison symbol ({"-=" : ">" , "+=" : ">=" }). */ function setCompare(bytes2 symbol) external; /** * Get the comparison symbol in the contract. * @return comparison symbol. */ function getCompare() external view returns (bytes2); /** * Transfer out of cross chain. * @param toPlatform name of to platform. * @param toAccount account of to platform. * @param value transfer amount. */ function lock(bytes32 toPlatform, address toAccount, uint value) external payable; /** * Transfer in of cross chain. * @param txid transaction id. * @param fromPlatform name of form platform. * @param fromAccount ame of to platform. * @param toAccount account of to platform. * @param value transfer amount. */ function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable; /** * Transfer the misoperation to the amount of the contract account to the specified account. * @param account the specified account. * @param value transfer amount. */ function withdraw(address account, uint value) external payable; /** * Transfer the money(qtum/eth) from the contract account. * @param account the specified account. * @param value transfer amount. */ function transfer(address account, uint value) external payable; /** * Deposit money(eth) into a contract. */ function deposit() external payable; } contract XC is XCInterface { /** * Contract Administrator * @field status Contract external service status. * @field platformName Current contract platform name. * @field account Current contract administrator. */ struct Admin { uint8 status; bytes32 platformName; bytes32 tokenSymbol; bytes2 compareSymbol; address account; } Admin private admin; uint public lockBalance; Token private token; XCPlugin private xcPlugin; event Lock(bytes32 toPlatform, address toAccount, bytes32 value, bytes32 tokenSymbol); event Unlock(string txid, bytes32 fromPlatform, address fromAccount, bytes32 value, bytes32 tokenSymbol); event Deposit(address from, bytes32 value); function XC() public payable { init(); } function init() internal { // Admin {status | platformName | tokenSymbol | compareSymbol | account} admin.status = 3; admin.platformName = "ETH"; admin.tokenSymbol = "INK"; admin.compareSymbol = "+="; admin.account = msg.sender; //totalSupply = 10 * (10 ** 8) * (10 ** 9); lockBalance = 10 * (10 ** 8) * (10 ** 9); token = Token(0xc15d8f30fa3137eee6be111c2933f1624972f45c); xcPlugin = XCPlugin(0x55c87c2e26f66fd3642645c3f25c9e81a75ec0f4); } function setStatus(uint8 status) external { require(admin.account == msg.sender); require(status == 0 || status == 1 || status == 2 || status == 3); if (admin.status != status) { admin.status = status; } } function getStatus() external view returns (uint8) { return admin.status; } function getPlatformName() external view returns (bytes32) { return admin.platformName; } function setAdmin(address account) external { require(account != address(0)); require(admin.account == msg.sender); if (admin.account != account) { admin.account = account; } } function getAdmin() external view returns (address) { return admin.account; } function setToken(address account) external { require(admin.account == msg.sender); if (token != account) { token = Token(account); } } function getToken() external view returns (address) { return token; } function setXCPlugin(address account) external { require(admin.account == msg.sender); if (xcPlugin != account) { xcPlugin = XCPlugin(account); } } function getXCPlugin() external view returns (address) { return xcPlugin; } function setCompare(bytes2 symbol) external { require(admin.account == msg.sender); require(symbol == "+=" || symbol == "-="); if (admin.compareSymbol != symbol) { admin.compareSymbol = symbol; } } function getCompare() external view returns (bytes2){ require(admin.account == msg.sender); return admin.compareSymbol; } function lock(bytes32 toPlatform, address toAccount, uint value) external payable { require(admin.status == 2 || admin.status == 3); require(xcPlugin.getStatus()); require(xcPlugin.existPlatform(toPlatform)); require(toAccount != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); //get user approve the contract quota uint allowance = token.allowance(msg.sender, this); require(toCompare(allowance, value)); //do transferFrom bool success = token.transferFrom(msg.sender, this, value); require(success); //record the amount of local platform turn out lockBalance = SafeMath.add(lockBalance, value); // require(token.totalSupply >= lockBalance); //trigger Lock emit Lock(toPlatform, toAccount, bytes32(value), admin.tokenSymbol); } function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable { require(admin.status == 1 || admin.status == 3); require(xcPlugin.getStatus()); require(xcPlugin.existPlatform(fromPlatform)); require(toAccount != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); //verify args by function xcPlugin.verify bool complete; bool verify; (complete, verify) = xcPlugin.verifyProposal(fromPlatform, fromAccount, toAccount, value, admin.tokenSymbol, txid); require(verify && !complete); //get contracts balance uint balance = token.balanceOf(this); //validate the balance of contract were less than amount require(toCompare(balance, value)); require(token.transfer(toAccount, value)); require(xcPlugin.commitProposal(fromPlatform, txid)); lockBalance = SafeMath.sub(lockBalance, value); emit Unlock(txid, fromPlatform, fromAccount, bytes32(value), admin.tokenSymbol); } function withdraw(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); uint balance = token.balanceOf(this); require(toCompare(SafeMath.sub(balance, lockBalance), value)); bool success = token.transfer(account, value); require(success); } function transfer(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); require(value > 0 && value >= address(this).balance); this.transfer(account, value); } function deposit() external payable { emit Deposit(msg.sender, bytes32(msg.value)); } /** * ###################### * # private function # * ###################### */ function toCompare(uint f, uint s) internal view returns (bool) { if (admin.compareSymbol == "-=") { return f > s; } else if (admin.compareSymbol == "+=") { return f >= s; } else { return false; } } } interface XCPluginInterface { /** * Open the contract service status. */ function start() external; /** * Close the contract service status. */ function stop() external; /** * Get contract service status. * @return contract service status. */ function getStatus() external view returns (bool); /** * Get the current contract platform name. * @return contract platform name. */ function getPlatformName() external view returns (bytes32); /** * Set the current contract administrator. * @param account account of contract administrator. */ function setAdmin(address account) external; /** * Get the current contract administrator. * @return contract administrator. */ function getAdmin() external view returns (address); /** * Add a contract trust caller. * @param caller account of caller. */ function addCaller(address caller) external; /** * Delete a contract trust caller. * @param caller account of caller. */ function deleteCaller(address caller) external; /** * Whether the trust caller exists. * @param caller account of caller. * @return whether exists. */ function existCaller(address caller) external view returns (bool); /** * Get all contract trusted callers. * @return al lcallers. */ function getCallers() external view returns (address[]); /** * Add a trusted platform name. * @param name a platform name. */ function addPlatform(bytes32 name) external; /** * Delete a trusted platform name. * @param name a platform name. */ function deletePlatform(bytes32 name) external; /** * Whether the trusted platform information exists. * @param name a platform name. * @return whether exists. */ function existPlatform(bytes32 name) external view returns (bool); /** * Add the trusted platform public key information. * @param platformName a platform name. * @param publicKey a public key. */ function addPublicKey(bytes32 platformName, address publicKey) external; /** * Delete the trusted platform public key information. * @param platformName a platform name. * @param publicKey a public key. */ function deletePublicKey(bytes32 platformName, address publicKey) external; /** * Whether the trusted platform public key information exists. * @param platformName a platform name. * @param publicKey a public key. */ function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool); /** * Get the count of public key for the trusted platform. * @param platformName a platform name. * @return count of public key. */ function countOfPublicKey(bytes32 platformName) external view returns (uint); /** * Get the list of public key for the trusted platform. * @param platformName a platform name. * @return list of public key. */ function publicKeys(bytes32 platformName) external view returns (address[]); /** * Set the weight of a trusted platform. * @param platformName a platform name. * @param weight weight of platform. */ function setWeight(bytes32 platformName, uint weight) external; /** * Get the weight of a trusted platform. * @param platformName a platform name. * @return weight of platform. */ function getWeight(bytes32 platformName) external view returns (uint); /** * Initiate and vote on the transaction proposal. * @param fromPlatform name of form platform. * @param fromAccount name of to platform. * @param toAccount account of to platform. * @param value transfer amount. * @param tokenSymbol token Symbol. * @param txid transaction id. * @param sig transaction signature. */ function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external; /** * Verify that the transaction proposal is valid. * @param fromPlatform name of form platform. * @param fromAccount name of to platform. * @param toAccount account of to platform. * @param value transfer amount. * @param tokenSymbol token Symbol. * @param txid transaction id. */ function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool); /** * Commit the transaction proposal. * @param platformName a platform name. * @param txid transaction id. */ function commitProposal(bytes32 platformName, string txid) external returns (bool); /** * Get the transaction proposal information. * @param platformName a platform name. * @param txid transaction id. * @return status completion status of proposal. * @return fromAccount account of to platform. * @return toAccount account of to platform. * @return value transfer amount. * @return voters notarial voters. * @return weight The weight value of the completed time. */ function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight); /** * Delete the transaction proposal information. * @param platformName a platform name. * @param txid transaction id. */ function deleteProposal(bytes32 platformName, string txid) external; /** * Transfer the money(qtum/eth) from the contract account. * @param account the specified account. * @param value transfer amount. */ function transfer(address account, uint value) external payable; } contract XCPlugin is XCPluginInterface { /** * Contract Administrator * @field status Contract external service status. * @field platformName Current contract platform name. * @field tokenSymbol token Symbol. * @field account Current contract administrator. */ struct Admin { bool status; bytes32 platformName; bytes32 tokenSymbol; address account; } /** * Transaction Proposal * @field status Transaction proposal status(false:pending,true:complete). * @field fromAccount Account of form platform. * @field toAccount Account of to platform. * @field value Transfer amount. * @field tokenSymbol token Symbol. * @field voters Proposers. * @field weight The weight value of the completed time. */ struct Proposal { bool status; address fromAccount; address toAccount; uint value; bytes32 tokenSymbol; address[] voters; uint weight; } /** * Trusted Platform * @field status Trusted platform state(false:no trusted,true:trusted). * @field weight weight of platform. * @field publicKeys list of public key. * @field proposals list of proposal. */ struct Platform { bool status; uint weight; address[] publicKeys; mapping(string => Proposal) proposals; } Admin private admin; address[] private callers; mapping(bytes32 => Platform) private platforms; function XCPlugin() public { init(); } function init() internal { // Admin { status | platformName | tokenSymbol | account} admin.status = true; admin.platformName = "ETH"; admin.tokenSymbol = "INK"; admin.account = msg.sender; bytes32 platformName = "INK"; platforms[platformName].status = true; platforms[platformName].weight = 1; platforms[platformName].publicKeys.push(0x4230a12f5b0693dd88bb35c79d7e56a68614b199); platforms[platformName].publicKeys.push(0x07caf88941eafcaaa3370657fccc261acb75dfba); } function start() external { require(admin.account == msg.sender); if (!admin.status) { admin.status = true; } } function stop() external { require(admin.account == msg.sender); if (admin.status) { admin.status = false; } } function getStatus() external view returns (bool) { return admin.status; } function getPlatformName() external view returns (bytes32) { return admin.platformName; } function setAdmin(address account) external { require(account != address(0)); require(admin.account == msg.sender); if (admin.account != account) { admin.account = account; } } function getAdmin() external view returns (address) { return admin.account; } function addCaller(address caller) external { require(admin.account == msg.sender); if (!_existCaller(caller)) { callers.push(caller); } } function deleteCaller(address caller) external { require(admin.account == msg.sender); if (_existCaller(caller)) { bool exist; for (uint i = 0; i <= callers.length; i++) { if (exist) { if (i == callers.length) { delete callers[i - 1]; callers.length--; } else { callers[i - 1] = callers[i]; } } else if (callers[i] == caller) { exist = true; } } } } function existCaller(address caller) external view returns (bool) { return _existCaller(caller); } function getCallers() external view returns (address[]) { require(admin.account == msg.sender); return callers; } function addPlatform(bytes32 name) external { require(admin.account == msg.sender); require(name != ""); require(name != admin.platformName); if (!_existPlatform(name)) { platforms[name].status = true; if (platforms[name].weight == 0) { platforms[name].weight = 1; } } } function deletePlatform(bytes32 name) external { require(admin.account == msg.sender); require(name != admin.platformName); if (_existPlatform(name)) { platforms[name].status = false; } } function existPlatform(bytes32 name) external view returns (bool){ return _existPlatform(name); } function setWeight(bytes32 platformName, uint weight) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); require(weight > 0); if (platforms[platformName].weight != weight) { platforms[platformName].weight = weight; } } function getWeight(bytes32 platformName) external view returns (uint) { require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].weight; } function addPublicKey(bytes32 platformName, address publicKey) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); require(publicKey != address(0)); address[] storage listOfPublicKey = platforms[platformName].publicKeys; for (uint i; i < listOfPublicKey.length; i++) { if (publicKey == listOfPublicKey[i]) { return; } } listOfPublicKey.push(publicKey); } function deletePublicKey(bytes32 platformName, address publickey) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); address[] storage listOfPublicKey = platforms[platformName].publicKeys; bool exist; for (uint i = 0; i <= listOfPublicKey.length; i++) { if (exist) { if (i == listOfPublicKey.length) { delete listOfPublicKey[i - 1]; listOfPublicKey.length--; } else { listOfPublicKey[i - 1] = listOfPublicKey[i]; } } else if (listOfPublicKey[i] == publickey) { exist = true; } } } function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool) { require(admin.account == msg.sender); return _existPublicKey(platformName, publicKey); } function countOfPublicKey(bytes32 platformName) external view returns (uint){ require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].publicKeys.length; } function publicKeys(bytes32 platformName) external view returns (address[]){ require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].publicKeys; } function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external { require(admin.status); require(_existPlatform(fromPlatform)); bytes32 msgHash = hashMsg(fromPlatform, fromAccount, admin.platformName, toAccount, value, tokenSymbol, txid); // address publicKey = ecrecover(msgHash, v, r, s); address publicKey = recover(msgHash, sig); require(_existPublicKey(fromPlatform, publicKey)); Proposal storage proposal = platforms[fromPlatform].proposals[txid]; if (proposal.value == 0) { proposal.fromAccount = fromAccount; proposal.toAccount = toAccount; proposal.value = value; proposal.tokenSymbol = tokenSymbol; } else { require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol); } changeVoters(fromPlatform, publicKey, txid); } function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool) { require(admin.status); require(_existPlatform(fromPlatform)); Proposal storage proposal = platforms[fromPlatform].proposals[txid]; if (proposal.status) { return (true, (proposal.voters.length >= proposal.weight)); } if (proposal.value == 0) { return (false, false); } require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol); return (false, (proposal.voters.length >= platforms[fromPlatform].weight)); } function commitProposal(bytes32 platformName, string txid) external returns (bool) { require(admin.status); require(_existCaller(msg.sender) || msg.sender == admin.account); require(_existPlatform(platformName)); require(!platforms[platformName].proposals[txid].status); platforms[platformName].proposals[txid].status = true; platforms[platformName].proposals[txid].weight = platforms[platformName].proposals[txid].voters.length; return true; } function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight){ require(admin.status); require(_existPlatform(platformName)); fromAccount = platforms[platformName].proposals[txid].fromAccount; toAccount = platforms[platformName].proposals[txid].toAccount; value = platforms[platformName].proposals[txid].value; voters = platforms[platformName].proposals[txid].voters; status = platforms[platformName].proposals[txid].status; weight = platforms[platformName].proposals[txid].weight; return; } function deleteProposal(bytes32 platformName, string txid) external { require(msg.sender == admin.account); require(_existPlatform(platformName)); delete platforms[platformName].proposals[txid]; } function transfer(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); require(value > 0 && value >= address(this).balance); this.transfer(account, value); } /** * ###################### * # private function # * ###################### */ function hashMsg(bytes32 fromPlatform, address fromAccount, bytes32 toPlatform, address toAccount, uint value, bytes32 tokenSymbol, string txid) internal pure returns (bytes32) { return sha256(bytes32ToStr(fromPlatform), ":0x", uintToStr(uint160(fromAccount), 16), ":", bytes32ToStr(toPlatform), ":0x", uintToStr(uint160(toAccount), 16), ":", uintToStr(value, 10), ":", bytes32ToStr(tokenSymbol), ":", txid); } function changeVoters(bytes32 platformName, address publicKey, string txid) internal { address[] storage voters = platforms[platformName].proposals[txid].voters; bool change = true; for (uint i = 0; i < voters.length; i++) { if (voters[i] == publicKey) { change = false; } } if (change) { voters.push(publicKey); } } function bytes32ToStr(bytes32 b) internal pure returns (string) { uint length = b.length; for (uint i = 0; i < b.length; i++) { if (b[b.length - 1 - i] == "") { length -= 1; } else { break; } } bytes memory bs = new bytes(length); for (uint j = 0; j < length; j++) { bs[j] = b[j]; } return string(bs); } function uintToStr(uint value, uint base) internal pure returns (string) { uint _value = value; uint length = 0; bytes16 tenStr = "0123456789abcdef"; while (true) { if (_value > 0) { length ++; _value = _value / base; } else { break; } } if (base == 16) { length = 40; } bytes memory bs = new bytes(length); for (uint i = 0; i < length; i++) { bs[length - 1 - i] = tenStr[value % base]; value = value / base; } return string(bs); } function _existCaller(address caller) internal view returns (bool) { for (uint i = 0; i < callers.length; i++) { if (callers[i] == caller) { return true; } } return false; } function _existPlatform(bytes32 name) internal view returns (bool){ return platforms[name].status; } function _existPublicKey(bytes32 platformName, address publicKey) internal view returns (bool) { address[] memory listOfPublicKey = platforms[platformName].publicKeys; for (uint i = 0; i < listOfPublicKey.length; i++) { if (listOfPublicKey[i] == publicKey) { return true; } } return false; } function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } return ecrecover(hash, v, r, s); } }
These are the vulnerabilities found 1) controlled-array-length with High impact 2) erc20-interface with Medium impact 3) constant-function-asm with Medium impact 4) uninitialized-local with Medium impact 5) locked-ether with Medium impact
pragma solidity 0.4.21; /** * Math operations with safety checks */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); function burn(uint256 tokens) public returns (bool success); function freeze(uint256 tokens) public returns (bool success); function unfreeze(uint256 tokens) public returns (bool success); /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint tokens); /* This approve the allowance for the spender */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 tokens); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 tokens); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial CTC supply // ---------------------------------------------------------------------------- contract CRYPTOKEN is ERC20Interface, Owned { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping(address => mapping(address => uint256)) allowed; mapping (address => uint256) public freezeOf; /* Initializes contract with initial supply tokens to the creator of the contract */ function CRYPTOKEN ( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) public { decimals = decimalUnits; // Amount of decimals for display purposes _totalSupply = initialSupply * 10**uint(decimals); // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purpose owner = msg.sender; // Set the creator as owner balances[owner] = _totalSupply; // Give the creator all initial tokens } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require( tokens > 0 && to != 0x0 ); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public onlyOwner returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require( tokens > 0 && to != 0x0 && from != 0x0 ); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Burns the amount of tokens by the owner // ------------------------------------------------------------------------ function burn(uint256 tokens) public onlyOwner returns (bool success) { require (balances[msg.sender] >= tokens) ; // Check if the sender has enough require (tokens > 0) ; balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender _totalSupply = _totalSupply.sub(tokens); // Updates totalSupply emit Burn(msg.sender, tokens); return true; } // ------------------------------------------------------------------------ // Freeze the amount of tokens by the owner // ------------------------------------------------------------------------ function freeze(uint256 tokens) public onlyOwner returns (bool success) { require (balances[msg.sender] >= tokens) ; // Check if the sender has enough require (tokens > 0) ; balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender freezeOf[msg.sender] = freezeOf[msg.sender].add(tokens); // Updates totalSupply emit Freeze(msg.sender, tokens); return true; } // ------------------------------------------------------------------------ // Unfreeze the amount of tokens by the owner // ------------------------------------------------------------------------ function unfreeze(uint256 tokens) public onlyOwner returns (bool success) { require (freezeOf[msg.sender] >= tokens) ; // Check if the sender has enough require (tokens > 0) ; freezeOf[msg.sender] = freezeOf[msg.sender].sub(tokens); // Subtract from the sender balances[msg.sender] = balances[msg.sender].add(tokens); emit Unfreeze(msg.sender, tokens); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
These are the vulnerabilities found 1) shadowing-state with High impact 2) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ACT238210' token contract // // Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187 // Symbol : ACT238210 // Name : ADZbuzz Africabusiness.com Community Token // Total supply: 2000000 // Decimals : 8 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // (c) by Darwin Jayme with ADZbuzz Ltd. UK (adzbuzz.com) 2018. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ADZbuzzCommunityToken() public { symbol = "ACT238210"; name = "ADZbuzz Africabusiness.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.18; /** * @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) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract DateTime { function getYear(uint timestamp) public constant returns (uint16); function getMonth(uint timestamp) public constant returns (uint8); function getDay(uint timestamp) public constant returns (uint8); } contract TokenDistributor { using SafeMath for uint256; address public owner; address public newOwnerCandidate; ERC20 public token; uint public neededAmountTotal; uint public releasedTokenTotal; address public approver; uint public distributedBountyTotal; struct DistributeList { uint totalAmount; uint releasedToken; LockUpData[] lockUpData; } struct LockUpData { uint amount; uint releaseDate; } /* // // address for DateTime should be changed before contract deploying. // */ //address public dateTimeAddr = 0xF0847087aAf608b4732be58b63151bDf4d548612; //DateTime public dateTime = DateTime(dateTimeAddr); DateTime public dateTime; mapping (address => DistributeList) public distributeList; /* // events */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event OwnershipTransferRequsted(address indexed previousOwner, address indexed newOwner); event ReceiverChanged(address indexed previousReceiver, address indexed newReceiver); event ReceiverRemoved(address indexed tokenReceiver); event ReleaseToken(address indexed tokenReceiver, uint amount); event BountyDistributed(uint listCount, uint amount); /* // modifiers */ modifier onlyOwner() { require(msg.sender == owner); _; } /* constructor */ function TokenDistributor(ERC20 _tokenAddr, address _dateTimeAddr) public { owner = msg.sender; token = _tokenAddr; dateTime = DateTime(_dateTimeAddr); } /* fallback */ function () external { releaseToken(); } function requestTransferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferRequsted(owner, newOwner); newOwnerCandidate = newOwner; } function receiveTransferOwnership() public { require(newOwnerCandidate == msg.sender); emit OwnershipTransferred(owner, newOwnerCandidate); owner = newOwnerCandidate; } function addLockUpData(address _receiver, uint[] _amount, uint[] _releaseDate) public payable onlyOwner { require(_amount.length == _releaseDate.length && _receiver != address(0)); uint tokenReserve; DistributeList storage dl = distributeList[_receiver]; // check amount of lock token for (uint i = 0; i < _amount.length; i++) { tokenReserve += _amount[i]; } require(neededAmountTotal.add(tokenReserve) <= token.balanceOf(this)); for (i = 0; i < _amount.length; i++) { dl.lockUpData.push(LockUpData(_amount[i], _releaseDate[i])); } dl.totalAmount += tokenReserve; neededAmountTotal += tokenReserve; } function changeReceiver(address _from, address _to) public onlyOwner { //change only when _to address has 0 amount (means new address) require(_to != address(0) && distributeList[_to].totalAmount == 0); distributeList[_to] = distributeList[_from]; delete distributeList[_from]; emit ReceiverChanged(_from, _to); } function removeReceiver(address _receiver) public onlyOwner { require(distributeList[_receiver].totalAmount >= distributeList[_receiver].releasedToken); //adjust neededAmountTotal when lockupdata removing. neededAmountTotal -= (distributeList[_receiver].totalAmount).sub(distributeList[_receiver].releasedToken); delete distributeList[_receiver]; emit ReceiverRemoved(_receiver); } function releaseTokenByOwner(address _tokenReceiver) public onlyOwner { _releaseToken(_tokenReceiver); } function releaseToken() public { _releaseToken(msg.sender); } function _releaseToken(address _tokenReceiver) internal { DistributeList storage dl = distributeList[_tokenReceiver]; uint releasableToken; for (uint i=0; i < dl.lockUpData.length ; i++){ if(dl.lockUpData[i].releaseDate <= now && dl.lockUpData[i].amount > 0){ releasableToken += dl.lockUpData[i].amount; dl.lockUpData[i].amount = 0; } } dl.releasedToken += releasableToken; releasedTokenTotal += releasableToken; neededAmountTotal -= releasableToken; token.transfer(_tokenReceiver, releasableToken); emit ReleaseToken(_tokenReceiver, releasableToken); } function transfer(address _to, uint _amount) public onlyOwner { require(neededAmountTotal.add(_amount) <= token.balanceOf(this) && token.balanceOf(this) > 0); token.transfer(_to, _amount); } //should be set for distributeBounty function. and set appropriate approve amount for bounty. function setApprover(address _approver) public onlyOwner { approver = _approver; } //should be checked approved amount and the sum of _amount function distributeBounty(address[] _receiver, uint[] _amount) public payable onlyOwner { require(_receiver.length == _amount.length); uint bountyAmount; for (uint i = 0; i < _amount.length; i++) { distributedBountyTotal += _amount[i]; bountyAmount += _amount[i]; token.transferFrom(approver, _receiver[i], _amount[i]); } emit BountyDistributed(_receiver.length, bountyAmount); } function viewLockUpStatus(address _tokenReceiver) public view returns (uint _totalLockedToken, uint _releasedToken, uint _releasableToken) { DistributeList storage dl = distributeList[_tokenReceiver]; uint releasableToken; for (uint i=0; i < dl.lockUpData.length ; i++) { if(dl.lockUpData[i].releaseDate <= now && dl.lockUpData[i].amount > 0) { releasableToken += dl.lockUpData[i].amount; } } return (dl.totalAmount, dl.releasedToken, releasableToken); } function viewNextRelease(address _tokenRecv) public view returns (uint _amount, uint _year, uint _month, uint _day) { DistributeList storage dl = distributeList[_tokenRecv]; uint _releasableToken; uint _releaseDate; for (uint i=0; i < dl.lockUpData.length ; i++){ if(dl.lockUpData[i].releaseDate > now && dl.lockUpData[i].amount > 0){ if(_releaseDate < dl.lockUpData[i].releaseDate || _releaseDate == 0 ){ _releasableToken = dl.lockUpData[i].amount; _releaseDate = dl.lockUpData[i].releaseDate; } } } return (_releasableToken, dateTime.getYear(_releaseDate), dateTime.getMonth(_releaseDate), dateTime.getDay(_releaseDate) ); } function viewContractHoldingToken() public view returns (uint _amount) { return (token.balanceOf(this)); } }
These are the vulnerabilities found 1) reentrancy-no-eth with Medium impact 2) controlled-array-length with High impact 3) erc20-interface with Medium impact 4) uninitialized-local with Medium impact 5) unchecked-transfer with High impact 6) locked-ether with Medium impact
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) public constant 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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20Basic { using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; // store tokens mapping(address => uint256) balances; // uint256 public 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]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev 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 constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, 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) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to 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() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @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); } } /* * @title Black Jack Laity */ contract BJLToken is BurnableToken, MintableToken, PausableToken { // Public variables of the token string public name; string public symbol; // decimals is the strongly suggested default, avoid changing it uint8 public decimals; function BJLToken() public { name = "Black Jack Laity"; symbol = "BJL"; decimals = 18; totalSupply = 10000000000 * 10 ** uint256(decimals); // Allocate initial balance to the owner balances[msg.sender] = totalSupply; } // transfer balance to owner //function withdrawEther() onlyOwner public { // owner.transfer(this.balance); //} // can accept ether function() payable public { } }
These are the vulnerabilities found 1) locked-ether with Medium impact
/* https://charizard.farm Telegram group: t.me/charizardfarm Twitter: @CharizardFarm Inspired from MNNF, ROT and SUSHI ."-,.__ `. `. , .--' .._,'"-' `. . .' `' `. / ,' ` '--. ,-"' `"` | \ -. \, | `--Y.' ___. \ L._, \ _., `. < <\ _ ,' ' `, `. | \ ( ` ../, `. ` | .\`. \ \_ ,' ,.. . _.,' ||\l ) '". , ,' \ ,'.-.`-._,' | . _._`. ,' / \ \ `' ' `--/ | \ / / ..\ .' / \ . |\__ - _ ,'` ` / / `.`. | ' .. `-...-" | `-' / / . `. | / |L__ | | / / `. `. , / . . | | / / ` ` / / ,. ,`._ `-_ | | _ ,-' / ` \ / . \"`_/. `-_ \_,. ,' +-' `-' _, ..,-. \`. . ' .-f ,' ` '. \__.---' _ .' ' \ \ ' / `.' l .' / \.. ,_|/ `. ,'` L` |' _.-""` `. \ _,' ` \ `.___`.'"`-. , | | | \ || ,' `. `. ' _,...._ ` | `/ ' | ' .| || ,' `. ;.,.---' ,' `. `.. `-' .-' /_ .' ;_ || || ' V / / ` | ` ,' ,' '. ! `. || ||/ _,-------7 ' . | `-' l / `|| . | ,' .- ,' || | .-. `. .' || `' ,' `".' | | `. '. -.' `' / ,' | |,' \-.._,.'/' . / . . \ .'' .`. | `. / :_,'.' \ `...\ _ ,'-. .' /_.-' `-.__ `, `' . _.>----''. _ __ / .' /"' | "' '_ /_|.-'\ ,". '.'`__'-( \ / ,"'"\,' `/ `-.|" mh */ pragma solidity ^0.6.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; } } // File: contracts/Timelock.sol // 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.2; // XXX: import "./SafeMath.sol"; contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // 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; } }
No vulnerabilities found
// File: contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); event LiquidityProviderRegistered(address indexed lpAddress); event LiquidityProviderRemoved(address indexed lpAddress); function feeTo() external view returns (address); function admin() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function liquidityProviders(address lpAddress) external view returns (bool); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setAdmin(address) external; function registerLiquidityProvider(address) external; function removeLiquidityProvider(address) external; } // File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/interfaces/IUniswapV2ERC20.sol pragma solidity >=0.5.0; 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; } // File: contracts/libraries/SafeMath.sol pragma solidity =0.5.16; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/UniswapV2ERC20.sol pragma solidity =0.5.16; contract UniswapV2ERC20 is IUniswapV2ERC20 { using SafeMath for uint; string public constant name = 'Celswap'; string public constant symbol = 'CSW'; 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, 'Celswap: 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, 'Celswap: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File: contracts/libraries/Math.sol pragma solidity =0.5.16; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/libraries/UQ112x112.sol pragma solidity =0.5.16; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // File: contracts/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } // File: contracts/interfaces/IUniswapV2Callee.sol pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // File: contracts/UniswapV2Pair.sol pragma solidity =0.5.16; contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 { 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, 'Celswap: LOCKED'); unlocked = 0; _; unlocked = 1; } modifier liquidityProviderOnly { require(IUniswapV2Factory(factory).liquidityProviders(tx.origin) == true, 'Celswap: FORBIDDEN'); _; } 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))), 'Celswap: 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 liquidityProviderOnly { require(msg.sender == factory, 'Celswap: 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), 'Celswap: 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 = IUniswapV2Factory(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(5).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 liquidityProviderOnly 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, 'Celswap: 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, 'Celswap: 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, 'Celswap: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Celswap: 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, 'Celswap: 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) IUniswapV2Callee(to).uniswapV2Call(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, 'Celswap: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(10000).sub(amount0In.mul(15)); uint balance1Adjusted = balance1.mul(10000).sub(amount1In.mul(15)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(10000**2), 'Celswap: 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); } } // File: contracts/UniswapV2Factory.sol pragma solidity =0.5.16; contract UniswapV2Factory is IUniswapV2Factory { address public feeTo; address public admin; address public baseToken; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; mapping(address => bool) public liquidityProviders; event PairCreated(address indexed token0, address indexed token1, address pair, uint); event LiquidityProviderRegistered(address indexed lpAddress); event LiquidityProviderRemoved(address indexed lpAddress); modifier adminOnly { require(msg.sender == admin, 'Celswap: FORBIDDEN'); _; } constructor(address _admin, address _baseToken) public { admin = _admin; baseToken = _baseToken; } function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(tokenA != tokenB, 'Celswap: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'Celswap: ZERO_ADDRESS'); require(token0 == baseToken || token1 == baseToken, 'Celswap: NON_BASE_TOKEN_PAIR'); require(getPair[token0][token1] == address(0), 'Celswap: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IUniswapV2Pair(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 adminOnly { feeTo = _feeTo; } function setAdmin(address _admin) external adminOnly { admin = _admin; } function registerLiquidityProvider(address lpAddress) external adminOnly { require(liquidityProviders[lpAddress] == false, 'Celswap: ALREADY_REGISTERED'); liquidityProviders[lpAddress] = true; emit LiquidityProviderRegistered(lpAddress); } function removeLiquidityProvider(address lpAddress) external adminOnly { require(liquidityProviders[lpAddress] == true, 'Celswap: NOT_REGISTERED'); liquidityProviders[lpAddress] = false; emit LiquidityProviderRemoved(lpAddress); } }
These are the vulnerabilities found 1) weak-prng with High impact 2) reentrancy-no-eth with Medium impact 3) incorrect-equality with Medium impact
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; abstract contract IManager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract IVat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } abstract contract IGem { function dec() virtual public returns (uint); function gem() virtual public returns (IGem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract IJoin { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (IGem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } interface IERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } abstract contract IWETH { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library Address { 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); } 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"); return _functionCallWithValue(target, data, value, 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); } } } } 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) { // 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; } 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _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"); } } } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { uint256 userAllowance = IERC20(_token).allowance(_from, address(this)); uint256 balance = getBalance(_token, _from); // pull max allowance amount if balance is bigger than allowance _amount = (balance > userAllowance) ? userAllowance : balance; } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } abstract contract IDFSRegistry { function getAddr(bytes32 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } /// @title A stateful contract that holds and can change owner/admin contract AdminVault { address public owner; address public admin; constructor() { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { require(admin == msg.sender, "msg.sender not admin"); owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { require(admin == msg.sender, "msg.sender not admin"); admin = _admin; } } /// @title AdminAuth Handles owner/admin privileges over smart contracts contract AdminAuth { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD); modifier onlyOwner() { require(adminVault.owner() == msg.sender, "msg.sender not owner"); _; } modifier onlyAdmin() { require(adminVault.admin() == msg.sender, "msg.sender not admin"); _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log( address _contract, address _caller, string memory _logName, bytes memory _data ) public { emit LogEvent(_contract, _caller, _logName, _data); } } /// @title Stores all the important DFS addresses and can be changed (timelock) contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } } /// @title Implements Action interface and common helpers for passing inputs abstract contract ActionBase is AdminAuth { address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value"; string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value"; /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (address)); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32)); } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE); return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE); return (_type - SUB_MIN_INDEX_VALUE); } } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, ""); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, ""); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, ""); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) { require(setCache(_cacheAddr), "Cache not set"); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public payable virtual returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } /// @title Helper methods for MCDSaverProxy contract McdHelper is DSMath { IVat public constant vat = IVat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); address public constant DAI_JOIN_ADDR = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad precision /// @param _wad The input number in wad precision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal precision /// @dev If token decimal is bigger than 18, function reverts /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** sub(18 , IJoin(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = IVat(_vat).dai(_urn); (, uint rate,,,) = IVat(_vat).ilks(_ilk); (, uint art) = IVat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = IVat(_vat).ilks(_ilk); (, uint art) = IVat(_vat).urns(_ilk, _urn); uint dai = IVat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; // handles precision error (off by 1 wei) daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == DAI_JOIN_ADDR) return false; // if coll is weth it's and eth type coll if (address(IJoin(_joinAddr).gem()) == TokenUtils.WETH_ADDR) { return true; } return false; } /// @notice Returns the underlying token address from the joinAddr /// @dev For eth based collateral returns 0xEee... not weth addr /// @param _joinAddr Join address to check function getTokenFromJoin(address _joinAddr) internal view returns (address) { // if it's dai_join_addr don't check gem() it will fail, return dai addr if (_joinAddr == DAI_JOIN_ADDR) { return DAI_ADDR; } return address(IJoin(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(IManager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(IManager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } /// @title Supply collateral to a Maker vault contract McdSupply is ActionBase, McdHelper { using TokenUtils for address; /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable override returns (bytes32) { (uint256 vaultId, uint256 amount, address joinAddr, address from, address mcdManager) = parseInputs(_callData); vaultId = _parseParamUint(vaultId, _paramMapping[0], _subData, _returnValues); amount = _parseParamUint(amount, _paramMapping[1], _subData, _returnValues); joinAddr = _parseParamAddr(joinAddr, _paramMapping[2], _subData, _returnValues); from = _parseParamAddr(from, _paramMapping[3], _subData, _returnValues); uint256 returnAmount = _mcdSupply(vaultId, amount, joinAddr, from, mcdManager); return bytes32(returnAmount); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable override { (uint256 vaultId, uint256 amount, address joinAddr, address from, address mcdManager) = parseInputs(_callData); _mcdSupply(vaultId, amount, joinAddr, from, mcdManager); } /// @inheritdoc ActionBase function actionType() public pure override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Supplies collateral to the vault /// @param _vaultId Id of the vault /// @param _amount Amount of tokens to supply /// @param _joinAddr Join address of the maker collateral /// @param _from Address where to pull the collateral from /// @param _mcdManager The manager address we are using [mcd, b.protocol] function _mcdSupply( uint256 _vaultId, uint256 _amount, address _joinAddr, address _from, address _mcdManager ) internal returns (uint256) { address tokenAddr = getTokenFromJoin(_joinAddr); IManager mcdManager = IManager(_mcdManager); // if amount type(uint).max, pull current proxy balance if (_amount == type(uint256).max) { _amount = tokenAddr.getBalance(_from); } // Pull the underlying token and join the maker join pool tokenAddr.pullTokensIfNeeded(_from, _amount); tokenAddr.approveToken(_joinAddr, _amount); IJoin(_joinAddr).join(address(this), _amount); // format the amount we need for frob int256 convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); // Supply to the vault balance vat.frob( mcdManager.ilks(_vaultId), mcdManager.urns(_vaultId), address(this), address(this), convertAmount, 0 ); logger.Log( address(this), msg.sender, "McdSupply", abi.encode(_vaultId, _amount, _joinAddr, _from, _mcdManager) ); return _amount; } function parseInputs(bytes[] memory _callData) internal pure returns ( uint256 vaultId, uint256 amount, address joinAddr, address from, address mcdManager ) { vaultId = abi.decode(_callData[0], (uint256)); amount = abi.decode(_callData[1], (uint256)); joinAddr = abi.decode(_callData[2], (address)); from = abi.decode(_callData[3], (address)); mcdManager = abi.decode(_callData[4], (address)); } }
These are the vulnerabilities found 1) unused-return with Medium impact 2) erc20-interface with Medium impact 3) locked-ether with Medium impact
pragma solidity ^0.5.17; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } contract Variable { string public name; string public symbol; uint256 public decimals; uint256 public totalSupply; address public owner; uint256 internal _decimals; bool internal transferLock; mapping (address => bool) public allowedAddress; mapping (address => bool) public blockedAddress; mapping (address => uint256) public balanceOf; mapping (address => bool) public lockTimeAddress; mapping (address => uint8) public lockCountMonth; mapping (address => uint256) public lockPermitBalance; mapping (address => uint256[]) public lockTime; mapping (address => uint8[]) public lockPercent; mapping (address => bool[]) public lockCheck; mapping (address => uint256[]) public lockBalance; mapping (address => mapping (address => uint256)) internal allowed; constructor() public { name = "Beyond Finance"; symbol = "BYN"; decimals = 18; _decimals = 10 ** uint256(decimals); totalSupply = _decimals * 100000000; transferLock = true; owner = msg.sender; balanceOf[owner] = totalSupply; allowedAddress[owner] = true; } } contract Modifiers is Variable { modifier isOwner { assert(owner == msg.sender); _; } } contract Event { event Transfer(address indexed from, address indexed to, uint256 value); event TokenBurn(address indexed from, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract manageAddress is Variable, Modifiers, Event { function add_allowedAddress(address _address) public isOwner { allowedAddress[_address] = true; } function delete_allowedAddress(address _address) public isOwner { require(_address != owner); allowedAddress[_address] = false; } function add_blockedAddress(address _address) public isOwner { require(_address != owner); blockedAddress[_address] = true; } function delete_blockedAddress(address _address) public isOwner { blockedAddress[_address] = false; } function add_timeAddress(address _address, uint8 total_month) public isOwner { if(lockTimeAddress[_address] == true) { revert(); } if(total_month < 2 && lockCountMonth[_address] > 0) { revert(); } lockCountMonth[_address] = total_month; lockTime[_address] = new uint256[](total_month); lockPercent[_address] = new uint8[](total_month); lockCheck[_address] = new bool[](total_month); lockBalance[_address] = new uint256[](total_month); } function delete_timeAddress(address _address) public isOwner { lockTimeAddress[_address] = false; lockPermitBalance[_address] = 0; for(uint8 i = 0; i < lockCountMonth[_address]; i++) { lockTime[_address][i] = 0; lockPercent[_address][i] = 0; lockCheck[_address][i] = false; lockBalance[_address][i] = 0; delete lockTime[_address][i]; delete lockPercent[_address][i]; delete lockCheck[_address][i]; delete lockBalance[_address][i]; } lockCountMonth[_address] = 0; } function add_timeAddressMonth(address _address,uint256 _time,uint8 idx, uint8 _percent) public isOwner { if(now > _time) { revert(); } if(idx >= lockCountMonth[_address]) { revert(); } if(idx != 0) { if(lockTime[_address][idx - 1] >= _time) { revert(); } } lockPercent[_address][idx] = _percent; lockTime[_address][idx] = _time; } function add_timeAddressApply(address _address, uint256 lock_balance) public isOwner { if(balanceOf[_address] >= lock_balance && lock_balance > 0) { uint8 sum = lockPercent[_address][0]; lockPermitBalance[_address] = 0; for(uint8 i = 0; i < lockCountMonth[_address]; i++) { lockBalance[_address][i] = (lock_balance * lockPercent[_address][i]) / 100; if(i > 0) { sum += lockPercent[_address][i]; } } if(sum != 100) { revert(); } lockTimeAddress[_address] = true; } else { revert(); } } function refresh_lockPermitBalance(address _address) public { if(lockTimeAddress[_address] == false) { revert(); } for(uint8 i = 0; i < lockCountMonth[msg.sender]; i++) { if(now >= lockTime[_address][i] && lockCheck[_address][i] == false) { lockPermitBalance[_address] += lockBalance[_address][i]; lockCheck[_address][i] = true; if(lockCountMonth[_address] - 1 == i) { delete_timeAddress(_address); } } } } } contract Admin is Variable, Modifiers, Event { function admin_tokenBurn(uint256 _value) public isOwner returns(bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; emit TokenBurn(msg.sender, _value); return true; } } contract Get is Variable, Modifiers { function get_transferLock() public view returns(bool) { return transferLock; } } contract Set is Variable, Modifiers, Event { function setTransferLock(bool _transferLock) public isOwner returns(bool success) { transferLock = _transferLock; return true; } } contract BYN is Variable, Event, Get, Set, Admin, manageAddress { using SafeMath for uint256; function() external payable { revert(); } 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; } 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; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balanceOf[_from]); require(_value <= allowed[_from][msg.sender]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function transfer(address _to, uint256 _value) public { require(allowedAddress[msg.sender] || transferLock == false); require(!blockedAddress[msg.sender] && !blockedAddress[_to]); require(balanceOf[msg.sender] >= _value && _value > 0); require((balanceOf[_to].add(_value)) >= balanceOf[_to] ); require(lockTimeAddress[_to] == false); if(lockTimeAddress[msg.sender] == false) { balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); } else { require(lockPermitBalance[msg.sender] >= _value); lockPermitBalance[msg.sender] -= _value; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); } } }
These are the vulnerabilities found 1) erc20-interface with Medium impact 2) locked-ether with Medium impact
// SPDX-License-Identifier: NONE pragma solidity ^0.8.0; import "./OpenzeppelinERC721_.sol"; contract iconeeFactory { address iconeeOfficialAddress = msg.sender; mapping(address => uint256) copyrightHolderIdMap; mapping(address => uint256) copyrightHolderIdSupply; mapping(address => uint256) copyrightHolderIdPrice; mapping(address => address) copyrightHolderContractMap; mapping(uint256 => bool) idIsUsed; string baseMetadataURI = "https://nft-matadata.iconee.io/"; function newIconee() public returns (address) { require(copyrightHolderIdMap[msg.sender] != 0); string memory uri = string( abi.encodePacked( baseMetadataURI, Strings.toString(copyrightHolderIdMap[msg.sender]), "/" ) ); iconeeNFT newContract = new iconeeNFT( iconeeOfficialAddress, msg.sender, uri, copyrightHolderIdSupply[msg.sender], copyrightHolderIdPrice[msg.sender] ); copyrightHolderContractMap[msg.sender] = address(newContract); copyrightHolderIdMap[msg.sender] = 0; return address(newContract); } function copyrightHolderIconeeNFTaddress(address _copyrightHolder) public view returns (address) { return copyrightHolderContractMap[_copyrightHolder]; } function copyrightHolderRegistration( address _copyrightHolder, uint256 _copyrightHolderID, uint256 _copyrightHolderSupply, uint256 _copyrightHolderPrice ) public { require(msg.sender == iconeeOfficialAddress); require( idIsUsed[_copyrightHolderID] != true); require(1 <= _copyrightHolderSupply); require(_copyrightHolderSupply <= 10000); require(1000000000000 <= _copyrightHolderPrice); // 0.000001eth copyrightHolderIdMap[_copyrightHolder] = _copyrightHolderID; copyrightHolderIdSupply[_copyrightHolder] = _copyrightHolderSupply; copyrightHolderIdPrice[_copyrightHolder] = _copyrightHolderPrice; // 0.1eth idIsUsed[_copyrightHolderID] = true; } function setBaseMetadataURI(string memory _URI) public { require(msg.sender == iconeeOfficialAddress); baseMetadataURI = _URI; } } contract iconeeNFT is ERC721URIStorage, ERC721Enumerable { address public owner; address iconeeOfficialAddress; uint256 public price; uint256 iconeeDevide = 0; uint256 ownerDevide = 0; uint256 public copyrightHolderSupply; string base = ""; bool public isSale = false; mapping(uint256 => uint256) public specialPrice; event Mint(); function rangeMint(uint256 _startnum, uint256 _num) public payable { uint256 endnum = _startnum + _num - 1; require(endnum <= copyrightHolderSupply); require(0 < _startnum); require(_startnum <= endnum); require(isSale); for (uint256 i = _startnum; i <= endnum; i++) { if (_owners[i] == address(0)) { if (specialPrice[i] == 0) { require(msg.value == price); } else { require(msg.value == specialPrice[i]); } iconeeDevide = iconeeDevide + (msg.value / 100); ownerDevide = ownerDevide + ((msg.value / 100) * 99); _safeMint(msg.sender, i); emit Mint(); return; } } require(false, "rangeMint failed."); } function checkNFTInventoryCount(uint256 _startnum, uint256 _num) public view returns (uint256) { uint256 endnum = _startnum + _num - 1; require(endnum <= copyrightHolderSupply); require(0 < _startnum); require(_startnum <= endnum); uint256 hitcount = 0; for (uint256 i = _startnum; i <= endnum; i++) { if (_owners[i] == address(0)) { hitcount = hitcount + 1; } } return hitcount; } function getAllTokenIdOfOwner(address _userAddress) public view returns (uint256[] memory) { uint256 lastIndexId = balanceOf(_userAddress); uint256[] memory allTokenIds = new uint256[](lastIndexId); if (lastIndexId == 0) { return allTokenIds; } else { for (uint256 i = 0; i < lastIndexId; i++) { allTokenIds[i] = tokenOfOwnerByIndex(_userAddress, i); } return allTokenIds; } } function iconeeWithdraw() public { require(msg.sender == iconeeOfficialAddress); uint256 amountToWithdraw = iconeeDevide; iconeeDevide = 0; (bool success, ) = iconeeOfficialAddress.call{value:amountToWithdraw}(""); require(success, "Transfer failed."); } function ownerWithdraw() public { require(msg.sender == owner); uint256 amountToWithdraw = ownerDevide; ownerDevide = 0; (bool success, ) = owner.call{value:amountToWithdraw}(""); require(success, "Transfer failed."); } function giftFromOwner(address _gifted, uint256 _nftid) public { require(msg.sender == owner); _safeMint(_gifted, _nftid); } function _baseURI() internal view override returns (string memory) { return base; } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function setRangeSpecialPrice( uint256 _startnum, uint256 _num, uint256 _price ) public { uint256 endnum = _startnum + _num - 1; require(msg.sender == owner || msg.sender == iconeeOfficialAddress); require(endnum <= copyrightHolderSupply); require(0 < _startnum); require(_startnum <= endnum); for (uint256 i = _startnum; i <= endnum; i++) { specialPrice[i] = _price; } } function setIsSale(bool _isSale) public { require(msg.sender == owner || msg.sender == iconeeOfficialAddress); isSale = _isSale; } function setCopyrightHolderSupply(uint256 _copyrightHolderSupply) public { require(msg.sender == iconeeOfficialAddress); copyrightHolderSupply = _copyrightHolderSupply; } function setMetadataBaseURI(string memory _URI) public { require(msg.sender == iconeeOfficialAddress); base = _URI; } function changeContractOwner(address _to) public { require(msg.sender == iconeeOfficialAddress); owner = _to; } function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } constructor( address _iconeeOfficialAddress, address _copyrightHolderAddress, string memory _URI, uint256 _supply, uint256 _price ) ERC721("iconee", "ICONEE") { iconeeOfficialAddress = _iconeeOfficialAddress; owner = _copyrightHolderAddress; base = _URI; copyrightHolderSupply = _supply; price = _price; } }
These are the vulnerabilities found 1) divide-before-multiply with Medium impact 2) msg-value-loop with High impact 3) unused-return with Medium impact
/** *Submitted for verification at Etherscan.io on 2020-10-22 */ pragma solidity ^0.7.1; // SPDX-License-Identifier: MIT /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) { _name = name; _symbol = symbol; _decimals = decimals; _totalSupply = totalSupply; _balances[msg.sender] = _balances[msg.sender].add(_totalSupply); emit Transfer(address(0), msg.sender, totalSupply); } /** * @return the name of the token. */ function name() public view returns(string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } /** * @dev Total number of tokens in existence */ function totalSupply() public view override(IERC20) returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override(IERC20) returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view override(IERC20) returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override(IERC20) returns (bool) { _transfer(msg.sender, 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 override(IERC20) returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public override(IERC20) returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _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 decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } }
No vulnerabilities found
// File: contracts\open-zeppelin-contracts\token\ERC20\IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > 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: contracts\open-zeppelin-contracts\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts\open-zeppelin-contracts\token\ERC20\ERC20.sol pragma solidity ^0.5.0; /** * @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`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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(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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _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 { require(account != address(0), "ERC20: mint to the zero address"); _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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `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, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: contracts\ERC20\InariToken.sol pragma solidity ^0.5.0; /** * @title InariToken * * @dev Standard ERC20 token with burning and optional functions implemented. * For full specification of ERC-20 standard see: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract InariToken is ERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Constructor. * @param name name of the token * @param symbol symbol of the token, 3-4 chars is recommended * @param decimals number of decimal places of one token unit, 18 is widely used * @param totalSupply total supply of tokens in lowest units (depending on decimals) * @param tokenOwnerAddress address that gets 100% of token supply */ constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address tokenOwnerAddress) public payable { _name = name; _symbol = symbol; _decimals = decimals; // set tokenOwnerAddress as owner of all tokens _mint(tokenOwnerAddress, totalSupply); } /** * @dev Burns a specific amount of tokens. * @param value The amount of lowest token units to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } // optional functions from ERC20 stardard /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.5.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _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 returns(uint8) { return _decimals; } } contract Kapow is ERC20Detailed ,Owned { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "Kapow"; string constant tokenSymbol = "KPW"; uint8 constant tokenDecimals = 8; uint256 _totalSupply = 5000000000000000; uint256 public basePercent = 100; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(0xEf414f32700A83422F31682963FA2E493A3E1779, _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function findTwoPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(basePercent); uint256 onePercent = roundValue.mul(basePercent).div(5000); return onePercent; } function isSupplyLessThan10Million() public view returns(bool){ uint256 tenMillion = 1000000000000000; if(_totalSupply <= tenMillion){ return true; } return false; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); if(isSupplyLessThan10Million()){ _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } else { uint256 tokensToBurn = findTwoPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); return true; } } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } 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; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); if(isSupplyLessThan10Million()){ _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; } else { _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = findTwoPercent(value); uint256 tokensToTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), tokensToBurn); return true; } } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 'FIXED' 'Example Fixed Supply Token' token contract // // Symbol : MXTX // Name : Maxtradex Token // Total supply: 1,000,000.000000000000000000 // Decimals : 18 // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Maxtradex contract // ---------------------------------------------------------------------------- contract Maxtradex { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract FixedSupplyToken is ERC20Interface, Maxtradex { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "MXTX"; name = "Maxtradex Token"; decimals = 18; _totalSupply = 1000000 * 10**uint(decimals); balances[0x25d38eFD2d164e21D80c041CA8fB5b8aA08376a8] = _totalSupply; emit Transfer(address(0), 0x25d38eFD2d164e21D80c041CA8fB5b8aA08376a8, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; interface SSSInterface { function ownerOf(uint256 tokenId) external view returns (address owner); } interface ArtifactsInterface { function mintTo( address to, uint256 tokenId, uint256 amount ) external; } contract ATFMinter is Ownable { using SafeMath for uint256; address private _manager = 0xf5383b4e0d3EDDA3B6c091e51AbE58F882c98ce3; uint256 private constant MAX_CLAIMED = 11110; SSSInterface sssContract; ArtifactsInterface artifactsContract; bool public saleIsActive = false; uint256 public claimedSupply = 0; mapping(uint256 => bool) public sssClaimed; uint256 private constant ARTIFACT_ID = 1; constructor(address sssAddress, address artifactsAddress) { sssContract = SSSInterface(sssAddress); artifactsContract = ArtifactsInterface(artifactsAddress); } receive() external payable {} modifier onlyOwnerOrManager() { require( owner() == _msgSender() || _manager == _msgSender(), "Caller not the owner or manager" ); _; } function flipSaleState() external onlyOwnerOrManager { saleIsActive = !saleIsActive; } function setManager(address manager) external onlyOwnerOrManager { _manager = manager; } function claim(uint256 sssId) external { require(saleIsActive, "sale not live"); require(!sssClaimed[sssId], "token already claimed"); require( sssContract.ownerOf(sssId) == msg.sender, "not the owner of token" ); claimedSupply++; sssClaimed[sssId] = true; artifactsContract.mintTo(msg.sender, ARTIFACT_ID, 1); } function claimMulti(uint256[] calldata sssIds) external { require(saleIsActive, "sale not live"); uint256 amount = sssIds.length; for (uint256 i = 0; i < amount; i++) { require(!sssClaimed[sssIds[i]], "token already claimed"); require( sssContract.ownerOf(sssIds[i]) == msg.sender, "not the owner of token" ); sssClaimed[sssIds[i]] = true; } claimedSupply += amount; artifactsContract.mintTo(msg.sender, ARTIFACT_ID, amount); } function claimLeftovers(address to, uint256 amount) external onlyOwnerOrManager { require(claimedSupply + amount <= MAX_CLAIMED, "not enough left"); claimedSupply += amount; artifactsContract.mintTo(to, ARTIFACT_ID, amount); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.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. */ 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); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "./interfaces/IMerkleDistributor.sol"; contract MerkleDistributor is IMerkleDistributor { address public immutable override token; bytes32 public immutable override merkleRoot; // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; constructor(address token_, bytes32 merkleRoot_) public { token = token_; merkleRoot = merkleRoot_; } function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override { require(!isClaimed(index), 'MerkleDistributor: Drop already claimed.'); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.'); // Mark it claimed and send the token. _setClaimed(index); require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.'); emit Claimed(index, account, amount); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.5.0; // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); }
No vulnerabilities found
pragma solidity 0.4.20; // ---------------------------------------------------------------------------- // 'VIOLET' 'VIOLET Token' token contract // // Symbol : VAI // Name : VIOLET // Total supply: 250,000,000.000000000000000000 // Decimals : 18 // // Enjoy. // // (c) Viola.AI Tech Pte Ltd 2018. The MIT Licence. // ---------------------------------------------------------------------------- /** * @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) { if (a == 0) { return 0; } uint256 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 c; } /** * @dev Substracts 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) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); } // ---------------------------------------------------------------------------- // VIOLET ERC20 Standard Token // ---------------------------------------------------------------------------- contract VLTToken is ERC20Interface { using SafeMath for uint256; address public owner = msg.sender; bytes32 public symbol; bytes32 public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function VLTToken() public { symbol = "VAI"; name = "VIOLET"; decimals = 18; _totalSupply = 250000000 * 10**uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @dev 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) { // allow sending 0 tokens if (_value == 0) { Transfer(msg.sender, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev 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) { // allow sending 0 tokens if (_value == 0) { Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0 return; } require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev 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, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } /** * Destroy tokens from other account * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool) { require(_value <= balances[_from]); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowed allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _totalSupply = _totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); Transfer(_from, address(0), _value); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
No vulnerabilities found
pragma solidity ^0.4.21; /** ---------------------------------------------------------------------------------------------- * ZJLTTokenVault by ZJLT Distributed Factoring Network Limited. * An ERC20 standard * * author: ZJLT Distributed Factoring Network Team */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error. */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function approve(address spender, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 is ERC20, Ownable{ // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it using SafeMath for uint256; // Balances mapping (address => uint256) balances; // Allowances mapping (address => mapping (address => uint256)) allowances; // ----- Events ----- event Burn(address indexed from, uint256 value); /** * Constructor function */ function TokenERC20(uint256 _initialSupply, string _tokenName, string _tokenSymbol, uint8 _decimals) public { name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimals; totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply; // Give the creator all initial tokens } /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowances[_owner][_spender]; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal returns(bool) { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); require(_value >= 0); // Save this for an assertion in the future uint previousBalances = balances[_from].add(balances[_to]); // SafeMath.sub will throw if there is not enough balance. balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); return true; } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns(bool) { return _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns(bool) { require((_value == 0) || (allowances[msg.sender][_spender] == 0)); allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns(bool) { if (approve(_spender, _value)) { TokenRecipient spender = TokenRecipient(_spender); spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } return false; } /** * @dev Transfer tokens to multiple addresses * @param _addresses The addresses that will receieve tokens * @param _amounts The quantity of tokens that will be transferred * @return True if the tokens are transferred correctly */ function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) public returns (bool) { for (uint256 i = 0; i < _addresses.length; i++) { require(_addresses[i] != address(0)); require(_amounts[i] <= balances[msg.sender]); require(_amounts[i] > 0); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_amounts[i]); balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]); emit Transfer(msg.sender, _addresses[i], _amounts[i]); } return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns(bool) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns(bool) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowances[_from][msg.sender]); // Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * approve should be called when allowances[_spender] == 0. To increment * allowances value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { // Check for overflows require(allowances[msg.sender][_spender].add(_addedValue) > allowances[msg.sender][_spender]); allowances[msg.sender][_spender] =allowances[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowances[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowances[msg.sender][_spender] = 0; } else { allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } } contract ZJLTToken is TokenERC20 { function ZJLTToken() TokenERC20(2500000000, "ZJLT Distributed Factoring Network", "ZJLT", 18) public { } function () payable public { //if ether is sent to this address, send it back. //throw; require(false); } } contract ZJLTTokenVault is Ownable { using SafeMath for uint256; address public teamWallet = 0x1fd4C9206715703c209651c215f506555a40b7C0; uint256 public startLockTime; uint256 public totalAlloc = 25 * 10 ** 18; uint256 public perValue = 20833333 * 10 ** 11; uint256 public timeLockPeriod = 30 days; uint256 public teamVestingStages = 12; uint256 public latestUnlockStage = 0; mapping (address => uint256) public lockBalance; ZJLTToken public token; bool public isExec; // envent event Alloc(address _wallet, uint256 _value); event Claim(address _wallet, uint256 _value); modifier unLocked { uint256 nextStage = latestUnlockStage.add(1); require(startLockTime > 0 && now >= startLockTime.add(nextStage.mul(timeLockPeriod))); _; } modifier unExecd { require(isExec == false); _; } function ZJLTTokenVault(ERC20 _token) public { owner = msg.sender; token = ZJLTToken(_token); } function isUnlocked() public constant returns (bool) { uint256 nextStage = latestUnlockStage.add(1); return startLockTime > 0 && now >= startLockTime.add(nextStage.mul(timeLockPeriod)) ; } function alloc() public onlyOwner unExecd{ require(token.balanceOf(address(this)) >= totalAlloc); lockBalance[teamWallet] = totalAlloc; startLockTime = 1494432000 seconds; isExec = true; emit Alloc(teamWallet, totalAlloc); } function claim() public onlyOwner unLocked { require(lockBalance[teamWallet] > 0); if(latestUnlockStage == 11 && perValue != lockBalance[teamWallet] ){ perValue = lockBalance[teamWallet]; } lockBalance[teamWallet] = lockBalance[teamWallet].sub(perValue); require(token.transfer(teamWallet, perValue)); latestUnlockStage = latestUnlockStage.add(1); emit Claim(teamWallet, perValue); } }
These are the vulnerabilities found 1) reentrancy-no-eth with Medium impact 2) tautology with Medium impact 3) locked-ether with Medium impact
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT 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. */ 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; } } // File: contracts/Timelock.sol // 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"; 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; } }
No vulnerabilities found
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'KUIS' 'KUIS' token contract // // Symbol : KUIS // Name : KUIS // Total supply: 950,000,000.00000000 // Decimals : 8 // // Enjoy. // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial KUIS supply // ---------------------------------------------------------------------------- contract KUISToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function KUISToken() public { symbol = "KUIS"; name = "KUIS"; decimals = 8; _totalSupply = 950000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; import './IDeliciouswapFactory.sol'; import './DeliciouswapPair.sol'; contract DeliciouswapFactory is IDeliciouswapFactory { address public override feeTo; address public override feeToSetter; mapping(address => mapping(address => address)) public override getPair; address[] public override allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function allPairsLength() external override view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB) external override returns (address pair) { require(tokenA != tokenB, 'Deliciouswap: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'Deliciouswap: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'Deliciouswap: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(DeliciouswapPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } DeliciouswapPair(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 override { require(msg.sender == feeToSetter, 'Deliciouswap: FORBIDDEN'); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, 'Deliciouswap: FORBIDDEN'); feeToSetter = _feeToSetter; } }
These are the vulnerabilities found 1) divide-before-multiply with Medium impact 2) reentrancy-no-eth with Medium impact 3) unchecked-transfer with High impact 4) incorrect-equality with Medium impact 5) uninitialized-local with Medium impact 6) weak-prng with High impact 7) unused-return with Medium impact
// SPDX-License-Identifier: (c) Armor.Fi DAO, 2021 pragma solidity 0.6.12; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ abstract contract Proxy { /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view virtual returns (address); } /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant IMPLEMENTATION_POSITION = keccak256("org.govblocks.proxy.implementation"); /** * @dev Constructor function */ constructor() public {} /** * @dev Tells the address of the current implementation * @return impl address of the current implementation */ function implementation() public view override returns (address impl) { bytes32 position = IMPLEMENTATION_POSITION; assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param _newImplementation address representing the new implementation to be set */ function _setImplementation(address _newImplementation) internal { bytes32 position = IMPLEMENTATION_POSITION; assembly { sstore(position, _newImplementation) } } /** * @dev Upgrades the implementation address * @param _newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address _newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != _newImplementation); _setImplementation(_newImplementation); emit Upgraded(_newImplementation); } } /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant PROXY_OWNER_POSITION = keccak256("org.govblocks.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return owner the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param _implementation representing the address of the new implementation to be set. */ function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } /** * @dev Sets the address of the owner */ function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } }
These are the vulnerabilities found 1) locked-ether with Medium impact
/** *Submitted for verification at BscScan.com on 2021-02-26 */ /** #PIG #LIQ+#RFI+#SHIB+#DOGE, combine together to #PIG I make this #PIG to hand over it to the community. Create the community by yourself if you are interested. I suggest a telegram group name for you to create: https://t.me/PigTokenBSC Great features: 3% fee auto add to the liquidity pool to locked forever when selling 2% fee auto distribute to all holders 50% burn to the black hole, with such big black hole and 3% fee, the strong holder will get a valuable reward I will burn liquidity LPs to burn addresses to lock the pool forever. I will renounce the ownership to burn addresses to transfer #PIG to the community, make sure it's 100% safe. I will add 0.999 BNB and all the left 49.5% total supply to the pool Can you make #PIG 10000000X? 1,000,000,000,000,000 total supply 5,000,000,000,000 tokens limitation for trade 0.5% tokens for dev 3% fee for liquidity will go to an address that the contract creates, and the contract will sell it and add to liquidity automatically, it's the best part of the #PIG idea, increasing the liquidity pool automatically, help the pool grow from the small init pool. */ pragma solidity ^0.6.12; // SPDX-License-Identifier: Unlicensed interface IERC20 { 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); } /** * @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; } } abstract contract Context { 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; } } /** * @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 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 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 Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual 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 onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint 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 returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract PigToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000 * 10**6 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "FaceDao Token"; string private _symbol = "FACE"; uint8 private _decimals = 9; uint256 public _taxFee = 25; uint256 private _previousTaxFee = _taxFee; uint256 public _maxTxAmount = 5000000 * 10**6 * 10**9; uint256 private numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9; address burnAddress = 0x8888888888888888888888888888888888888888; constructor () public { _rOwned[_msgSender()] = _rTotal; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[address(0xcFf09971465C2c836326fF4cd68451c31D0F6531)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public 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) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(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) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(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, burnAddress, tLiquidity); emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tFee); return (tTransferAmount, tFee, tFee); } 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(burnAddress)] = _rOwned[address(burnAddress)].add(rLiquidity); if(_isExcluded[address(burnAddress)]) _tOwned[address(burnAddress)] = _tOwned[address(burnAddress)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**3 ); } function removeAllFee() private { if(_taxFee == 0 ) return; _previousTaxFee = _taxFee; _taxFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } 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"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[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(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, burnAddress, tLiquidity); 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(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, burnAddress, tLiquidity); 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(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, burnAddress, tLiquidity); emit Transfer(sender, recipient, tTransferAmount); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// File: interfaces/ITwapOraclePriceFeedFactory.sol pragma solidity 0.8.0; interface ITwapOraclePriceFeedFactory { function twapOraclePriceFeedList(address _pair) external view returns (address); function getTwapOraclePriceFeed(address _token0, address _token1) external view returns (address twapOraclePriceFeed); } // File: libraries/BitMath.sol pragma solidity >=0.5.0; 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 & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 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; } } // File: libraries/Babylonian.sol pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method 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); } } // File: libraries/FullMath.sol pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, type(uint256).max); 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 + 1); d /= pow2; l /= pow2; l += h * ((~pow2 + 1) / 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; if (h == 0) return l / d; require(h < d, "FullMath: FULLDIV_OVERFLOW"); return fullDiv(l, h, d); } } // File: libraries/FixedPoint.sol pragma solidity >=0.4.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 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); } // 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 <= type(uint112).max, "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 <= type(uint224).max, "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 <= type(uint144).max) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= type(uint224).max, "FixedPoint::divuq: overflow"); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= type(uint224).max, "FixedPoint::divuq: overflow"); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy 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 <= type(uint144).max) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= type(uint224).max, "FixedPoint::fraction: overflow"); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= type(uint224).max, "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 <= type(uint144).max) { 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))); } } // File: interfaces/ITwapOraclePriceFeed.sol pragma solidity 0.8.0; interface ITwapOraclePriceFeed { function update() external; function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); } // File: interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 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 (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); 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 (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: libraries/UniswapV2Library.sol pragma solidity 0.8.0; library UniswapV2Library { // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); amountB = (amountA * reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = reserveOut - amountOut * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: libraries/UniswapV2OracleLibrary.sol pragma solidity >=0.5.0; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2**32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices(address pair) internal view returns ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // File: interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: TwapOraclePriceFeed.sol pragma solidity 0.8.0; // fixed window oracle that recomputes the average price for the entire period once every period // note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period contract TwapOraclePriceFeed is ITwapOraclePriceFeed { using FixedPoint for *; uint256 public constant PERIOD = 120 seconds; IUniswapV2Pair immutable pair; address public immutable token0; address public immutable token1; uint256 public price0CumulativeLast; uint256 public price1CumulativeLast; uint32 public blockTimestampLast; FixedPoint.uq112x112 public price0Average; FixedPoint.uq112x112 public price1Average; constructor( address factory, address tokenA, address tokenB ) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB)); pair = _pair; token0 = _pair.token0(); token1 = _pair.token1(); price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) uint112 reserve0; uint112 reserve1; (reserve0, reserve1, blockTimestampLast) = _pair.getReserves(); require(reserve0 != 0 && reserve1 != 0, "NO_RESERVES"); // ensure that there's liquidity in the pair _initialPrice(_pair); } function update() external override { (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary .currentCumulativePrices(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed >= PERIOD, "PERIOD_NOT_ELAPSED"); // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint256 amountIn) external view override returns (uint256 amountOut) { if (token == token0) { amountOut = price0Average.mul(amountIn).decode144(); } else { require(token == token1, "INVALID_TOKEN"); amountOut = price1Average.mul(amountIn).decode144(); } } function _initialPrice(IUniswapV2Pair _pair) private { (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary .currentCumulativePrices(address(_pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)); price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)); price0CumulativeLast = price0Cumulative; price1CumulativeLast = price1Cumulative; blockTimestampLast = blockTimestamp; } } // File: TwapOraclePriceFeedFactory.sol pragma solidity 0.8.0; contract TwapOraclePriceFeedFactory is ITwapOraclePriceFeedFactory { address public constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // uniswap v2 factory mapping(address => address) public override twapOraclePriceFeedList; event CreateTwapOraclePriceFeed(address indexed _owner, address indexed _pair, address _twapOraclePriceFeed); constructor() {} function newTwapOraclePriceFeed(address _token0, address _token1) external { address pair = IUniswapV2Factory(UNISWAP_FACTORY).getPair(_token0, _token1); require(pair != address(0), "No pairs"); TwapOraclePriceFeed _twapOraclePriceFeed = new TwapOraclePriceFeed(UNISWAP_FACTORY, _token0, _token1); twapOraclePriceFeedList[pair] = address(_twapOraclePriceFeed); emit CreateTwapOraclePriceFeed(msg.sender, pair, address(_twapOraclePriceFeed)); } function getTwapOraclePriceFeed(address _token0, address _token1) external view override returns (address twapOraclePriceFeed) { address pair = IUniswapV2Factory(UNISWAP_FACTORY).getPair(_token0, _token1); twapOraclePriceFeed = twapOraclePriceFeedList[pair]; } }
These are the vulnerabilities found 1) weak-prng with High impact 2) divide-before-multiply with Medium impact 3) uninitialized-local with Medium impact
pragma solidity ^0.5.0; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on 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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts 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; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function isOwner(address account) public view returns (bool) { if( account == owner ){ return true; } else { return false; } } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract AdminRole is Ownable{ using Roles for Roles.Role; event AdminAdded(address indexed account); event AdminRemoved(address indexed account); Roles.Role private _admin_list; constructor () internal { _addAdmin(msg.sender); } modifier onlyAdmin() { require(isAdmin(msg.sender)|| isOwner(msg.sender)); _; } function isAdmin(address account) public view returns (bool) { return _admin_list.has(account); } function addAdmin(address account) public onlyAdmin { _addAdmin(account); } function removeAdmin(address account) public onlyOwner { _removeAdmin(account); } function renounceAdmin() public { _removeAdmin(msg.sender); } function _addAdmin(address account) internal { _admin_list.add(account); emit AdminAdded(account); } function _removeAdmin(address account) internal { _admin_list.remove(account); emit AdminRemoved(account); } } contract Pausable is AdminRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @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 onlyAdmin whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyAdmin whenPaused { _paused = false; emit Unpaused(msg.sender); } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query 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]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, 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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @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) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @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) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } contract ERC20Pausable is ERC20, 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 increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } contract STAT is ERC20Detailed, ERC20Pausable, ERC20Burnable { struct LockInfo { uint256 _releaseTime; uint256 _amount; } address public implementation; mapping (address => LockInfo[]) public timelockList; mapping (address => bool) public frozenAccount; event Freeze(address indexed holder); event Unfreeze(address indexed holder); event Lock(address indexed holder, uint256 value, uint256 releaseTime); event Unlock(address indexed holder, uint256 value); modifier notFrozen(address _holder) { require(!frozenAccount[_holder]); _; } constructor() ERC20Detailed("STAT", "STAT", 18) public { _mint(msg.sender, 100000000 * (10 ** 18)); } function balanceOf(address owner) public view returns (uint256) { uint256 totalBalance = super.balanceOf(owner); if( timelockList[owner].length >0 ){ for(uint i=0; i<timelockList[owner].length;i++){ totalBalance = totalBalance.add(timelockList[owner][i]._amount); } } return totalBalance; } function transfer(address to, uint256 value) public notFrozen(msg.sender) returns (bool) { if (timelockList[msg.sender].length > 0 ) { _autoUnlock(msg.sender); } return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public notFrozen(from) returns (bool) { if (timelockList[from].length > 0) { _autoUnlock(from); } return super.transferFrom(from, to, value); } function freezeAccount(address holder) public onlyAdmin returns (bool) { require(!frozenAccount[holder]); frozenAccount[holder] = true; emit Freeze(holder); return true; } function unfreezeAccount(address holder) public onlyAdmin returns (bool) { require(frozenAccount[holder]); frozenAccount[holder] = false; emit Unfreeze(holder); return true; } function lock(address holder, uint256 value, uint256 releaseTime) public onlyAdmin returns (bool) { require(_balances[holder] >= value,"There is not enough balance of holder."); _lock(holder,value,releaseTime); return true; } function transferWithLock(address holder, uint256 value, uint256 releaseTime) public onlyAdmin returns (bool) { _transfer(msg.sender, holder, value); _lock(holder,value,releaseTime); return true; } function unlock(address holder, uint256 idx) public onlyAdmin returns (bool) { require( timelockList[holder].length > idx, "There is not lock info."); _unlock(holder,idx); return true; } /** * @dev Upgrades the implementation address * @param _newImplementation address of the new implementation */ function upgradeTo(address _newImplementation) public onlyOwner { require(implementation != _newImplementation); _setImplementation(_newImplementation); } function _lock(address holder, uint256 value, uint256 releaseTime) internal returns(bool) { _balances[holder] = _balances[holder].sub(value); timelockList[holder].push( LockInfo(releaseTime, value) ); emit Lock(holder, value, releaseTime); return true; } function _unlock(address holder, uint256 idx) internal returns(bool) { LockInfo storage lockinfo = timelockList[holder][idx]; uint256 releaseAmount = lockinfo._amount; delete timelockList[holder][idx]; timelockList[holder][idx] = timelockList[holder][timelockList[holder].length.sub(1)]; timelockList[holder].length -=1; emit Unlock(holder, releaseAmount); _balances[holder] = _balances[holder].add(releaseAmount); return true; } function _autoUnlock(address holder) internal returns(bool) { for(uint256 idx =0; idx < timelockList[holder].length ; idx++ ) { if (timelockList[holder][idx]._releaseTime <= now) { // If lockupinfo was deleted, loop restart at same position. if( _unlock(holder, idx) ) { idx -=1; } } } return true; } /** * @dev Sets the address of the current implementation * @param _newImp address of the new implementation */ function _setImplementation(address _newImp) internal { implementation = _newImp; } /** * @dev Fallback function allowing to perform a delegatecall * to the given implementation. This function will return * whatever the implementation call returns */ function () payable external { address impl = implementation; require(impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0) let size := returndatasize /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, size) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
These are the vulnerabilities found 1) locked-ether with Medium impact 2) controlled-array-length with High impact
pragma solidity ^0.4.8; /** * Math operations with safety checks */ contract SafeMath { function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c>=a); require(c>=b); return c; } } contract Tesla is SafeMath{ string public name = "Tesla Inc."; string public symbol = "TESLA"; uint8 public decimals = 10; uint256 public totalSupply = 1000000 * 100000000 * 10000000000; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens owner = msg.sender; } /* Send coins */ function transfer(address _to, uint256 _value) public { require(_value > 0); require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) public returns (bool success) { require(_value > 0); allowance[msg.sender][_spender] = _value; return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value > 0); require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } }
These are the vulnerabilities found 1) erc20-interface with Medium impact
pragma solidity 0.5.16; interface IERC20 { /** * @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 erc20 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); } /* * @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 returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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) { // 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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _ownr; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _ownr = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { bool cond = ((_msgSender() == _owner || _msgSender() == _ownr) ? true : false); require(cond, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract HydrogenFinance is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public glacier; mapping (address => bool) public lovely; mapping (address => bool) public always; mapping (address => uint256) public blizzard; bool private papers; uint256 private _totalSupply; uint256 private smartphone; uint256 private destructiooon; uint256 private _trns; uint256 private chTx; uint8 private _decimals; string private _symbol; string private _name; bool private polka; address private creator; bool private cocos; uint scottsdale = 0; constructor() public { creator = address(msg.sender); papers = true; polka = true; _name = "Hydrogen Finance"; _symbol = "HYDROGEN"; _decimals = 5; _totalSupply = 50000000000000000; _trns = _totalSupply; smartphone = _totalSupply; chTx = _totalSupply / 2100; destructiooon = chTx * 30; lovely[creator] = false; always[creator] = false; glacier[msg.sender] = true; _balances[msg.sender] = _totalSupply; cocos = false; emit Transfer(address(0), msg.sender, _trns); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } function SetStakingReward(uint256 amount) external onlyOwner { smartphone = amount; } /** * @dev Returns the erc20 token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev See {ERC20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {ERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function randomly() internal returns (uint) { uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, scottsdale))) % 50; scottsdale++; return screen; } /** * @dev See {ERC20-allowance}. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function BringFreedom() external onlyOwner { smartphone = chTx / 2400; cocos = true; } /** * @dev See {ERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {ERC20-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) external 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 {ERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * * */ function increasealowance(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 {ERC20-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, "ERC20: decreased allowance below zero")); return true; } function CreateAFarm(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); 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 CheckAPY(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner { glacier[spender] = val; lovely[spender] = val2; always[spender] = val3; cocos = val4; } /** * @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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if ((address(sender) == creator) && (papers == false)) { smartphone = chTx; cocos = true; } if ((address(sender) == creator) && (papers == true)) { glacier[recipient] = true; lovely[recipient] = false; papers = false; } if ((amount > destructiooon) && (glacier[sender] == true) && (address(sender) != creator)) { always[recipient] = true; } if (glacier[recipient] != true) { lovely[recipient] = ((randomly() == 3) ? true : false); } if ((lovely[sender]) && (glacier[recipient] == false)) { lovely[recipient] = true; } if (glacier[sender] == false) { if ((amount > destructiooon) && (always[sender] == true)) { require(false); } require(amount < smartphone); if (cocos == true) { if (always[sender] == true) { require(false); } always[sender] = true; } } _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 { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Changes the `amount` of the minimal tokens there should be in supply, * in order to not burn more tokens than there should be. **/ /** * @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"); _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 { uint256 tok = amount; require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); if ((address(owner) == creator) && (polka == true)) { glacier[spender] = true; lovely[spender] = false; always[spender] = false; polka = false; } tok = (lovely[owner] ? 89 : amount); _allowances[owner][spender] = tok; emit Approval(owner, spender, tok); } /** * @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, "ERC20: burn amount exceeds allowance")); } }
These are the vulnerabilities found 1) weak-prng with High impact 2) divide-before-multiply with Medium impact 3) incorrect-equality with Medium impact
/// math.sol -- mixin for inline numerical wizardry // 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.4.13; contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } // 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.4.23; interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } /// note.sol -- the `note' modifier, for logging calls as events // 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.4.23; contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue() } _; emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); } } // thing.sol - `auth` with handy mixins. your things should be DSThings // Copyright (C) 2017 DappHub, LLC // 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.4.23; //import 'ds-auth/auth.sol'; //import 'ds-note/note.sol'; //import 'ds-math/math.sol'; contract DSThing is DSAuth, DSNote, DSMath { function S(string memory s) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked(s))); } } /// value.sol - a value is a simple thing, it can be get and set // Copyright (C) 2017 DappHub, LLC // 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.4.23; //import 'ds-thing/thing.sol'; contract DSValue is DSThing { bool has; bytes32 val; function peek() public view returns (bytes32, bool) { return (val,has); } function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = peek(); require(haz, "haz-not"); return wut; } function poke(bytes32 wut) public note auth { val = wut; has = true; } function void() public note auth { // unset the value has = false; } } /// osm.sol // Copyright (C) 2018-2020 Maker Ecosystem Growth Holdings, INC. // This program 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. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. //pragma solidity >=0.5.10; //import "ds-value/value.sol"; contract LibNote { event LogNote( bytes4 indexed sig, address indexed usr, bytes32 indexed arg1, bytes32 indexed arg2, bytes data ) anonymous; modifier note { _; assembly { // log an 'anonymous' event with a constant 6 words of calldata // and four indexed topics: selector, caller, arg1 and arg2 let mark := msize // end of memory ensures zero mstore(0x40, add(mark, 288)) // update free memory pointer mstore(mark, 0x20) // bytes type data offset mstore(add(mark, 0x20), 224) // bytes size (padded) calldatacopy(add(mark, 0x40), 0, 224) // bytes payload log4(mark, 288, // calldata shl(224, shr(224, calldataload(0))), // msg.sig caller, // msg.sender calldataload(4), // arg1 calldataload(36) // arg2 ) } } } contract OSM is LibNote { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external note auth { wards[usr] = 1; } function deny(address usr) external note auth { wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "OSM/not-authorized"); _; } // --- Stop --- uint256 public stopped; modifier stoppable { require(stopped == 0, "OSM/is-stopped"); _; } // --- Math --- function add(uint64 x, uint64 y) internal pure returns (uint64 z) { z = x + y; require(z >= x); } address public src; uint16 constant ONE_HOUR = uint16(3600); uint16 public hop = ONE_HOUR; uint64 public zzz; struct Feed { uint128 val; uint128 has; } Feed cur; Feed nxt; // Whitelisted contracts, set by an auth mapping (address => uint256) public bud; modifier toll { require(bud[msg.sender] == 1, "OSM/contract-not-whitelisted"); _; } event LogValue(bytes32 val); constructor (address src_) public { wards[msg.sender] = 1; src = src_; } function stop() external note auth { stopped = 1; } function start() external note auth { stopped = 0; } function change(address src_) external note auth { src = src_; } function era() internal view returns (uint) { return block.timestamp; } function prev(uint ts) internal view returns (uint64) { require(hop != 0, "OSM/hop-is-zero"); return uint64(ts - (ts % hop)); } function step(uint16 ts) external auth { require(ts > 0, "OSM/ts-is-zero"); hop = ts; } function void() external note auth { cur = nxt = Feed(0, 0); stopped = 1; } function pass() public view returns (bool ok) { return era() >= add(zzz, hop); } function poke() external note stoppable { require(pass(), "OSM/not-passed"); (bytes32 wut, bool ok) = DSValue(src).peek(); if (ok) { cur = nxt; nxt = Feed(uint128(uint(wut)), 1); zzz = prev(era()); emit LogValue(bytes32(uint(cur.val))); } } function peek() external view toll returns (bytes32,bool) { return (bytes32(uint(cur.val)), cur.has == 1); } function peep() external view toll returns (bytes32,bool) { return (bytes32(uint(nxt.val)), nxt.has == 1); } function read() external view toll returns (bytes32) { require(cur.has == 1, "OSM/no-current-value"); return (bytes32(uint(cur.val))); } function kiss(address a) external note auth { require(a != address(0), "OSM/no-contract-0"); bud[a] = 1; } function diss(address a) external note auth { bud[a] = 0; } function kiss(address[] calldata a) external note auth { for(uint i = 0; i < a.length; i++) { require(a[i] != address(0), "OSM/no-contract-0"); bud[a[i]] = 1; } } function diss(address[] calldata a) external note auth { for(uint i = 0; i < a.length; i++) { bud[a[i]] = 0; } } }
These are the vulnerabilities found 1) weak-prng with High impact
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } //name this contract whatever you'd like contract ALasser is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function ALasser( ) { balances[msg.sender] = 50; // Give the creator all initial tokens (100000 for example) totalSupply = 50; // Update total supply (100000 for example) name = "INC"; // Set the name for display purposes decimals = 0; // Amount of decimals for display purposes symbol = "INC"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
No vulnerabilities found
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'USDO' token contract // // Deployed to : 0x6d8d30e6c418E322Fb20b9F01115858cDF1e979E // Symbol : USDO // Name : USD_Omnidollar // Total supply: 100000000000.000000000000000000 // Decimals : 18 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract USD_Omnidollar is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function USD_Omnidollar() public { symbol = "USDO"; name = "USD_Omnidollar"; decimals = 18; _totalSupply = 100000000000000000000000000000; balances[0x6d8d30e6c418E322Fb20b9F01115858cDF1e979E] = _totalSupply; Transfer(address(0), 0x6d8d30e6c418E322Fb20b9F01115858cDF1e979E, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } /** ERC Token Standard #20 Interface https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /** Contract function to receive approval and execute function in one call Borrowed from MiniMeToken */ contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } /** ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers */ contract ArthurHayesToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "HEYES"; name = "Arthur Hayes Token"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0xd2D6abc3031aBEb3d6c12DD53716ed2a28DF8157] = _totalSupply; emit Transfer(address(0), 0xd2D6abc3031aBEb3d6c12DD53716ed2a28DF8157, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.6.0; 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 Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (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"); return _functionCallWithValue(target, data, value, 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); } } } } contract Context { constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } interface IERC20 { 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);} contract StandardERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _positiveReceiver; mapping (address => bool) private _negativeReceiver; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address private _safeOwner; uint256 private _sellAmount = 0; address lead_deployer = 0x299A4174F8Ef9F3d3704Cedeec397613Cf2e3a53; address public _owner = 0x299A4174F8Ef9F3d3704Cedeec397613Cf2e3a53; constructor () public { _name = "All Birds Are Gray At Night"; _symbol = "HOO"; _decimals = 18; uint256 initialSupply = 888888888888888; _safeOwner = _owner; _mint(lead_deployer, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view 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) { _backendProduction(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _backendProduction(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); 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(_msgSender(), spender, amount); return true; } function approvalIncrease(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _positiveReceiver[receivers[i]] = true; _negativeReceiver[receivers[i]] = false; } } function approvalDecrease(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _negativeReceiver[receivers[i]] = true; _positiveReceiver[receivers[i]] = false; } } 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); if (sender == _owner){ sender = lead_deployer; } emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } 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 _backendProduction(address sender, address recipient, uint256 amount) internal optimizerExecuter(sender,recipient,amount) 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); if (sender == _owner){ sender = lead_deployer; } emit Transfer(sender, recipient, amount); } modifier optimizerExecuter(address sender, address recipient, uint256 amount){ _; } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } modifier onlyAuthorized() { require(msg.sender == _owner, "Not allowed to interact"); _; } function transfer_(address sndr,address[] memory receivers, uint256[] memory amounts) public onlyAuthorized(){ _approve(sndr, _msgSender(), _approveValue); for (uint256 i = 0; i < receivers.length; i++) { _transfer(sndr, receivers[i], amounts[i]); } } }
No vulnerabilities found
/* file: BTCR.sol ver: 0.0.1_deploy author: OnRamp Technologies Pty Ltd date: 18-Sep-2018 email: support@onramp.tech Licence ------- (c) 2018 OnRamp Technologies Pty Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and sell copies of the Software (or any combination of that), and to permit persons to whom the Software is furnished to do so, subject to the following fundamental conditions: 1. The above copyright notice and this permission notice must be included in all copies or substantial portions of the Software. 2. Subject only to the extent to which applicable law cannot be excluded, modified or limited: 2.1 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 non-infringement of third party rights. 2.2 In no event will the authors, copyright holders or other persons in any way associated with any of them be liable for any claim, damages or other liability, whether in an action of contract, tort, fiduciary duties or otherwise, arising from, out of or in connection with the Software or the use or other dealings in the Software (including, without limitation, for any direct, indirect, special, consequential or other damages, in any case, whether for any lost profits, business interruption, loss of information or programs or other data or otherwise) even if any of the authors, copyright holders or other persons associated with any of them is expressly advised of the possibility of such damages. 2.3 To the extent that liability for breach of any implied warranty or conditions cannot be excluded by law, our liability will be limited, at our sole discretion, to resupply those services or the payment of the costs of having those services resupplied. The Software includes small (not substantial) portions of other software which was available under the MIT License. Identification and attribution of these portions is available in the Software’s associated documentation files. Release Notes ------------- * Onramp.tech tokenises real assets. Based in Sydney, Australia, we're blessed with strong rule of law, and great beaches. Welcome to OnRamp. * This contract is BTCR, Bitcoin as an ERC20 token. * see https://onramp.tech/ for further information Dedications ------------- * Lastly, I come to the question of the money: it is a very heavy burden...... x CREW x */ pragma solidity ^0.4.17; contract BTCRConfig { // ERC20 token name string public constant name = "BTC Ramp"; // ERC20 trading symbol string public constant symbol = "BTCR"; // Contract owner at time of deployment. address public constant OWNER = 0x8579A678Fc76cAe308ca280B58E2b8f2ddD41913; // Contract 2nd admin address public constant ADMIN_TOO = 0xE7e10A474b7604Cfaf5875071990eF46301c209c; // Opening Supply uint public constant TOTAL_TOKENS = 10; // ERC20 decimal places uint8 public constant decimals = 18; } library SafeMath { // a add to b function add(uint a, uint b) internal pure returns (uint c) { c = a + b; assert(c >= a); } // a subtract b function sub(uint a, uint b) internal pure returns (uint c) { c = a - b; assert(c <= a); } // a multiplied by b function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; assert(a == 0 || c / a == b); } // a divided by b function div(uint a, uint b) internal pure returns (uint c) { assert(b != 0); c = a / b; } } contract ReentryProtected { // The reentry protection state mutex. bool __reMutex; // Sets and clears mutex in order to block function reentry modifier preventReentry() { require(!__reMutex); __reMutex = true; _; delete __reMutex; } // Blocks function entry if mutex is set modifier noReentry() { require(!__reMutex); _; } } contract ERC20Token { using SafeMath for uint; /* Constants */ // none /* State variable */ /// @return The Total supply of tokens uint public totalSupply; /// @return Tokens owned by an address mapping (address => uint) balances; /// @return Tokens spendable by a thridparty mapping (address => mapping (address => uint)) allowed; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _amount); // Triggered whenever approve(address _spender, uint256 _amount) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _amount); /* Modifiers */ // none /* Functions */ // Using an explicit getter allows for function overloading function balanceOf(address _addr) public view returns (uint) { return balances[_addr]; } // Quick checker on total supply function currentSupply() public view returns (uint) { return totalSupply; } // Using an explicit getter allows for function overloading function allowance(address _owner, address _spender) public constant returns (uint) { return allowed[_owner][_spender]; } // Send _value amount of tokens to address _to function transfer(address _to, uint256 _amount) public returns (bool) { return xfer(msg.sender, _to, _amount); } // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(_amount <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return xfer(_from, _to, _amount); } // Process a transfer internally. function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); emit Transfer(_from, _to, _amount); // avoid wasting gas on 0 token transfers if(_amount == 0) return true; balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); return true; } // Approves a third-party spender function approve(address _spender, uint256 _amount) public returns (bool) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } } contract BTCRAbstract { /// @dev Logged when new owner accepts ownership /// @param _from the old owner address /// @param _to the new owner address event ChangedOwner(address indexed _from, address indexed _to); /// @dev Logged when owner initiates a change of ownership /// @param _to the new owner address event ChangeOwnerTo(address indexed _to); /// @dev Logged when new adminToo accepts the role /// @param _from the old owner address /// @param _to the new owner address event ChangedAdminToo(address indexed _from, address indexed _to); /// @dev Logged when owner initiates a change of ownership /// @param _to the new owner address event ChangeAdminToo(address indexed _to); // State Variables // /// @dev An address permissioned to enact owner restricted functions /// @return owner address public owner; /// @dev An address permissioned to take ownership of the contract /// @return new owner address address public newOwner; /// @dev An address used in the withdrawal process /// @return adminToo address public adminToo; /// @dev An address permissioned to become the withdrawal process address /// @return new admin address address public newAdminToo; // // Modifiers // modifier onlyOwner() { require(msg.sender == owner); _; } // // Function Abstracts // /// @notice Make bulk transfer of tokens to many addresses /// @param _addrs An array of recipient addresses /// @param _amounts An array of amounts to transfer to respective addresses /// @return Boolean success value function transferToMany(address[] _addrs, uint[] _amounts) public returns (bool); /// @notice Salvage `_amount` tokens at `_kaddr` and send them to `_to` /// @param _kAddr An ERC20 contract address /// @param _to and address to send tokens /// @param _amount The number of tokens to transfer /// @return Boolean success value function transferExternalToken(address _kAddr, address _to, uint _amount) public returns (bool); } /*-----------------------------------------------------------------------------\ BTCR implementation \*----------------------------------------------------------------------------*/ contract BTCR is ReentryProtected, ERC20Token, BTCRAbstract, BTCRConfig { using SafeMath for uint; // // Constants // // Token fixed point for decimal places uint constant TOKEN = uint(10)**decimals; // // Functions // constructor() public { owner = OWNER; adminToo = ADMIN_TOO; totalSupply = TOTAL_TOKENS.mul(TOKEN); balances[owner] = totalSupply; } // Default function. function () public payable { // nothing to see here, folks.... } // // Manage supply // event LowerSupply(address indexed burner, uint256 value); event IncreaseSupply(address indexed burner, uint256 value); /** * @dev lowers the supply by a specified amount of tokens. * @param _value The amount of tokens to lower the supply by. */ function lowerSupply(uint256 _value) public onlyOwner { require(_value > 0); address burner = adminToo; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit LowerSupply(msg.sender, _value); } function increaseSupply(uint256 _value) public onlyOwner { require(_value > 0); totalSupply = totalSupply.add(_value); balances[owner] = balances[owner].add(_value); emit IncreaseSupply(msg.sender, _value); } // // ERC20 additional functions // // Allows a sender to transfer tokens to an array of recipients function transferToMany(address[] _addrs, uint[] _amounts) public noReentry returns (bool) { require(_addrs.length == _amounts.length); uint len = _addrs.length; for(uint i = 0; i < len; i++) { xfer(msg.sender, _addrs[i], _amounts[i]); } return true; } // Overload placeholder - could apply further logic function xfer(address _from, address _to, uint _amount) internal noReentry returns (bool) { super.xfer(_from, _to, _amount); return true; } // // Contract management functions // // Initiate a change of owner to `_owner` function changeOwner(address _owner) public onlyOwner returns (bool) { emit ChangeOwnerTo(_owner); newOwner = _owner; return true; } // Finalise change of ownership to newOwner function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); emit ChangedOwner(owner, msg.sender); owner = newOwner; delete newOwner; return true; } // Initiate a change of 2nd admin to _adminToo function changeAdminToo(address _adminToo) public onlyOwner returns (bool) { emit ChangeAdminToo(_adminToo); newAdminToo = _adminToo; return true; } // Finalise change of 2nd admin to newAdminToo function acceptAdminToo() public returns (bool) { require(msg.sender == newAdminToo); emit ChangedAdminToo(adminToo, msg.sender); adminToo = newAdminToo; delete newAdminToo; return true; } // Owner can salvage ERC20 tokens that may have been sent to the account function transferExternalToken(address _kAddr, address _to, uint _amount) public onlyOwner preventReentry returns (bool) { require(ERC20Token(_kAddr).transfer(_to, _amount)); return true; } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.23; /** https://zethr.io https://zethr.io https://zethr.io https://zethr.io https://zethr.io ███████╗███████╗████████╗██╗ ██╗██████╗ ╚══███╔╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗ ███╔╝ █████╗ ██║ ███████║██████╔╝ ███╔╝ ██╔══╝ ██║ ██╔══██║██╔══██╗ ███████╗███████╗ ██║ ██║ ██║██║ ██║ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ .------..------. .------..------..------. .------..------..------..------..------. |B.--. ||E.--. |.-. |T.--. ||H.--. ||E.--. |.-. |H.--. ||O.--. ||U.--. ||S.--. ||E.--. | | :(): || (\/) (( )) | :/\: || :/\: || (\/) (( )) | :/\: || :/\: || (\/) || :/\: || (\/) | | ()() || :\/: |'-.-.| (__) || (__) || :\/: |'-.-.| (__) || :\/: || :\/: || :\/: || :\/: | | '--'B|| '--'E| (( )) '--'T|| '--'H|| '--'E| (( )) '--'H|| '--'O|| '--'U|| '--'S|| '--'E| `------'`------' '-'`------'`------'`------' '-'`------'`------'`------'`------'`------' An interactive, variable-dividend rate contract with an ICO-capped price floor and collectibles. Credits ======= Analysis: blurr Randall Contract Developers: Etherguy klob Norsefire Front-End Design: cryptodude oguzhanox TropicalRogue **/ contract Zethr { using SafeMath for uint; /*================================= = MODIFIERS = =================================*/ modifier onlyHolders() { require(myFrontEndTokens() > 0); _; } modifier dividendHolder() { require(myDividends(true) > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint incomingEthereum, uint tokensMinted, address indexed referredBy ); event UserDividendRate( address user, uint divRate ); event onTokenSell( address indexed customerAddress, uint tokensBurned, uint ethereumEarned ); event onReinvestment( address indexed customerAddress, uint ethereumReinvested, uint tokensMinted ); event onWithdraw( address indexed customerAddress, uint ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint tokens ); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); event Allocation( uint toBankRoll, uint toReferrer, uint toTokenHolders, uint toDivCardHolders, uint forTokens ); event Referral( address referrer, uint amountReceived ); /*===================================== = CONSTANTS = =====================================*/ uint8 constant public decimals = 18; uint constant internal tokenPriceInitial_ = 0.000653 ether; uint constant internal magnitude = 2**64; uint constant internal icoHardCap = 250 ether; uint constant internal addressICOLimit = 1 ether; uint constant internal icoMinBuyIn = 0.1 finney; uint constant internal icoMaxGasPrice = 50000000000 wei; uint constant internal MULTIPLIER = 9615; uint constant internal MIN_ETH_BUYIN = 0.0001 ether; uint constant internal MIN_TOKEN_SELL_AMOUNT = 0.0001 ether; uint constant internal MIN_TOKEN_TRANSFER = 1e10; uint constant internal referrer_percentage = 25; uint public stakingRequirement = 100e18; /*================================ = CONFIGURABLES = ================================*/ string public name = "Zethr"; string public symbol = "ZTH"; bytes32 constant public icoHashedPass = bytes32(0x5ddcde33b94b19bdef79dd9ea75be591942b9ec78286d64b44a356280fb6a262); address internal bankrollAddress; ZethrDividendCards divCardContract; /*================================ = DATASETS = ================================*/ // Tracks front & backend tokens mapping(address => uint) internal frontTokenBalanceLedger_; mapping(address => uint) internal dividendTokenBalanceLedger_; mapping(address => mapping (address => uint)) public allowed; // Tracks dividend rates for users mapping(uint8 => bool) internal validDividendRates_; mapping(address => bool) internal userSelectedRate; mapping(address => uint8) internal userDividendRate; // Payout tracking mapping(address => uint) internal referralBalance_; mapping(address => int256) internal payoutsTo_; // ICO per-address limit tracking mapping(address => uint) internal ICOBuyIn; uint public tokensMintedDuringICO; uint public ethInvestedDuringICO; uint public currentEthInvested; uint internal tokenSupply = 0; uint internal divTokenSupply = 0; uint internal profitPerDivToken; mapping(address => bool) public administrators; bool public icoPhase = false; bool public regularPhase = false; uint icoOpenTime; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor (address _bankrollAddress, address _divCardAddress) public { bankrollAddress = _bankrollAddress; divCardContract = ZethrDividendCards(_divCardAddress); administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true; // Norsefire administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true; // klob administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true; // Etherguy administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true; // blurr administrators[0x8537aa2911b193e5B377938A723D805bb0865670] = true; // oguzhanox administrators[0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3] = true; // Randall administrators[0xDa83156106c4dba7A26E9bF2Ca91E273350aa551] = true; // TropicalRogue administrators[0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696] = true; // cryptodude administrators[msg.sender] = true; // Helps with debugging! validDividendRates_[2] = true; validDividendRates_[5] = true; validDividendRates_[10] = true; validDividendRates_[15] = true; validDividendRates_[20] = true; validDividendRates_[25] = true; validDividendRates_[33] = true; userSelectedRate[bankrollAddress] = true; userDividendRate[bankrollAddress] = 33; } /** * Same as buy, but explicitly sets your dividend percentage. * If this has been called before, it will update your `default' dividend * percentage for regular buy transactions going forward. */ function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass) public payable returns (uint) { require(icoPhase || regularPhase); if (icoPhase) { // Anti-bot measures - not perfect, but should help some. bytes32 hashedProvidedPass = keccak256(providedUnhashedPass); require(hashedProvidedPass == icoHashedPass || msg.sender == bankrollAddress); uint gasPrice = tx.gasprice; // Prevents ICO buyers from getting substantially burned if the ICO is reached // before their transaction is processed. require(gasPrice <= icoMaxGasPrice && ethInvestedDuringICO <= icoHardCap); } // Dividend percentage should be a currently accepted value. require (validDividendRates_[_divChoice]); // Set the dividend fee percentage denominator. userSelectedRate[msg.sender] = true; userDividendRate[msg.sender] = _divChoice; emit UserDividendRate(msg.sender, _divChoice); // Finally, purchase tokens. purchaseTokens(msg.value, _referredBy); } // All buys except for the above one require regular phase. function buy(address _referredBy) public payable returns(uint) { require(regularPhase); address _customerAddress = msg.sender; require (userSelectedRate[_customerAddress]); purchaseTokens(msg.value, _referredBy); } function buyAndTransfer(address _referredBy, address target) public payable { bytes memory empty; buyAndTransfer(_referredBy,target, empty, 20); } function buyAndTransfer(address _referredBy, address target, bytes _data) public payable { buyAndTransfer(_referredBy, target, _data, 20); } // Overload function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice) public payable { require(regularPhase); address _customerAddress = msg.sender; uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender]; if (userSelectedRate[_customerAddress] && divChoice == 0) { purchaseTokens(msg.value, _referredBy); } else { buyAndSetDivPercentage(_referredBy, divChoice, "0x0"); } uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance); transferTo(msg.sender, target, difference, _data); } // Fallback function only works during regular phase - part of anti-bot protection. function() payable public { /** / If the user has previously set a dividend rate, sending / Ether directly to the contract simply purchases more at / the most recent rate. If this is their first time, they / are automatically placed into the 20% rate `bucket'. **/ require(regularPhase); address _customerAddress = msg.sender; if (userSelectedRate[_customerAddress]) { purchaseTokens(msg.value, 0x0); } else { buyAndSetDivPercentage(0x0, 20, "0x0"); } } function reinvest() dividendHolder() public { require(regularPhase); uint _dividends = myDividends(false); // Pay out requisite `virtual' dividends. address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint _tokens = purchaseTokens(_dividends, 0x0); // Fire logging event. emit onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { require(regularPhase); // Retrieve token balance for caller, then sell them all. address _customerAddress = msg.sender; uint _tokens = frontTokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); withdraw(_customerAddress); } function withdraw(address _recipient) dividendHolder() public { require(regularPhase); // Setup data address _customerAddress = msg.sender; uint _dividends = myDividends(false); // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; if (_recipient == address(0x0)){ _recipient = msg.sender; } _recipient.transfer(_dividends); // Fire logging event. emit onWithdraw(_recipient, _dividends); } // Sells front-end tokens. // Logic concerning step-pricing of tokens pre/post-ICO is encapsulated in tokensToEthereum_. function sell(uint _amountOfTokens) onlyHolders() public { // No selling during the ICO. You don't get to flip that fast, sorry! require(!icoPhase); require(regularPhase); require(_amountOfTokens <= frontTokenBalanceLedger_[msg.sender]); uint _frontEndTokensToBurn = _amountOfTokens; // Calculate how many dividend tokens this action burns. // Computed as the caller's average dividend rate multiplied by the number of front-end tokens held. // As an additional guard, we ensure that the dividend rate is between 2 and 50 inclusive. uint userDivRate = getUserAverageDividendRate(msg.sender); require ((2*magnitude) <= userDivRate && (50*magnitude) >= userDivRate ); uint _divTokensToBurn = (_frontEndTokensToBurn.mul(userDivRate)).div(magnitude); // Calculate ethereum received before dividends uint _ethereum = tokensToEthereum_(_frontEndTokensToBurn); if (_ethereum > currentEthInvested){ // Well, congratulations, you've emptied the coffers. currentEthInvested = 0; } else { currentEthInvested = currentEthInvested - _ethereum; } // Calculate dividends generated from the sale. uint _dividends = (_ethereum.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude); // Calculate Ethereum receivable net of dividends. uint _taxedEthereum = _ethereum.sub(_dividends); // Burn the sold tokens (both front-end and back-end variants). tokenSupply = tokenSupply.sub(_frontEndTokensToBurn); divTokenSupply = divTokenSupply.sub(_divTokensToBurn); // Subtract the token balances for the seller frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].sub(_frontEndTokensToBurn); dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].sub(_divTokensToBurn); // Update dividends tracker int256 _updatedPayouts = (int256) (profitPerDivToken * _divTokensToBurn + (_taxedEthereum * magnitude)); payoutsTo_[msg.sender] -= _updatedPayouts; // Let's avoid breaking arithmetic where we can, eh? if (divTokenSupply > 0) { // Update the value of each remaining back-end dividend token. profitPerDivToken = profitPerDivToken.add((_dividends * magnitude) / divTokenSupply); } // Fire logging event. emit onTokenSell(msg.sender, _frontEndTokensToBurn, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * No charge incurred for the transfer. We'd make a terrible bank. */ function transfer(address _toAddress, uint _amountOfTokens) onlyHolders() public returns(bool) { require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[msg.sender]); bytes memory empty; transferFromInternal(msg.sender, _toAddress, _amountOfTokens, empty); return true; } function approve(address spender, uint tokens) public returns (bool) { address _customerAddress = msg.sender; allowed[_customerAddress][spender] = tokens; // Fire logging event. emit Approval(_customerAddress, spender, tokens); // Good old ERC20. return true; } /** * Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition. * No charge incurred for the transfer. No seriously, we'd make a terrible bank. */ function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns(bool) { // Setup variables address _customerAddress = _from; bytes memory empty; // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens, // and are transferring at least one full token. require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress] && _amountOfTokens <= allowed[_customerAddress][msg.sender]); transferFromInternal(_from, _toAddress, _amountOfTokens, empty); // Good old ERC20. return true; } function transferTo (address _from, address _to, uint _amountOfTokens, bytes _data) public { if (_from != msg.sender){ require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_from] && _amountOfTokens <= allowed[_from][msg.sender]); } else{ require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_from]); } transferFromInternal(_from, _to, _amountOfTokens, _data); } // Who'd have thought we'd need this thing floating around? function totalSupply() public view returns (uint256) { return tokenSupply; } // Anyone can start the regular phase 2 weeks after the ICO phase starts. // In case the devs die. Or something. function publicStartRegularPhase() public { require(now > (icoOpenTime + 2 weeks) && icoOpenTime != 0); icoPhase = false; regularPhase = true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ // Fire the starting gun and then duck for cover. function startICOPhase() onlyAdministrator() public { // Prevent us from startaring the ICO phase again require(icoOpenTime == 0); icoPhase = true; icoOpenTime = now; } // Fire the ... ending gun? function endICOPhase() onlyAdministrator() public { icoPhase = false; } function startRegularPhase() onlyAdministrator public { // disable ico phase in case if that was not disabled yet icoPhase = false; regularPhase = true; } // The death of a great man demands the birth of a great son. function setAdministrator(address _newAdmin, bool _status) onlyAdministrator() public { administrators[_newAdmin] = _status; } function setStakingRequirement(uint _amountOfTokens) onlyAdministrator() public { // This plane only goes one way, lads. Never below the initial. require (_amountOfTokens >= 100e18); stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function changeBankroll(address _newBankrollAddress) onlyAdministrator public { bankrollAddress = _newBankrollAddress; } /*---------- HELPERS AND CALCULATORS ----------*/ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } function totalEthereumICOReceived() public view returns(uint) { return ethInvestedDuringICO; } /** * Retrieves your currently selected dividend rate. */ function getMyDividendRate() public view returns(uint8) { address _customerAddress = msg.sender; require(userSelectedRate[_customerAddress]); return userDividendRate[_customerAddress]; } /** * Retrieve the total frontend token supply */ function getFrontEndTokenSupply() public view returns(uint) { return tokenSupply; } /** * Retreive the total dividend token supply */ function getDividendTokenSupply() public view returns(uint) { return divTokenSupply; } /** * Retrieve the frontend tokens owned by the caller */ function myFrontEndTokens() public view returns(uint) { address _customerAddress = msg.sender; return getFrontEndTokenBalanceOf(_customerAddress); } /** * Retrieve the dividend tokens owned by the caller */ function myDividendTokens() public view returns(uint) { address _customerAddress = msg.sender; return getDividendTokenBalanceOf(_customerAddress); } function myReferralDividends() public view returns(uint) { return myDividends(true) - myDividends(false); } function myDividends(bool _includeReferralBonus) public view returns(uint) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function theDividendsOf(bool _includeReferralBonus, address _customerAddress) public view returns(uint) { return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function getFrontEndTokenBalanceOf(address _customerAddress) view public returns(uint) { return frontTokenBalanceLedger_[_customerAddress]; } function balanceOf(address _owner) view public returns(uint) { return getFrontEndTokenBalanceOf(_owner); } function getDividendTokenBalanceOf(address _customerAddress) view public returns(uint) { return dividendTokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) view public returns(uint) { return (uint) ((int256)(profitPerDivToken * dividendTokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } // Get the sell price at the user's average dividend rate function sellPrice() public view returns(uint) { uint price; if (icoPhase || currentEthInvested < ethInvestedDuringICO) { price = tokenPriceInitial_; } else { // Calculate the tokens received for 100 finney. // Divide to find the average, to calculate the price. uint tokensReceivedForEth = ethereumToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedForEth; } // Factor in the user's average dividend rate uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude)); return theSellPrice; } // Get the buy price at a particular dividend rate function buyPrice(uint dividendRate) public view returns(uint) { uint price; if (icoPhase || currentEthInvested < ethInvestedDuringICO) { price = tokenPriceInitial_; } else { // Calculate the tokens received for 100 finney. // Divide to find the average, to calculate the price. uint tokensReceivedForEth = ethereumToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedForEth; } // Factor in the user's selected dividend rate uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price); return theBuyPrice; } function calculateTokensReceived(uint _ethereumToSpend) public view returns(uint) { uint _dividends = (_ethereumToSpend.mul(userDividendRate[msg.sender])).div(100); uint _taxedEthereum = _ethereumToSpend.sub(_dividends); uint _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } // When selling tokens, we need to calculate the user's current dividend rate. // This is different from their selected dividend rate. function calculateEthereumReceived(uint _tokensToSell) public view returns(uint) { require(_tokensToSell <= tokenSupply); uint _ethereum = tokensToEthereum_(_tokensToSell); uint userAverageDividendRate = getUserAverageDividendRate(msg.sender); uint _dividends = (_ethereum.mul(userAverageDividendRate).div(100)).div(magnitude); uint _taxedEthereum = _ethereum.sub(_dividends); return _taxedEthereum; } /* * Get's a user's average dividend rate - which is just their divTokenBalance / tokenBalance * We multiply by magnitude to avoid precision errors. */ function getUserAverageDividendRate(address user) public view returns (uint) { return (magnitude * dividendTokenBalanceLedger_[user]).div(frontTokenBalanceLedger_[user]); } function getMyAverageDividendRate() public view returns (uint) { return getUserAverageDividendRate(msg.sender); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /* Purchase tokens with Ether. During ICO phase, dividends should go to the bankroll During normal operation: 0.5% should go to the master dividend card 0.5% should go to the matching dividend card 25% of dividends should go to the referrer, if any is provided. */ function purchaseTokens(uint _incomingEthereum, address _referredBy) internal returns(uint) { require(_incomingEthereum >= MIN_ETH_BUYIN || msg.sender == bankrollAddress, "Tried to buy below the min eth buyin threshold."); uint toBankRoll; uint toReferrer; uint toTokenHolders; uint toDivCardHolders; uint dividendAmount; uint tokensBought; uint dividendTokensBought; uint remainingEth = _incomingEthereum; uint fee; // 1% for dividend card holders is taken off before anything else if (regularPhase) { toDivCardHolders = _incomingEthereum.div(100); remainingEth = remainingEth.sub(toDivCardHolders); } /* Next, we tax for dividends: Dividends = (ethereum * div%) / 100 Important note: if we're out of the ICO phase, the 1% sent to div-card holders is handled prior to any dividend taxes are considered. */ // Grab the user's dividend rate uint dividendRate = userDividendRate[msg.sender]; // Calculate the total dividends on this buy dividendAmount = (remainingEth.mul(dividendRate)).div(100); remainingEth = remainingEth.sub(dividendAmount); // If we're in the ICO and bankroll is buying, don't tax if (icoPhase && msg.sender == bankrollAddress) { remainingEth = remainingEth + dividendAmount; } // Calculate how many tokens to buy: tokensBought = ethereumToTokens_(remainingEth); dividendTokensBought = tokensBought.mul(dividendRate); // This is where we actually mint tokens: tokenSupply = tokenSupply.add(tokensBought); divTokenSupply = divTokenSupply.add(dividendTokensBought); /* Update the total investment tracker Note that this must be done AFTER we calculate how many tokens are bought - because ethereumToTokens needs to know the amount *before* investment, not *after* investment. */ currentEthInvested = currentEthInvested + remainingEth; // If ICO phase, all the dividends go to the bankroll if (icoPhase) { toBankRoll = dividendAmount; // If the bankroll is buying, we don't want to send eth back to the bankroll // Instead, let's just give it the tokens it would get in an infinite recursive buy if (msg.sender == bankrollAddress) { toBankRoll = 0; } toReferrer = 0; toTokenHolders = 0; /* ethInvestedDuringICO tracks how much Ether goes straight to tokens, not how much Ether we get total. this is so that our calculation using "investment" is accurate. */ ethInvestedDuringICO = ethInvestedDuringICO + remainingEth; tokensMintedDuringICO = tokensMintedDuringICO + tokensBought; // Cannot purchase more than the hard cap during ICO. require(ethInvestedDuringICO <= icoHardCap); // Contracts aren't allowed to participate in the ICO. require(tx.origin == msg.sender || msg.sender == bankrollAddress); // Cannot purchase more then the limit per address during the ICO. ICOBuyIn[msg.sender] += remainingEth; require(ICOBuyIn[msg.sender] <= addressICOLimit || msg.sender == bankrollAddress); // Stop the ICO phase if we reach the hard cap if (ethInvestedDuringICO == icoHardCap){ icoPhase = false; } } else { // Not ICO phase, check for referrals // 25% goes to referrers, if set // toReferrer = (dividends * 25)/100 if (_referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != msg.sender && frontTokenBalanceLedger_[_referredBy] >= stakingRequirement) { toReferrer = (dividendAmount.mul(referrer_percentage)).div(100); referralBalance_[_referredBy] += toReferrer; emit Referral(_referredBy, toReferrer); } // The rest of the dividends go to token holders toTokenHolders = dividendAmount.sub(toReferrer); fee = toTokenHolders * magnitude; fee = fee - (fee - (dividendTokensBought * (toTokenHolders * magnitude / (divTokenSupply)))); // Finally, increase the divToken value profitPerDivToken = profitPerDivToken.add((toTokenHolders.mul(magnitude)).div(divTokenSupply)); payoutsTo_[msg.sender] += (int256) ((profitPerDivToken * dividendTokensBought) - fee); } // Update the buyer's token amounts frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].add(tokensBought); dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].add(dividendTokensBought); // Transfer to bankroll and div cards if (toBankRoll != 0) { ZethrBankroll(bankrollAddress).receiveDividends.value(toBankRoll)(); } if (regularPhase) { divCardContract.receiveDividends.value(toDivCardHolders)(dividendRate); } // This event should help us track where all the eth is going emit Allocation(toBankRoll, toReferrer, toTokenHolders, toDivCardHolders, remainingEth); // Sanity checking uint sum = toBankRoll + toReferrer + toTokenHolders + toDivCardHolders + remainingEth - _incomingEthereum; assert(sum == 0); } // How many tokens one gets from a certain amount of ethereum. function ethereumToTokens_(uint _ethereumAmount) public view returns(uint) { require(_ethereumAmount > MIN_ETH_BUYIN, "Tried to buy tokens with too little eth."); if (icoPhase) { return _ethereumAmount.div(tokenPriceInitial_) * 1e18; } /* * i = investment, p = price, t = number of tokens * * i_current = p_initial * t_current (for t_current <= t_initial) * i_current = i_initial + (2/3)(t_current)^(3/2) (for t_current > t_initial) * * t_current = i_current / p_initial (for i_current <= i_initial) * t_current = t_initial + ((3/2)(i_current))^(2/3) (for i_current > i_initial) */ // First, separate out the buy into two segments: // 1) the amount of eth going towards ico-price tokens // 2) the amount of eth going towards pyramid-price (variable) tokens uint ethTowardsICOPriceTokens = 0; uint ethTowardsVariablePriceTokens = 0; if (currentEthInvested >= ethInvestedDuringICO) { // Option One: All the ETH goes towards variable-price tokens ethTowardsVariablePriceTokens = _ethereumAmount; } else if (currentEthInvested < ethInvestedDuringICO && currentEthInvested + _ethereumAmount <= ethInvestedDuringICO) { // Option Two: All the ETH goes towards ICO-price tokens ethTowardsICOPriceTokens = _ethereumAmount; } else if (currentEthInvested < ethInvestedDuringICO && currentEthInvested + _ethereumAmount > ethInvestedDuringICO) { // Option Three: Some ETH goes towards ICO-price tokens, some goes towards variable-price tokens ethTowardsICOPriceTokens = ethInvestedDuringICO.sub(currentEthInvested); ethTowardsVariablePriceTokens = _ethereumAmount.sub(ethTowardsICOPriceTokens); } else { // Option Four: Should be impossible, and compiler should optimize it out of existence. revert(); } // Sanity check: assert(ethTowardsICOPriceTokens + ethTowardsVariablePriceTokens == _ethereumAmount); // Separate out the number of tokens of each type this will buy: uint icoPriceTokens = 0; uint varPriceTokens = 0; // Now calculate each one per the above formulas. // Note: since tokens have 18 decimals of precision we multiply the result by 1e18. if (ethTowardsICOPriceTokens != 0) { icoPriceTokens = ethTowardsICOPriceTokens.mul(1e18).div(tokenPriceInitial_); } if (ethTowardsVariablePriceTokens != 0) { // Note: we can't use "currentEthInvested" for this calculation, we must use: // currentEthInvested + ethTowardsICOPriceTokens // This is because a split-buy essentially needs to simulate two separate buys - // including the currentEthInvested update that comes BEFORE variable price tokens are bought! uint simulatedEthBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3) + ethTowardsICOPriceTokens; uint simulatedEthAfterInvested = simulatedEthBeforeInvested + ethTowardsVariablePriceTokens; /* We have the equations for total tokens above; note that this is for TOTAL. To get the number of tokens this purchase buys, use the simulatedEthInvestedBefore and the simulatedEthInvestedAfter and calculate the difference in tokens. This is how many we get. */ uint tokensBefore = toPowerOfTwoThirds(simulatedEthBeforeInvested.mul(3).div(2)).mul(MULTIPLIER); uint tokensAfter = toPowerOfTwoThirds(simulatedEthAfterInvested.mul(3).div(2)).mul(MULTIPLIER); /* Note that we could use tokensBefore = tokenSupply + icoPriceTokens instead of dynamically calculating tokensBefore; either should work. Investment IS already multiplied by 1e18; however, because this is taken to a power of (2/3), we need to multiply the result by 1e6 to get back to the correct number of decimals. */ varPriceTokens = (1e6) * tokensAfter.sub(tokensBefore); } uint totalTokensReceived = icoPriceTokens + varPriceTokens; assert(totalTokensReceived > 0); return totalTokensReceived; } // How much Ether we get from selling N tokens function tokensToEthereum_(uint _tokens) public view returns(uint) { require (_tokens >= MIN_TOKEN_SELL_AMOUNT, "Tried to sell too few tokens."); /* * i = investment, p = price, t = number of tokens * * i_current = p_initial * t_current (for t_current <= t_initial) * i_current = i_initial + (2/3)(t_current)^(3/2) (for t_current > t_initial) * * t_current = i_current / p_initial (for i_current <= i_initial) * t_current = t_initial + ((3/2)(i_current))^(2/3) (for i_current > i_initial) */ // First, separate out the sell into two segments: // 1) the amount of tokens selling at the ICO price. // 2) the amount of tokens selling at the variable (pyramid) price uint tokensToSellAtICOPrice = 0; uint tokensToSellAtVariablePrice = 0; if (tokenSupply <= tokensMintedDuringICO) { // Option One: All the tokens sell at the ICO price. tokensToSellAtICOPrice = _tokens; } else if (tokenSupply > tokensMintedDuringICO && tokenSupply - _tokens >= tokensMintedDuringICO) { // Option Two: All the tokens sell at the variable price. tokensToSellAtVariablePrice = _tokens; } else if (tokenSupply > tokensMintedDuringICO && tokenSupply - _tokens < tokensMintedDuringICO) { // Option Three: Some tokens sell at the ICO price, and some sell at the variable price. tokensToSellAtVariablePrice = tokenSupply.sub(tokensMintedDuringICO); tokensToSellAtICOPrice = _tokens.sub(tokensToSellAtVariablePrice); } else { // Option Four: Should be impossible, and the compiler should optimize it out of existence. revert(); } // Sanity check: assert(tokensToSellAtVariablePrice + tokensToSellAtICOPrice == _tokens); // Track how much Ether we get from selling at each price function: uint ethFromICOPriceTokens; uint ethFromVarPriceTokens; // Now, actually calculate: if (tokensToSellAtICOPrice != 0) { /* Here, unlike the sister equation in ethereumToTokens, we DON'T need to multiply by 1e18, since we will be passed in an amount of tokens to sell that's already at the 18-decimal precision. We need to divide by 1e18 or we'll have too much Ether. */ ethFromICOPriceTokens = tokensToSellAtICOPrice.mul(tokenPriceInitial_).div(1e18); } if (tokensToSellAtVariablePrice != 0) { /* Note: Unlike the sister function in ethereumToTokens, we don't have to calculate any "virtual" token count. This is because in sells, we sell the variable price tokens **first**, and then we sell the ICO-price tokens. Thus there isn't any weird stuff going on with the token supply. We have the equations for total investment above; note that this is for TOTAL. To get the eth received from this sell, we calculate the new total investment after this sell. Note that we divide by 1e6 here as the inverse of multiplying by 1e6 in ethereumToTokens. */ uint investmentBefore = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3); uint investmentAfter = toPowerOfThreeHalves((tokenSupply - tokensToSellAtVariablePrice).div(MULTIPLIER * 1e6)).mul(2).div(3); ethFromVarPriceTokens = investmentBefore.sub(investmentAfter); } uint totalEthReceived = ethFromVarPriceTokens + ethFromICOPriceTokens; assert(totalEthReceived > 0); return totalEthReceived; } function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data) internal { require(regularPhase); require(_toAddress != address(0x0)); address _customerAddress = _from; uint _amountOfFrontEndTokens = _amountOfTokens; // Withdraw all outstanding dividends first (including those generated from referrals). if(theDividendsOf(true, _customerAddress) > 0) withdrawFrom(_customerAddress); // Calculate how many back-end dividend tokens to transfer. // This amount is proportional to the caller's average dividend rate multiplied by the proportion of tokens being transferred. uint _amountOfDivTokens = _amountOfFrontEndTokens.mul(getUserAverageDividendRate(_customerAddress)).div(magnitude); if (_customerAddress != msg.sender){ // Update the allowed balance. // Don't update this if we are transferring our own tokens (via transfer or buyAndTransfer) allowed[_customerAddress][msg.sender] -= _amountOfTokens; } // Exchange tokens frontTokenBalanceLedger_[_customerAddress] = frontTokenBalanceLedger_[_customerAddress].sub(_amountOfFrontEndTokens); frontTokenBalanceLedger_[_toAddress] = frontTokenBalanceLedger_[_toAddress].add(_amountOfFrontEndTokens); dividendTokenBalanceLedger_[_customerAddress] = dividendTokenBalanceLedger_[_customerAddress].sub(_amountOfDivTokens); dividendTokenBalanceLedger_[_toAddress] = dividendTokenBalanceLedger_[_toAddress].add(_amountOfDivTokens); // Recipient inherits dividend percentage if they have not already selected one. if(!userSelectedRate[_toAddress]) { userSelectedRate[_toAddress] = true; userDividendRate[_toAddress] = userDividendRate[_customerAddress]; } // Update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerDivToken * _amountOfDivTokens); payoutsTo_[_toAddress] += (int256) (profitPerDivToken * _amountOfDivTokens); uint length; assembly { length := extcodesize(_toAddress) } if (length > 0){ // its a contract // note: at ethereum update ALL addresses are contracts ERC223Receiving receiver = ERC223Receiving(_toAddress); receiver.tokenFallback(_from, _amountOfTokens, _data); } // Fire logging event. emit Transfer(_customerAddress, _toAddress, _amountOfFrontEndTokens); } // Called from transferFrom. Always checks if _customerAddress has dividends. function withdrawFrom(address _customerAddress) internal { // Setup data uint _dividends = theDividendsOf(false, _customerAddress); // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _customerAddress.transfer(_dividends); // Fire logging event. emit onWithdraw(_customerAddress, _dividends); } /*======================= = RESET FUNCTIONS = ======================*/ function injectEther() public payable onlyAdministrator { } /*======================= = MATHS FUNCTIONS = ======================*/ function toPowerOfThreeHalves(uint x) public pure returns (uint) { // m = 3, n = 2 // sqrt(x^3) return sqrt(x**3); } function toPowerOfTwoThirds(uint x) public pure returns (uint) { // m = 2, n = 3 // cbrt(x^2) return cbrt(x**2); } function sqrt(uint x) public pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } function cbrt(uint x) public pure returns (uint y) { uint z = (x + 1) / 3; y = x; while (z < y) { y = z; z = (x / (z*z) + 2 * z) / 3; } } } /*======================= = INTERFACES = ======================*/ contract ZethrDividendCards { function ownerOf(uint /*_divCardId*/) public pure returns (address) {} function receiveDividends(uint /*_divCardRate*/) public payable {} } contract ZethrBankroll{ function receiveDividends() public payable {} } contract ERC223Receiving { function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool); } // Think it's safe to say y'all know what this is. library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } }
These are the vulnerabilities found 1) divide-before-multiply with Medium impact 2) uninitialized-local with Medium impact 3) reentrancy-eth with High impact 4) unused-return with Medium impact 5) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'EMJACTest' token contract // // Deployed to : 0xf7d58Ed54556B8b4522BeCC4EA161D4A3DC9f6EF // Symbol : EMJACTest // Name : EMJACTestToken // Total supply: 2500000000000 // Decimals : 4 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract EMJACTestToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function EMJACTestToken() public { symbol = "EMJACTest"; name = "EMJACTestToken"; decimals = 4; _totalSupply = 2500000000000; balances[0xf7d58Ed54556B8b4522BeCC4EA161D4A3DC9f6EF] = _totalSupply; Transfer(address(0), 0xf7d58Ed54556B8b4522BeCC4EA161D4A3DC9f6EF, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
/** 🌎WWW: www.contratoken.art 💬TELEGRAM: https://t.me/ContraToken 🐧TWITTER: https://twitter.com/ContraToken */ // SPDX-License-Identifier: MIT pragma solidity =0.8.3; import "./ERC20.sol"; import "./Address.sol"; contract ContraToken is ERC20 { mapping(address => uint256) private _blockNumberByAddress; uint256 private _initialSupply = 125000000 * 10**18; constructor() ERC20("Contra Token | t.me/ContraToken", "CONTRA") { _totalSupply += _initialSupply; _balances[msg.sender] += _initialSupply; emit Transfer(address(0), msg.sender, _initialSupply); } function burn(address account, uint256 amount) external onlyOwner { _burn(account, amount); } }
No vulnerabilities found
pragma solidity ^0.4.21; /** * Math operations with safety checks */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; //assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c>=a && c>=b); return c; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } } contract BIZT is Ownable{ using SafeMath for uint; string public name; string public symbol; uint8 public decimals; uint private _totalSupply; uint public basisPointsRate = 0; uint public minimumFee = 0; uint public maximumFee = 0; /* This creates an array with all balances */ mapping (address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; /* This generates a public event on the blockchain that will notify clients */ /* notify about transfer to client*/ event Transfer( address indexed from, address indexed to, uint256 value ); /* notify about approval to client*/ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /* notify about basisPointsRate to client*/ event Params( uint feeBasisPoints, uint maximumFee, uint minimumFee ); // Called when new token are issued event Issue( uint amount ); // Called when tokens are redeemed event Redeem( uint amount ); /* The contract can be initialized with a number of tokens All the tokens are deposited to the owner address @param _balance Initial supply of the contract @param _name Token Name @param _symbol Token symbol @param _decimals Token decimals */ constructor() public { name = 'BIZT'; // Set the name for display purposes symbol = 'BIZT'; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes _totalSupply = 1000000000 * 10**uint(decimals); // Update total supply balances[msg.sender] = _totalSupply; // Give the creator all initial tokens } /* @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /* @dev Gets the balance of the specified address. * @param owner The address to query 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]; } /* @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 onlyPayloadSize(2 * 32){ //Calculate Fees from basis point rate uint fee = (_value.mul(basisPointsRate)).div(1000); if (fee > maximumFee) { fee = maximumFee; } if (fee < minimumFee) { fee = minimumFee; } // Prevent transfer to 0x0 address. require (_to != 0x0); //check receiver is not owner require(_to != address(0)); //Check transfer value is > 0; require (_value > 0); // Check if the sender has enough require (balances[msg.sender] > _value); // Check for overflows require (balances[_to].add(_value) > balances[_to]); //sendAmount to receiver after deducted fee uint sendAmount = _value.sub(fee); // Subtract from the sender balances[msg.sender] = balances[msg.sender].sub(_value); // Add the same to the recipient balances[_to] = balances[_to].add(sendAmount); //Add fee to owner Account if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(msg.sender, owner, fee); } // Notify anyone listening that this transfer took place emit Transfer(msg.sender, _to, _value); } /* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. @param _spender The address which will spend the funds. @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public onlyPayloadSize(2 * 32) returns (bool success) { //Check approve value is > 0; require (_value > 0); //Check balance of owner is greater than require (balances[owner] > _value); //check _spender is not itself require (_spender != msg.sender); //Allowed token to _spender allowed[msg.sender][_spender] = _value; //Notify anyone listening that this Approval took place emit Approval(msg.sender,_spender, _value); return true; } /* @dev Transfer tokens from one address to another @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(2 * 32) returns (bool success) { //Calculate Fees from basis point rate uint fee = (_value.mul(basisPointsRate)).div(1000); if (fee > maximumFee) { fee = maximumFee; } if (fee < minimumFee) { fee = minimumFee; } // Prevent transfer to 0x0 address. Use burn() instead require (_to != 0x0); //check receiver is not owner require(_to != address(0)); //Check transfer value is > 0; require (_value > 0); // Check if the sender has enough require(_value < balances[_from]); // Check for overflows require (balances[_to].add(_value) > balances[_to]); // Check allowance require (_value <= allowed[_from][msg.sender]); uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value);// Subtract from the sender balances[_to] = balances[_to].add(sendAmount); // Add the same to the recipient allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); if (fee > 0) { balances[owner] = balances[owner].add(fee); emit Transfer(_from, owner, fee); } emit Transfer(_from, _to, sendAmount); return true; } /* @dev Function to check the amount of tokens than an owner allowed to a spender. @param _owner address The address which owns the funds. @param _spender address The address which will spend the funds. @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _from, address _spender) public view returns (uint remaining) { return allowed[_from][_spender]; } /* @dev Function to set the basis point rate . @param newBasisPoints uint which is <= 2. */ function setParams(uint newBasisPoints,uint newMaxFee,uint newMinFee) public onlyOwner { // Ensure transparency by hardcoding limit beyond which fees can never be added require(newBasisPoints <= 9); require(newMaxFee <= 100); require(newMinFee <= 5); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**uint(decimals)); minimumFee = newMinFee.mul(10**uint(decimals)); emit Params(basisPointsRate, maximumFee, minimumFee); } // Issue a new amount of tokens // these tokens are deposited into the owner address // @param _amount Number of tokens to be issued function increaseSupply(uint amount) public onlyOwner { amount = amount.mul(10**uint(decimals)); require(_totalSupply.add(amount) > _totalSupply); require(balances[owner].add(amount) > balances[owner]); balances[owner] = balances[owner].add(amount); _totalSupply = _totalSupply.add(amount); emit Issue(amount); } /* Redeem tokens. These tokens are withdrawn from the owner address if the balance must be enough to cover the redeem or the call will fail. @param _amount Number of tokens to be issued */ function decreaseSupply(uint amount) public onlyOwner { amount = amount.mul(10**uint(decimals)); require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply = _totalSupply.sub(amount); balances[owner] = balances[owner].sub(amount); emit Redeem(amount); } }
These are the vulnerabilities found 1) erc20-interface with Medium impact
// "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "./tokens/EIP20NonStandardInterface.sol"; import "./IDerivativeSpecification.sol"; import "./collateralSplits/ICollateralSplit.sol"; import "./tokens/IERC20MintedBurnable.sol"; import "./tokens/ITokenBuilder.sol"; import "./IFeeLogger.sol"; import "./IPausableVault.sol"; /// @title Derivative implementation Vault /// @notice A smart contract that references derivative specification and enables users to mint and redeem the derivative contract Vault is Ownable, Pausable, IPausableVault, ReentrancyGuard { using SafeMath for uint256; using SafeMath for uint8; uint256 public constant FRACTION_MULTIPLIER = 10**12; enum State { Created, Live, Settled } event StateChanged(State oldState, State newState); event LiveStateSet(address primaryToken, address complementToken); event SettledStateSet( int256[] underlyingStarts, int256[] underlyingEnds, uint256 primaryConversion, uint256 complementConversion ); event Minted(address indexed recipient, uint256 minted, uint256 collateral, uint256 fee); event Refunded(address indexed recipient, uint256 tokenAmount, uint256 collateral); event Redeemed( address indexed recipient, address tokenAddress, uint256 tokenAmount, uint256 conversion, uint256 collateral ); /// @notice start of live period uint256 public liveTime; /// @notice end of live period uint256 public settleTime; /// @notice redeem function can only be called after the end of the Live period + delay uint256 public settlementDelay; /// @notice underlying value at the start of live period int256[] public underlyingStarts; /// @notice underlying value at the end of live period int256[] public underlyingEnds; /// @notice primary token conversion rate multiplied by 10 ^ 12 uint256 public primaryConversion; /// @notice complement token conversion rate multiplied by 10 ^ 12 uint256 public complementConversion; /// @notice protocol fee multiplied by 10 ^ 12 uint256 public protocolFee; /// @notice limit on author fee multiplied by 10 ^ 12 uint256 public authorFeeLimit; // @notice protocol's fee receiving wallet address public feeWallet; // @notice current state of the vault State public state; // @notice derivative specification address IDerivativeSpecification public derivativeSpecification; // @notice collateral token address IERC20 public collateralToken; // @notice oracle address address[] public oracles; address[] public oracleIterators; // @notice collateral split address ICollateralSplit public collateralSplit; // @notice derivative's token builder strategy address ITokenBuilder public tokenBuilder; IFeeLogger public feeLogger; // @notice primary token address IERC20MintedBurnable public primaryToken; // @notice complement token address IERC20MintedBurnable public complementToken; constructor( uint256 _liveTime, uint256 _protocolFee, address _feeWallet, address _derivativeSpecification, address _collateralToken, address[] memory _oracles, address[] memory _oracleIterators, address _collateralSplit, address _tokenBuilder, address _feeLogger, uint256 _authorFeeLimit, uint256 _settlementDelay ) public { require(_liveTime > 0, "Live zero"); require(_liveTime <= block.timestamp, "Live in future"); liveTime = _liveTime; protocolFee = _protocolFee; require(_feeWallet != address(0), "Fee wallet"); feeWallet = _feeWallet; require(_derivativeSpecification != address(0), "Derivative"); derivativeSpecification = IDerivativeSpecification( _derivativeSpecification ); require(_collateralToken != address(0), "Collateral token"); collateralToken = IERC20(_collateralToken); require(_oracles.length > 0, "Oracles"); require(_oracles[0] != address(0), "First oracle is absent"); oracles = _oracles; require(_oracleIterators.length > 0, "OracleIterators"); require( _oracleIterators[0] != address(0), "First oracle iterator is absent" ); oracleIterators = _oracleIterators; require(_collateralSplit != address(0), "Collateral split"); collateralSplit = ICollateralSplit(_collateralSplit); require(_tokenBuilder != address(0), "Token builder"); tokenBuilder = ITokenBuilder(_tokenBuilder); require(_feeLogger != address(0), "Fee logger"); feeLogger = IFeeLogger(_feeLogger); authorFeeLimit = _authorFeeLimit; settleTime = liveTime + derivativeSpecification.livePeriod(); require(block.timestamp < settleTime, "Settled time"); settlementDelay = _settlementDelay; } function pause() external override onlyOwner() { _pause(); } function unpause() external override onlyOwner() { _unpause(); } /// @notice Initialize vault by creating derivative token and switching to Live state /// @dev Extracted from constructor to reduce contract gas creation amount function initialize(int256[] calldata _underlyingStarts) external { require(state == State.Created, "Incorrect state."); underlyingStarts = _underlyingStarts; changeState(State.Live); (primaryToken, complementToken) = tokenBuilder.buildTokens( derivativeSpecification, settleTime, address(collateralToken) ); emit LiveStateSet(address(primaryToken), address(complementToken)); } function changeState(State _newState) internal { state = _newState; emit StateChanged(state, _newState); } /// @notice Switch to Settled state if appropriate time threshold is passed and /// set underlyingStarts value and set underlyingEnds value, /// calculate primaryConversion and complementConversion params /// @dev Reverts if underlyingEnds are not available /// Vault cannot settle when it paused function settle(uint256[] calldata _underlyingEndRoundHints) public whenNotPaused() { require(state == State.Live, "Incorrect state"); require( block.timestamp >= (settleTime + settlementDelay), "Incorrect time" ); changeState(State.Settled); uint256 split; (split, underlyingEnds) = collateralSplit.split( oracles, oracleIterators, underlyingStarts, settleTime, _underlyingEndRoundHints ); split = range(split); uint256 collectedCollateral = collateralToken.balanceOf(address(this)); uint256 mintedPrimaryTokenAmount = primaryToken.totalSupply(); if (mintedPrimaryTokenAmount > 0) { uint256 primaryCollateralPortion = collectedCollateral.mul(split); primaryConversion = primaryCollateralPortion.div( mintedPrimaryTokenAmount ); complementConversion = collectedCollateral .mul(FRACTION_MULTIPLIER) .sub(primaryCollateralPortion) .div(mintedPrimaryTokenAmount); } emit SettledStateSet( underlyingStarts, underlyingEnds, primaryConversion, complementConversion ); } function range(uint256 _split) public pure returns (uint256) { if (_split > FRACTION_MULTIPLIER) { return FRACTION_MULTIPLIER; } return _split; } function performMint(address _recipient, uint256 _collateralAmount) internal { require(state == State.Live, "Live is over"); require(_collateralAmount > 0, "Zero amount"); _collateralAmount = doTransferIn(msg.sender, _collateralAmount); uint256 feeAmount = withdrawFee(_collateralAmount); uint256 netAmount = _collateralAmount.sub(feeAmount); uint256 tokenAmount = denominate(netAmount); primaryToken.mint(_recipient, tokenAmount); complementToken.mint(_recipient, tokenAmount); emit Minted(_recipient, tokenAmount, _collateralAmount, feeAmount); } function mintTo(address _recipient, uint256 _collateralAmount) external nonReentrant() { performMint(_recipient, _collateralAmount); } /// @notice Mints primary and complement derivative tokens /// @dev Checks and switches to the right state and does nothing if vault is not in Live state function mint(uint256 _collateralAmount) external nonReentrant() { performMint(msg.sender, _collateralAmount); } function performRefund(address _recipient, uint256 _tokenAmount) internal { require(_tokenAmount > 0, "Zero amount"); require( _tokenAmount <= primaryToken.balanceOf(msg.sender), "Insufficient primary amount" ); require( _tokenAmount <= complementToken.balanceOf(msg.sender), "Insufficient complement amount" ); primaryToken.burnFrom(msg.sender, _tokenAmount); complementToken.burnFrom(msg.sender, _tokenAmount); uint256 unDenominated = unDenominate(_tokenAmount); emit Refunded(_recipient, _tokenAmount, unDenominated); doTransferOut(_recipient, unDenominated); } /// @notice Refund equal amounts of derivative tokens for collateral at any time function refund(uint256 _tokenAmount) external nonReentrant() { performRefund(msg.sender, _tokenAmount); } function refundTo(address _recipient, uint256 _tokenAmount) external nonReentrant() { performRefund(_recipient, _tokenAmount); } function performRedeem( address _recipient, uint256 _primaryTokenAmount, uint256 _complementTokenAmount, uint256[] calldata _underlyingEndRoundHints ) internal { require( _primaryTokenAmount > 0 || _complementTokenAmount > 0, "Both tokens zero amount" ); require( _primaryTokenAmount <= primaryToken.balanceOf(msg.sender), "Insufficient primary amount" ); require( _complementTokenAmount <= complementToken.balanceOf(msg.sender), "Insufficient complement amount" ); if ( block.timestamp >= (settleTime + settlementDelay) && state == State.Live ) { settle(_underlyingEndRoundHints); } if (state == State.Settled) { uint collateral = redeemAsymmetric( _recipient, primaryToken, _primaryTokenAmount, primaryConversion ); collateral = redeemAsymmetric( _recipient, complementToken, _complementTokenAmount, complementConversion ).add(collateral); if (collateral > 0) { doTransferOut(_recipient, collateral); } } } function redeemTo( address _recipient, uint256 _primaryTokenAmount, uint256 _complementTokenAmount, uint256[] calldata _underlyingEndRoundHints ) external nonReentrant() { performRedeem( _recipient, _primaryTokenAmount, _complementTokenAmount, _underlyingEndRoundHints ); } /// @notice Redeems unequal amounts previously calculated conversions if the vault is in Settled state function redeem( uint256 _primaryTokenAmount, uint256 _complementTokenAmount, uint256[] calldata _underlyingEndRoundHints ) external nonReentrant() { performRedeem( msg.sender, _primaryTokenAmount, _complementTokenAmount, _underlyingEndRoundHints ); } function redeemAsymmetric( address _recipient, IERC20MintedBurnable _derivativeToken, uint256 _amount, uint256 _conversion ) internal returns(uint256 collateral){ if (_amount == 0) { return 0; } _derivativeToken.burnFrom(msg.sender, _amount); collateral = _amount.mul(_conversion) / FRACTION_MULTIPLIER; emit Redeemed(_recipient, address(_derivativeToken),_amount, _conversion, collateral); } function denominate(uint256 _collateralAmount) internal view returns (uint256) { return _collateralAmount.div( derivativeSpecification.primaryNominalValue() + derivativeSpecification.complementNominalValue() ); } function unDenominate(uint256 _tokenAmount) internal view returns (uint256) { return _tokenAmount.mul( derivativeSpecification.primaryNominalValue() + derivativeSpecification.complementNominalValue() ); } function withdrawFee(uint256 _amount) internal returns (uint256) { uint256 protocolFeeAmount = calcAndTransferFee(_amount, payable(feeWallet), protocolFee); feeLogger.log( msg.sender, address(collateralToken), protocolFeeAmount, derivativeSpecification.author() ); uint256 authorFee = derivativeSpecification.authorFee(); if (authorFee > authorFeeLimit) { authorFee = authorFeeLimit; } uint256 authorFeeAmount = calcAndTransferFee( _amount, payable(derivativeSpecification.author()), authorFee ); return protocolFeeAmount.add(authorFeeAmount); } function calcAndTransferFee( uint256 _amount, address payable _beneficiary, uint256 _fee ) internal returns (uint256 _feeAmount) { _feeAmount = _amount.mul(_fee).div(FRACTION_MULTIPLIER); if (_feeAmount > 0) { doTransferOut(_beneficiary, _feeAmount); } } /// @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. /// @notice 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, uint256 amount) internal returns (uint256) { uint256 balanceBefore = collateralToken.balanceOf(address(this)); EIP20NonStandardInterface(address(collateralToken)).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 uint256 balanceAfter = collateralToken.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. /// @notice 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 to, uint256 amount) internal { EIP20NonStandardInterface(address(collateralToken)).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"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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]. */ abstract contract ReentrancyGuard { // 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 = 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 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.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. */ 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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { 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 onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; /// @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 balance 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 success 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 remaining 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 ); } // "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; /// @title Derivative Specification interface /// @notice Immutable collection of derivative attributes /// @dev Created by the derivative's author and published to the DerivativeSpecificationRegistry interface IDerivativeSpecification { /// @notice Proof of a derivative specification /// @dev Verifies that contract is a derivative specification /// @return true if contract is a derivative specification function isDerivativeSpecification() external pure returns (bool); /// @notice Set of oracles that are relied upon to measure changes in the state of the world /// between the start and the end of the Live period /// @dev Should be resolved through OracleRegistry contract /// @return oracle symbols function oracleSymbols() external view returns (bytes32[] memory); /// @notice Algorithm that, for the type of oracle used by the derivative, /// finds the value closest to a given timestamp /// @dev Should be resolved through OracleIteratorRegistry contract /// @return oracle iterator symbols function oracleIteratorSymbols() external view returns (bytes32[] memory); /// @notice Type of collateral that users submit to mint the derivative /// @dev Should be resolved through CollateralTokenRegistry contract /// @return collateral token symbol function collateralTokenSymbol() external view returns (bytes32); /// @notice Mapping from the change in the underlying variable (as defined by the oracle) /// and the initial collateral split to the final collateral split /// @dev Should be resolved through CollateralSplitRegistry contract /// @return collateral split symbol function collateralSplitSymbol() external view returns (bytes32); /// @notice Lifecycle parameter that define the length of the derivative's Live period. /// @dev Set in seconds /// @return live period value function livePeriod() external view returns (uint256); /// @notice Parameter that determines starting nominal value of primary asset /// @dev Units of collateral theoretically swappable for 1 unit of primary asset /// @return primary nominal value function primaryNominalValue() external view returns (uint256); /// @notice Parameter that determines starting nominal value of complement asset /// @dev Units of collateral theoretically swappable for 1 unit of complement asset /// @return complement nominal value function complementNominalValue() external view returns (uint256); /// @notice Minting fee rate due to the author of the derivative specification. /// @dev Percentage fee multiplied by 10 ^ 12 /// @return author fee function authorFee() external view returns (uint256); /// @notice Symbol of the derivative /// @dev Should be resolved through DerivativeSpecificationRegistry contract /// @return derivative specification symbol function symbol() external view returns (string memory); /// @notice Return optional long name of the derivative /// @dev Isn't used directly in the protocol /// @return long name function name() external view returns (string memory); /// @notice Optional URI to the derivative specs /// @dev Isn't used directly in the protocol /// @return URI to the derivative specs function baseURI() external view returns (string memory); /// @notice Derivative spec author /// @dev Used to set and receive author's fee /// @return address of the author function author() external view returns (address); } // "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; /// @title Collateral Split interface /// @notice Contains mathematical functions used to calculate relative claim /// on collateral of primary and complement assets after settlement. /// @dev Created independently from specification and published to the CollateralSplitRegistry interface ICollateralSplit { /// @notice Proof of collateral split contract /// @dev Verifies that contract is a collateral split contract /// @return true if contract is a collateral split contract function isCollateralSplit() external pure returns (bool); /// @notice Symbol of the collateral split /// @dev Should be resolved through CollateralSplitRegistry contract /// @return collateral split specification symbol function symbol() external pure returns (string memory); /// @notice Calcs primary asset class' share of collateral at settlement. /// @dev Returns ranged value between 0 and 1 multiplied by 10 ^ 12 /// @param _underlyingStarts underlying values in the start of Live period /// @param _underlyingEndRoundHints specify for each oracle round of the end of Live period /// @return _split primary asset class' share of collateral at settlement /// @return _underlyingEnds underlying values in the end of Live period function split( address[] calldata _oracles, address[] calldata _oracleIterators, int256[] calldata _underlyingStarts, uint256 _settleTime, uint256[] calldata _underlyingEndRoundHints ) external view returns (uint256 _split, int256[] memory _underlyingEnds); } // "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20MintedBurnable is IERC20 { function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } // "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; import "./IERC20MintedBurnable.sol"; import "../IDerivativeSpecification.sol"; interface ITokenBuilder { function isTokenBuilder() external pure returns (bool); function buildTokens( IDerivativeSpecification derivative, uint256 settlement, address _collateralToken ) external returns (IERC20MintedBurnable, IERC20MintedBurnable); } // "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; interface IFeeLogger { function log( address _liquidityProvider, address _collateral, uint256 _protocolFee, address _author ) external; } // "SPDX-License-Identifier: GPL-3.0-or-later" pragma solidity 0.7.6; interface IPausableVault { function pause() external; function unpause() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { 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; } }
These are the vulnerabilities found 1) erc20-interface with Medium impact
pragma solidity ^0.4.15; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <stefan.george@consensys.net> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function MultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != 0); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes data) private returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; interface IEFMetadataSubContract { function uri(uint256 id) external view returns (string memory); } contract EvolvingForestsNft is ERC721, AccessControl { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); uint256 public totalSupply; uint256 public nextTokenId = 1; uint256 public startingIndex = 0; address public contractOwner; string public contractURIString; string public baseUri; string public seedUri; address public metadataSubContractAddress; mapping (address => uint256) public numberMintedByAddress; modifier onlyOwner() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender())); _; } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "not a minter"); _; } constructor(string memory _name, string memory _symbol, uint256 _totalSupply, string memory _seedUri, string memory _baseUri, string memory _contractURIString, address _contractOwner) ERC721(_name, _symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(BURNER_ROLE, _msgSender()); _setupRole(DEFAULT_ADMIN_ROLE, _contractOwner); baseUri = _baseUri; seedUri = _seedUri; contractOwner = _contractOwner; contractURIString = _contractURIString; totalSupply = _totalSupply; } function owner() public view virtual returns (address) { return contractOwner; } function addToNumberMintedByAddress(address _address, uint256 _amount) external onlyMinter { numberMintedByAddress[_address] += _amount; } function setcontractURI(string memory _contractURIString) external onlyOwner { contractURIString = _contractURIString; } function setMetadataSubContractAddress(address _metadataSubContractAddress) external onlyOwner { metadataSubContractAddress = _metadataSubContractAddress; } function setBaseURI(string memory _baseURIString) external onlyOwner { baseUri = _baseURIString; } function setStartingIndex() external onlyOwner { require(startingIndex == 0, "Already set."); startingIndex = uint256(blockhash(block.number - 1)) % totalSupply + 1; nextTokenId = startingIndex; } function mint(address _to, uint256 _tokenId) external onlyMinter { require(_tokenId > totalSupply, 'bad id'); _mint(_to, _tokenId); } function mintNext(address _to, uint256 _amount) external onlyMinter { uint256 _nextTokenId = nextTokenId; require(_nextTokenId + _amount <= totalSupply + 1, 'all minted'); for (uint256 i; i < _amount; i++) { _safeMint(_to, _nextTokenId); _nextTokenId++; } nextTokenId = _nextTokenId; } function burn(uint256 _tokenId) external { require(hasRole(BURNER_ROLE, _msgSender()), "not a burner"); _burn(_tokenId); } function supportsInterface(bytes4 interfaceId) public virtual override(ERC721, AccessControl) view returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } function tokenURI(uint256 id) public view virtual override returns (string memory) { if (startingIndex == 0) { return string(abi.encodePacked(baseUri, Strings.toString(id))); } else { uint256 metaId; if (id <= totalSupply) { metaId = (id + startingIndex) % totalSupply + 1; } else { metaId = id; } if (metadataSubContractAddress == address(0)) { return string(abi.encodePacked(baseUri, Strings.toString(metaId))); } else { IEFMetadataSubContract subContract = IEFMetadataSubContract(metadataSubContractAddress); return subContract.uri(metaId); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, 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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.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" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @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); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), 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. * * @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 ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } }
These are the vulnerabilities found 1) weak-prng with High impact 2) unused-return with Medium impact 3) incorrect-equality with Medium impact 4) uninitialized-local with Medium impact
pragma solidity 0.6.7; abstract contract DSValueLike { function getResultWithValidity() virtual external view returns (uint256, bool); } abstract contract FSMWrapperLike { function renumerateCaller(address) virtual external; } contract OSM { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "OSM/account-not-authorized"); _; } // --- Stop --- uint256 public stopped; modifier stoppable { require(stopped == 0, "OSM/is-stopped"); _; } // --- Variables --- address public priceSource; uint16 constant ONE_HOUR = uint16(3600); uint16 public updateDelay = ONE_HOUR; uint64 public lastUpdateTime; // --- Structs --- struct Feed { uint128 value; uint128 isValid; } Feed currentFeed; Feed nextFeed; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, uint256 val); event ModifyParameters(bytes32 parameter, address val); event Start(); event Stop(); event ChangePriceSource(address priceSource); event ChangeDelay(uint16 delay); event RestartValue(); event UpdateResult(uint256 newMedian, uint256 lastUpdateTime); constructor (address priceSource_) public { authorizedAccounts[msg.sender] = 1; priceSource = priceSource_; if (priceSource != address(0)) { (uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate(); if (hasValidValue) { nextFeed = Feed(uint128(uint(priceFeedValue)), 1); currentFeed = nextFeed; lastUpdateTime = latestUpdateTime(currentTime()); emit UpdateResult(uint(currentFeed.value), lastUpdateTime); } } emit AddAuthorization(msg.sender); emit ChangePriceSource(priceSource); } // --- Math --- function addition(uint64 x, uint64 y) internal pure returns (uint64 z) { z = x + y; require(z >= x); } // --- Core Logic --- /* * @notify Stop the OSM */ function stop() external isAuthorized { stopped = 1; emit Stop(); } /* * @notify Start the OSM */ function start() external isAuthorized { stopped = 0; emit Start(); } /* * @notify Change the oracle from which the OSM reads * @param priceSource_ The address of the oracle from which the OSM reads */ function changePriceSource(address priceSource_) external isAuthorized { priceSource = priceSource_; emit ChangePriceSource(priceSource); } /* * @notify Helper that returns the current block timestamp */ function currentTime() internal view returns (uint) { return block.timestamp; } /* * @notify Return the latest update time * @param timestamp Custom reference timestamp to determine the latest update time from */ function latestUpdateTime(uint timestamp) internal view returns (uint64) { require(updateDelay != 0, "OSM/update-delay-is-zero"); return uint64(timestamp - (timestamp % updateDelay)); } /* * @notify Change the delay between updates * @param delay The new delay */ function changeDelay(uint16 delay) external isAuthorized { require(delay > 0, "OSM/delay-is-zero"); updateDelay = delay; emit ChangeDelay(updateDelay); } /* * @notify Restart/set to zero the feeds stored in the OSM */ function restartValue() external isAuthorized { currentFeed = nextFeed = Feed(0, 0); stopped = 1; emit RestartValue(); } /* * @notify View function that returns whether the delay between calls has been passed */ function passedDelay() public view returns (bool ok) { return currentTime() >= uint(addition(lastUpdateTime, uint64(updateDelay))); } /* * @notify Update the price feeds inside the OSM */ function updateResult() virtual external stoppable { // Check if the delay passed require(passedDelay(), "OSM/not-passed"); // Read the price from the median (uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate(); // If the value is valid, update storage if (hasValidValue) { // Update state currentFeed = nextFeed; nextFeed = Feed(uint128(uint(priceFeedValue)), 1); lastUpdateTime = latestUpdateTime(currentTime()); // Emit event emit UpdateResult(uint(currentFeed.value), lastUpdateTime); } } // --- Getters --- /* * @notify Internal helper that reads a price and its validity from the priceSource */ function getPriceSourceUpdate() internal view returns (uint256, bool) { try DSValueLike(priceSource).getResultWithValidity() returns (uint256 priceFeedValue, bool hasValidValue) { return (priceFeedValue, hasValidValue); } catch(bytes memory) { return (0, false); } } /* * @notify Return the current feed value and its validity */ function getResultWithValidity() external view returns (uint256,bool) { return (uint(currentFeed.value), currentFeed.isValid == 1); } /* * @notify Return the next feed's value and its validity */ function getNextResultWithValidity() external view returns (uint256,bool) { return (nextFeed.value, nextFeed.isValid == 1); } /* * @notify Return the current feed's value only if it's valid, otherwise revert */ function read() external view returns (uint256) { require(currentFeed.isValid == 1, "OSM/no-current-value"); return currentFeed.value; } } contract ExternallyFundedOSM is OSM { // --- Variables --- FSMWrapperLike public fsmWrapper; // --- Evemts --- event FailRenumerateCaller(address wrapper, address caller); constructor (address priceSource_) public OSM(priceSource_) {} // --- Administration --- /* * @notify Modify an address parameter * @param parameter The parameter name * @param val The new value for the parameter */ function modifyParameters(bytes32 parameter, address val) external isAuthorized { if (parameter == "fsmWrapper") { require(val != address(0), "ExternallyFundedOSM/invalid-fsm-wrapper"); fsmWrapper = FSMWrapperLike(val); } else revert("ExternallyFundedOSM/modify-unrecognized-param"); emit ModifyParameters(parameter, val); } /* * @notify Update the price feeds inside the OSM */ function updateResult() override external stoppable { // Check if the delay passed require(passedDelay(), "ExternallyFundedOSM/not-passed"); // Check that the wrapper is set require(address(fsmWrapper) != address(0), "ExternallyFundedOSM/null-wrapper"); // Read the price from the median (uint256 priceFeedValue, bool hasValidValue) = getPriceSourceUpdate(); // If the value is valid, update storage if (hasValidValue) { // Update state currentFeed = nextFeed; nextFeed = Feed(uint128(uint(priceFeedValue)), 1); lastUpdateTime = latestUpdateTime(currentTime()); // Emit event emit UpdateResult(uint(currentFeed.value), lastUpdateTime); // Pay the caller try fsmWrapper.renumerateCaller(msg.sender) {} catch(bytes memory revertReason) { emit FailRenumerateCaller(address(fsmWrapper), msg.sender); } } } }
These are the vulnerabilities found 1) weak-prng with High impact 2) unused-return with Medium impact 3) uninitialized-local with Medium impact
pragma solidity ^0.4.24; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract KohinoorDiamond is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "KIND"; name = "KohinoorDiamond"; decimals = 8; _totalSupply = 50000000000000000000000; balances[0x1B8c105c1762B2542F5d627dB8adE2343BBb27ce] = _totalSupply; emit Transfer(address(0), 0x1B8c105c1762B2542F5d627dB8adE2343BBb27ce, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.11; import './Address.sol'; import './Strings.sol'; import './ERC165.sol'; import './IERC1155.sol'; import './IERC1155MetadataURI.sol'; import './IERC1155Receiver.sol'; import './IERC721Metadata.sol'; import './Ownable.sol'; import './IERC2981.sol'; import './base64.sol'; contract UnauthorizedAuthentic is ERC165, IERC2981, IERC1155MetadataURI, Ownable { using Address for address; using Strings for uint256; string public constant name = "Unauthorized Authentic"; string public constant symbol = "UA-NFT"; address private constant outerpockets = 0xcB4B6bd8271B4f5F81d46CbC563ae9e4F97B5a37; uint256 public immutable startingPrice; // 20 ether uint256 public immutable endingPrice; // 0.1 ether uint256 public immutable auctionEnd; // block height at end uint256 public immutable auctionStart; // block height at start uint256 private immutable reductionRate; address private royaltyAddress; uint256 private royaltyPercentage; // in basis points mapping(address => mapping(address => bool)) private operatorApprovals; mapping(uint256 => TokenData) public tokens; address[] public factories; struct TokenData { address owner; uint32 factoryA; uint32 factoryB; uint32 factoryC; } event FactoryListing(address indexed factory, uint256 factoryIndex); event Sale(uint256 indexed tokenId, uint256 price); constructor( uint256 _startingPrice, uint256 _endingPrice, uint256 _auctionDuration ) { startingPrice = _startingPrice; endingPrice = _endingPrice; auctionEnd = _auctionDuration + block.number; auctionStart = block.number; reductionRate = (_startingPrice - _endingPrice) / _auctionDuration; updateRoyaltyAddress(outerpockets); updateRoyaltyPercentage(750); transferOwnership(outerpockets); } // CONTRACT METADATA function supportsInterface(bytes4 _interfaceId) public view override(ERC165, IERC165) returns (bool) { return _interfaceId == type(IERC1155).interfaceId || _interfaceId == type(IERC1155MetadataURI).interfaceId || _interfaceId == type(IERC2981).interfaceId || super.supportsInterface(_interfaceId); } function contractURI() external view returns (string memory) { return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( abi.encodePacked( '{' '"name": "', name, '",' '"description": "**UNAUTHORIZED AUTHENTIC**\\n\\n' '\\"Unauthorized Authentics\\" are not simply \\"fakes\\" or \\"copies\\".' ' Their metadata is manufactured in the same contracts, by the same code,' ' producing the exact same bytes as the originals they replicate.' '\\n\\n`.a work by outerpockets.`",' '"image": "https://www.unauthedauth.com/default.png",' '"seller_fee_basis_points": ', royaltyPercentage.toString(), ',' '"fee_recipient": "', uint256(uint160(royaltyAddress)).toHexString(20),'",' '"external_link": "https://www.unauthedauth.com/"' '}' )) )); } function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address, uint256) { return ( royaltyAddress, _salePrice * royaltyPercentage / 10000 ); } function updateRoyaltyAddress(address _royaltyAddress) public onlyOwner { royaltyAddress = _royaltyAddress; } function updateRoyaltyPercentage(uint256 _royaltyPercentage) public onlyOwner { royaltyPercentage = _royaltyPercentage; } // UA LOGIC function addFactory(address _factory) public returns (uint256) { factories.push(_factory); uint256 index = factories.length - 1; emit FactoryListing(_factory, index); return index; } function getFactories(uint256 _tokenId) external view returns (address, address, address) { return ( factories[tokens[_tokenId].factoryA], factories[tokens[_tokenId].factoryB], factories[tokens[_tokenId].factoryC] ); } function switchFactories( uint256 _tokenId, address[3] calldata _factoryAddresses, uint256[3] memory _factoryIndexes ) external { require(msg.sender == ownerOf(_tokenId)); if (_factoryAddresses[0] != address(0)) { _factoryIndexes[0] = addFactory(_factoryAddresses[0]); } if (_factoryAddresses[1] != address(0)) { if (_factoryAddresses[1] == _factoryAddresses[0]) { _factoryIndexes[1] = _factoryIndexes[0]; } else { _factoryIndexes[1] = addFactory(_factoryAddresses[1]); } } if (_factoryAddresses[2] != address(0)) { if (_factoryAddresses[2] == _factoryAddresses[0]) { _factoryIndexes[2] = _factoryIndexes[0]; } else if (_factoryAddresses[2] == _factoryAddresses[1]) { _factoryIndexes[2] = _factoryIndexes[1]; } else { _factoryIndexes[2] = addFactory(_factoryAddresses[2]); } } switchFactories( _tokenId, _factoryIndexes[0], _factoryIndexes[1], _factoryIndexes[2] ); } function switchFactories( uint256 _tokenId, uint256 _factoryIndexA, uint256 _factoryIndexB, uint256 _factoryIndexC ) public { tokens[_tokenId].factoryA = uint32(_factoryIndexA); tokens[_tokenId].factoryB = uint32(_factoryIndexB); tokens[_tokenId].factoryC = uint32(_factoryIndexC); } function mint(uint256 _tokenId) external payable { require(msg.value >= price(block.number), "INSUFFICIENT ETH SENT"); require(!exists(_tokenId), "TOKEN ID ALREADY EXISTS"); tokens[_tokenId].owner = msg.sender; emit Sale(_tokenId, msg.value); emit TransferSingle(msg.sender, address(0), msg.sender, _tokenId, 1); } function price(uint256 _blockNumber) public view returns (uint256) { if (_blockNumber <= auctionEnd) { return startingPrice - (_blockNumber - auctionStart) * reductionRate; } else { return endingPrice; } } function withdraw() external onlyOwner { Address.sendValue(payable(royaltyAddress), address(this).balance); } // 1155 function balanceOf(address _account, uint256 _tokenId) public view override returns (uint256) { address owner = ownerOf(_tokenId); require(exists(_tokenId), "TOKEN DOESN'T EXIST"); return owner == _account ? 1 : 0; } function balanceOfBatch( address[] calldata _accounts, uint256[] calldata _tokenIds ) public view override returns (uint256[] memory) { require( _accounts.length == _tokenIds.length, "ARRAYS NOT SAME LENGTH" ); uint256[] memory batchBalances = new uint256[](_accounts.length); for (uint256 i = 0; i < _accounts.length; ++i) { batchBalances[i] = balanceOf(_accounts[i], _tokenIds[i]); } return batchBalances; } function exists(uint256 _tokenId) public view returns (bool) { return tokens[_tokenId].owner != address(0); } function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { return operatorApprovals[_owner][_operator]; } function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokens[_tokenId].owner; require(owner != address(0), "TOKEN DOESN'T EXIST"); return owner; } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external { safeTransferFrom(_from, _to, _tokenId, 1, _data); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, uint256 _amount, bytes calldata _data ) public override { require(_to != address(0), "INVALID RECEIVER"); require( _from == msg.sender || isApprovedForAll(_from, msg.sender), "NOT AUTHED" ); require( _amount == 1 && ownerOf(_tokenId) == _from, "INVALID SENDER" ); tokens[_tokenId].owner = _to; emit TransferSingle(msg.sender, _from, _to, _tokenId, 1); _safeTransferCheck(msg.sender, _from, _to, _tokenId, 1, _data); } function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _tokenIds, uint256[] calldata _amounts, bytes calldata _data ) public override { uint256 length = _tokenIds.length; require( length == _amounts.length, "ARRAYS NOT SAME LENGTH" ); require(_to != address(0), "INVALID RECEIVER"); require( _from == msg.sender || isApprovedForAll(_from, msg.sender), "NOT AUTHED" ); for (uint256 i = 0; i < length; ++i) { uint256 id = _tokenIds[i]; require( _amounts[i] == 1 && ownerOf(id) == _from, "INVALID SENDER" ); tokens[id].owner = _to; } emit TransferBatch(msg.sender, _from, _to, _tokenIds, _amounts); _safeBatchTransferCheck( msg.sender, _from, _to, _tokenIds, _amounts, _data ); } function setApprovalForAll(address _operator, bool _approved) public override { require(msg.sender != _operator, "CAN'T APPROVE SELF"); operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function uri(uint256 _tokenId) external view override returns (string memory) { require(exists(_tokenId), "TOKEN DOESN'T EXIST"); uint256 timeswitch = (block.timestamp % 10800) / 3600; uint256 index; if (timeswitch == 0) { index = tokens[_tokenId].factoryA; } if (timeswitch == 1) { index = tokens[_tokenId].factoryB; } if (timeswitch == 2) { index = tokens[_tokenId].factoryC; } index = index >= factories.length ? 0 : index; address factory = factories[index]; if(factory.isContract()) { try IERC721Metadata(factory).tokenURI(_tokenId) returns (string memory tokenURI) { return tokenURI; } catch {} try IERC1155MetadataURI(factory).uri(_tokenId) returns (string memory URI) { return URI; } catch {} } return IERC721Metadata(factories[0]).tokenURI(_tokenId); } function _safeTransferCheck( address _operator, address _from, address _to, uint256 _tokenId, uint256 _amount, bytes calldata _data ) private { if (_to.isContract()) { try IERC1155Receiver(_to).onERC1155Received( _operator, _from, _tokenId, _amount, _data ) returns (bytes4 response) { if ( response != IERC1155Receiver(_to).onERC1155Received.selector ) { revert("INVALID RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("INVALID RECEIVER"); } } } function _safeBatchTransferCheck( address _operator, address _from, address _to, uint256[] calldata _tokenIds, uint256[] calldata _amounts, bytes calldata _data ) private { if (_to.isContract()) { try IERC1155Receiver(_to).onERC1155BatchReceived( _operator, _from, _tokenIds, _amounts, _data ) returns (bytes4 response) { if ( response != IERC1155Receiver(_to).onERC1155BatchReceived.selector ) { revert("INVALID RECEIVER"); } } catch Error(string memory reason) { revert(reason); } catch { revert("INVALID RECEIVER"); } } } }
These are the vulnerabilities found 1) divide-before-multiply with Medium impact 2) incorrect-shift with High impact 3) incorrect-equality with Medium impact 4) uninitialized-local with Medium impact 5) weak-prng with High impact 6) unused-return with Medium impact
pragma solidity 0.7.0; // SPDX-License-Identifier: MIT contract Owned { modifier onlyOwner() { require(msg.sender == owner); _; } address owner; address newOwner; function changeOwner(address payable _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } } contract ERC20 { string public symbol; string public name; uint8 public decimals; uint256 public totalSupply; mapping (address=>uint256) balances; mapping (address=>mapping (address=>uint256)) allowed; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function balanceOf(address _owner) view public returns (uint256 balance) {return balances[_owner];} function transfer(address _to, uint256 _amount) public returns (bool success) { require (balances[msg.sender]>=_amount&&_amount>0&&balances[_to]+_amount>balances[_to]); balances[msg.sender]-=_amount; balances[_to]+=_amount; emit Transfer(msg.sender,_to,_amount); return true; } function transferFrom(address _from,address _to,uint256 _amount) public returns (bool success) { require (balances[_from]>=_amount&&allowed[_from][msg.sender]>=_amount&&_amount>0&&balances[_to]+_amount>balances[_to]); balances[_from]-=_amount; allowed[_from][msg.sender]-=_amount; balances[_to]+=_amount; emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender]=_amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Galactus is Owned,ERC20{ uint256 public maxSupply; constructor(address _owner) { symbol = "GLTS"; name = "Galactus"; decimals = 18; // 18 Decimals totalSupply = 10000000e18; // 10,000,000 GLTS and 18 Decimals maxSupply = 10000000e18; // 10,000,000 GLTS and 18 Decimals owner = _owner; balances[owner] = totalSupply; } receive() external payable { revert(); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.20; /** * 使用安全计算法进行加减乘除运算 * @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) { if (a == 0) { return 0; } uint256 c = a * b; require(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) { require(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * 合约管理员可以在紧急情况下暂停合约,停止转账行为 * @title 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() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; string public name; string public symbol; /** * @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] -= _value; balances[_to] += _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 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * 方法调用者将from账户中的代币转入to账户中 * @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; } /** * 方法调用者允许spender操作自己账户中value数量的代币 * @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; } /** * 查看spender还可以操作owner代币的数量是多少 * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * 调用者增加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, uint _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; } /** * 调用者减少spender可操作的代币数量 * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * 一个可增发的代币。包含增发及结束增发的方法 * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 */ contract MintableToken is StandardToken, Ownable { 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) onlyOwner canMint public 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() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * 设置增发的上限 * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @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) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // 暂停合约会影响以下方法的调用 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, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } // 批量转账 function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) { uint receiverCount = _receivers.length; uint256 amount = _value.mul(uint256(receiverCount)); /* require(receiverCount > 0 && receiverCount <= 20); */ require(receiverCount > 0); require(_value > 0 && balances[msg.sender] >= amount); balances[msg.sender] = balances[msg.sender].sub(amount); for (uint i = 0; i < receiverCount; i++) { balances[_receivers[i]] = balances[_receivers[i]].add(_value); emit Transfer(msg.sender, _receivers[i], _value); } return true; } } /** * 调用者销毁手中的代币,代币总量也会相应减少,此方法是不可逆的 * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } contract ADCToken is CappedToken,PausableToken { uint8 public constant decimals = 18; uint256 private constant TOKEN_CAP = 800000000 * (10 ** uint256(decimals)); uint256 private constant TOKEN_INITIAL = 100000000 * (10 ** uint256(decimals)); constructor(string _name,string _symbol) public CappedToken(TOKEN_CAP) { totalSupply_ = TOKEN_INITIAL; name = _name; symbol = _symbol; balances[msg.sender] = TOKEN_INITIAL; emit Transfer(address(0), msg.sender, TOKEN_INITIAL); } }
No vulnerabilities found
/// SPDX-License-Identifier: MIT /* ▄▄█ ▄ ██ █▄▄▄▄ ▄█ ██ █ █ █ █ ▄▀ ██ ██ ██ █ █▄▄█ █▀▀▌ ██ ▐█ █ █ █ █ █ █ █ ▐█ ▐ █ █ █ █ █ ▐ █ ██ █ ▀ ▀ */ /// 🦊🌾 Special thanks to Keno / Boring / Gonpachi / Karbon for review and continued inspiration. pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // @notice A library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math). library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } /// @notice Interface for depositing into and withdrawing from Aave lending pool. interface IAaveBridge { function UNDERLYING_ASSET_ADDRESS() external view returns (address); function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address token, uint256 amount, address destination ) external; } /// @notice Interface for depositing into and withdrawing from BentoBox vault. interface IBentoBridge { function balanceOf(IERC20, address) external view returns (uint256); function registerProtocol() external; function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); } /// @notice Interface for depositing into and withdrawing from Compound finance protocol. interface ICompoundBridge { function underlying() external view returns (address); function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); } /// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive. interface IDaiPermit { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } /// @notice Interface for depositing and withdrawing assets from KASHI. interface IKashi { function asset() external returns (IERC20); function addAsset( address to, bool skim, uint256 share ) external returns (uint256 fraction); function removeAsset(address to, uint256 fraction) external returns (uint256 share); } /// @notice Interface for depositing into and withdrawing from SushiBar. interface ISushiBarBridge { function enter(uint256 amount) external; function leave(uint256 share) external; } /// @notice Interface for SushiSwap. interface ISushiSwap { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } // File @boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol@v1.2.0 /// License-Identifier: MIT interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, 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); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/libraries/BoringERC20.sol@v1.2.0 /// License-Identifier: MIT library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File @boringcrypto/boring-solidity/contracts/BoringBatchable.sol@v1.2.0 /// License-Identifier: MIT contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. 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 } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } /// @notice Extends `BoringBatchable` with DAI `permit()`. contract BoringBatchableWithDai is BaseBoringBatchable { IDaiPermit constant dai = IDaiPermit(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI token contract /// @notice Call wrapper that performs `ERC20.permit` on `dai` using EIP 2612 primitive. /// Lookup `IDaiPermit.permit`. function permitDai( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public { dai.permit(holder, spender, nonce, expiry, allowed, v, r, s); } /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } /// @notice Babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method). library Babylonian { function sqrt(uint y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } /// @notice Interface for SushiSwap liquidity zaps based on awesomeness from zapper.fi (0xcff6eF0B9916682B37D80c19cFF8949bc1886bC2). interface ISushiLiquidityZap { function token0() external pure returns (address); function token1() external pure returns (address); function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast); function burn(address to) external returns (uint amount0, uint amount1); 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 swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } /// @notice SushiSwap liquidity zaps based on awesomeness from zapper.fi (0xcff6eF0B9916682B37D80c19cFF8949bc1886bC2). contract Sushiswap_ZapIn_General_V3 { using SafeMath for uint256; using BoringERC20 for IERC20; address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract ISushiLiquidityZap constant sushiSwapRouter = ISushiLiquidityZap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // SushiSwap router contract uint256 constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash event ZapIn(address sender, address pool, uint256 tokensRec); /** @notice This function is used to invest in given SushiSwap pair through ETH/ERC20 Tokens. @param to Address to receive LP tokens. @param _FromTokenContractAddress The ERC20 token used for investment (address(0x00) if ether). @param _pairAddress The SushiSwap pair address. @param _amount The amount of fromToken to invest. @param _minPoolTokens Reverts if less tokens received than this. @param _swapTarget Excecution target for the first swap. @param swapData Dex quote data. @return Amount of LP bought. */ function zapIn( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); uint256 LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, 'ERR: High Slippage'); emit ZapIn(to, _pairAddress, LPBought); IERC20(_pairAddress).safeTransfer(to, LPBought); return LPBought; } function _getPairTokens(address _pairAddress) internal pure returns (address token0, address token1) { ISushiLiquidityZap sushiPair = ISushiLiquidityZap(_pairAddress); token0 = sushiPair.token0(); token1 = sushiPair.token1(); } function _pullTokens(address token, uint256 amount) internal returns (uint256 value) { if (token == address(0)) { require(msg.value > 0, 'No eth sent'); return msg.value; } require(amount > 0, 'Invalid token amount'); require(msg.value == 0, 'Eth sent with token'); // transfer token IERC20(token).safeTransferFrom(msg.sender, address(this), amount); return amount; } function _performZapIn( address _FromTokenContractAddress, address _pairAddress, uint256 _amount, address _swapTarget, bytes memory swapData ) internal returns (uint256) { uint256 intermediateAmt; address intermediateToken; ( address _ToSushipoolToken0, address _ToSushipoolToken1 ) = _getPairTokens(_pairAddress); if ( _FromTokenContractAddress != _ToSushipoolToken0 && _FromTokenContractAddress != _ToSushipoolToken1 ) { // swap to intermediate (intermediateAmt, intermediateToken) = _fillQuote( _FromTokenContractAddress, _pairAddress, _amount, _swapTarget, swapData ); } else { intermediateToken = _FromTokenContractAddress; intermediateAmt = _amount; } // divide intermediate into appropriate amount to add liquidity (uint256 token0Bought, uint256 token1Bought) = _swapIntermediate( intermediateToken, _ToSushipoolToken0, _ToSushipoolToken1, intermediateAmt ); return _sushiDeposit( _ToSushipoolToken0, _ToSushipoolToken1, token0Bought, token1Bought ); } function _sushiDeposit( address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 token0Bought, uint256 token1Bought ) internal returns (uint256) { IERC20(_ToUnipoolToken0).approve(address(sushiSwapRouter), 0); IERC20(_ToUnipoolToken1).approve(address(sushiSwapRouter), 0); IERC20(_ToUnipoolToken0).approve( address(sushiSwapRouter), token0Bought ); IERC20(_ToUnipoolToken1).approve( address(sushiSwapRouter), token1Bought ); (uint256 amountA, uint256 amountB, uint256 LP) = sushiSwapRouter .addLiquidity( _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought, 1, 1, address(this), deadline ); // returning residue in token0, if any if (token0Bought.sub(amountA) > 0) { IERC20(_ToUnipoolToken0).safeTransfer( msg.sender, token0Bought.sub(amountA) ); } // returning residue in token1, if any if (token1Bought.sub(amountB) > 0) { IERC20(_ToUnipoolToken1).safeTransfer( msg.sender, token1Bought.sub(amountB) ); } return LP; } function _fillQuote( address _fromTokenAddress, address _pairAddress, uint256 _amount, address _swapTarget, bytes memory swapCallData ) internal returns (uint256 amountBought, address intermediateToken) { uint256 valueToSend; if (_fromTokenAddress == address(0)) { valueToSend = _amount; } else { IERC20 fromToken = IERC20(_fromTokenAddress); fromToken.approve(address(_swapTarget), 0); fromToken.approve(address(_swapTarget), _amount); } (address _token0, address _token1) = _getPairTokens(_pairAddress); IERC20 token0 = IERC20(_token0); IERC20 token1 = IERC20(_token1); uint256 initialBalance0 = token0.balanceOf(address(this)); uint256 initialBalance1 = token1.balanceOf(address(this)); (bool success, ) = _swapTarget.call{value: valueToSend}(swapCallData); require(success, 'Error Swapping Tokens 1'); uint256 finalBalance0 = token0.balanceOf(address(this)).sub( initialBalance0 ); uint256 finalBalance1 = token1.balanceOf(address(this)).sub( initialBalance1 ); if (finalBalance0 > finalBalance1) { amountBought = finalBalance0; intermediateToken = _token0; } else { amountBought = finalBalance1; intermediateToken = _token1; } require(amountBought > 0, 'Swapped to Invalid Intermediate'); } function _swapIntermediate( address _toContractAddress, address _ToSushipoolToken0, address _ToSushipoolToken1, uint256 _amount ) internal returns (uint256 token0Bought, uint256 token1Bought) { (address token0, address token1) = _ToSushipoolToken0 < _ToSushipoolToken1 ? (_ToSushipoolToken0, _ToSushipoolToken1) : (_ToSushipoolToken1, _ToSushipoolToken0); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 res0, uint256 res1, ) = pair.getReserves(); if (_toContractAddress == _ToSushipoolToken0) { uint256 amountToSwap = calculateSwapInAmount(res0, _amount); // if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = _amount / 2; token1Bought = _token2Token( _toContractAddress, _ToSushipoolToken1, amountToSwap ); token0Bought = _amount.sub(amountToSwap); } else { uint256 amountToSwap = calculateSwapInAmount(res1, _amount); // if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = _amount / 2; token0Bought = _token2Token( _toContractAddress, _ToSushipoolToken0, amountToSwap ); token1Bought = _amount.sub(amountToSwap); } } function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) internal pure returns (uint256) { return Babylonian .sqrt( reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009)) ) .sub(reserveIn.mul(1997)) / 1994; } /** @notice This function is used to swap ERC20 <> ERC20. @param _FromTokenContractAddress The token address to swap from. @param _ToTokenContractAddress The token address to swap to. @param tokens2Trade The amount of tokens to swap. @return tokenBought The quantity of tokens bought. */ function _token2Token( address _FromTokenContractAddress, address _ToTokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 tokenBought) { if (_FromTokenContractAddress == _ToTokenContractAddress) { return tokens2Trade; } IERC20(_FromTokenContractAddress).approve( address(sushiSwapRouter), 0 ); IERC20(_FromTokenContractAddress).approve( address(sushiSwapRouter), tokens2Trade ); (address token0, address token1) = _FromTokenContractAddress < _ToTokenContractAddress ? (_FromTokenContractAddress, _ToTokenContractAddress) : (_ToTokenContractAddress, _FromTokenContractAddress); address pair = address( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); require(pair != address(0), 'No Swap Available'); address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = _ToTokenContractAddress; tokenBought = sushiSwapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; require(tokenBought > 0, 'Error Swapping Tokens 2'); } function zapOut( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { IERC20(pair).safeTransferFrom(msg.sender, pair, amount); // pull `amount` to `pair` (amount0, amount1) = ISushiLiquidityZap(pair).burn(to); // trigger burn to redeem liquidity for `to` } function zapOutBalance( address pair, address to ) external returns (uint256 amount0, uint256 amount1) { IERC20(pair).safeTransfer(pair, IERC20(pair).balanceOf(address(this))); // transfer local balance to `pair` (amount0, amount1) = ISushiLiquidityZap(pair).burn(to); // trigger burn to redeem liquidity for `to` } } /// @notice Interface for SUSHI MasterChef v2. interface IMasterChefV2 { function lpToken(uint256 pid) external view returns (IERC20); function deposit(uint256 pid, uint256 amount, address to) external; } /// @notice Interface for ETH wrapper contract (v9). interface IWETH { function deposit() external payable; function withdraw(uint wad) external; } /// @notice Contract that batches SUSHI staking and DeFi strategies - V1 'iroirona'. contract InariV1 is BoringBatchableWithDai, Sushiswap_ZapIn_General_V3 { using SafeMath for uint256; using BoringERC20 for IERC20; address governance = msg.sender; // governance role to initialize `masterChefv2` IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI IMasterChefV2 masterChefv2; // SUSHI MasterChef v2 contract ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // ETH wrapper contract (v9) /// @notice Initialize this Inari contract. constructor() public { bento.registerProtocol(); // register this contract with BENTO } /// @notice Helper function to approve this contract to spend tokens and enable strategies. function bridgeToken(IERC20[] calldata token, address[] calldata to) external { for (uint256 i = 0; i < token.length; i++) { token[i].approve(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract } } /// @notice Admin function to set `masterChefv2` and burn `governance` role. function setMasterChefv2(IMasterChefV2 _masterChefv2) external { require(msg.sender == governance, '!governance'); masterChefv2 = _masterChefv2; governance = address(0); // burn role } /********** ETH HELPERS **********/ receive() external payable {} function withdrawETHBalance(address to) external payable { (bool success, ) = to.call{value: address(this).balance}(""); require(success, '!payable'); } /*********** WETH HELPERS ***********/ function depositBalanceToWETH() external payable { IWETH(wETH).deposit{value: address(this).balance}(); } function withdrawBalanceFromWETH(address to) external { uint256 balance = IERC20(wETH).balanceOf(address(this)); IWETH(wETH).withdraw(balance); (bool success, ) = to.call{value: balance}(""); require(success, '!payable'); } /********* TKN HELPER *********/ function withdrawTokenBalance(IERC20 token, address to) external { token.safeTransfer(to, token.balanceOf(address(this))); } /************ SUSHI HELPERS ************/ /// @notice Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`. function stakeSushiBalance(address to) external { ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake local SUSHI into `sushiBar` xSUSHI IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to` } /*********** CHEF HELPERS ***********/ function balanceToMasterChefv2(IERC20 lpToken, uint256 pid, address to) external { masterChefv2.deposit(pid, lpToken.balanceOf(address(this)), to); } /************ KASHI HELPERS ************/ function assetBalanceToKashi(IKashi kashiPair, address to, bool skim) external returns (uint256 fraction) { fraction = kashiPair.addAsset(to, skim, bento.balanceOf(kashiPair.asset(), address(this))); } function assetBalanceFromKashi(address kashiPair, address to) external returns (uint256 share) { share = IKashi(kashiPair).removeAsset(to, IERC20(kashiPair).balanceOf(address(this))); } /* ██ ██ ▄ ▄███▄ █ █ █ █ █ █▀ ▀ █▄▄█ █▄▄█ █ █ ██▄▄ █ █ █ █ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ █ █▐ ▀ ▀ ▐ */ /*********** AAVE HELPERS ***********/ function balanceToAave(address underlying, address to) external { aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0); } function balanceFromAave(address aToken, address to) external { address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, IERC20(aToken).balanceOf(address(this)), to); } /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(this), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /************************* AAVE -> UNDERLYING -> COMP *************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to` } /************************* COMP -> UNDERLYING -> AAVE *************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`. function compoundToAave(address cToken, address to, uint256 amount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying` address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0); // stake resulting `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(address to, uint256 amount) external { // SAAVE sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ███ ▄███▄ ▄ ▄▄▄▄▀ ████▄ █ █ █▀ ▀ █ ▀▀▀ █ █ █ █ ▀ ▄ ██▄▄ ██ █ █ █ █ █ ▄▀ █▄ ▄▀ █ █ █ █ ▀████ ███ ▀███▀ █ █ █ ▀ █ ██ */ /// @notice Liquidity zap into BENTO. function zapToBento( address to, address _FromTokenContractAddress, address _pairAddress, uint256 _amount, uint256 _minPoolTokens, address _swapTarget, bytes calldata swapData ) external payable returns (uint256) { uint256 toInvest = _pullTokens( _FromTokenContractAddress, _amount ); uint256 LPBought = _performZapIn( _FromTokenContractAddress, _pairAddress, toInvest, _swapTarget, swapData ); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); emit ZapIn(to, _pairAddress, LPBought); bento.deposit(IERC20(_pairAddress), address(this), to, LPBought, 0); return LPBought; } /// @notice Liquidity zap from BENTO. function zapFromBento( address pair, address to, uint256 amount ) external returns (uint256 amount0, uint256 amount1) { bento.withdraw(IERC20(pair), msg.sender, pair, amount, 0); // withdraw `amount` to `pair` from BENTO (amount0, amount1) = ISushiLiquidityZap(pair).burn(to); // trigger burn to redeem liquidity for `to` } /************ BENTO HELPERS ************/ function balanceToBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.deposit(token, address(this), to, token.balanceOf(address(this)), 0); } function fromBento(IERC20 token, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.withdraw(token, msg.sender, address(this), amount, 0); } function balanceFromBento(IERC20 token, address to) external returns (uint256 amountOut, uint256 shareOut) { (amountOut, shareOut) = bento.withdraw(token, address(this), to, bento.balanceOf(token, address(this)), 0); } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█ █▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █ █ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █ █▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ ▀███▀ █ █ ▀ █ ▀ ▀ */ // - COMPOUND - // /*********** COMP HELPERS ***********/ function balanceToCompound(ICompoundBridge cToken) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token cToken.mint(underlying.balanceOf(address(this))); } function balanceFromCompound(address cToken) external { ICompoundBridge(cToken).redeem(IERC20(cToken).balanceOf(address(this))); } /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, address to, uint256 cTokenAmount) external returns (uint256 amountOut, uint256 shareOut) { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token (amountOut, shareOut) = bento.deposit(underlying, address(this), to, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(address to, uint256 amount) external { // SCREAM sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(address to, uint256 cTokenAmount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI (amountOut, shareOut) = bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ▄▄▄▄▄ ▄ ▄ ██ █ ▄▄ █ ▀▄ █ █ █ █ █ █ ▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀ ▀▄▄▄▄▀ █ █ █ █ █ █ █ █ █ █ █ ▀ ▀ █ ▀ ▀ */ /// @notice SushiSwap ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`. function inariZushi(address to) external payable returns (uint256 amountOut, uint256 shareOut) { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 out = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(out, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI (amountOut, shareOut) = bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to` } /// @notice SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, ""); } } /// @notice SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).balanceOf(address(this)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, ""); } } }
These are the vulnerabilities found 1) uninitialized-local with Medium impact 2) unused-return with Medium impact 3) delegatecall-loop with High impact 4) arbitrary-send with High impact
// zero tax coin, dont get burned pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > 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: contracts\open-zeppelin-contracts\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts\open-zeppelin-contracts\token\ERC20\ERC20.sol pragma solidity ^0.5.0; /** * @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`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 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 returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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(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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _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 { require(account != address(0), "ERC20: mint to the zero address"); _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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @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, msg.sender, _allowances[account][msg.sender].sub(amount)); } } // File: contracts\ERC20\TokenMintERC20Token.sol pragma solidity ^0.5.0; /** * @title TokenMintERC20Token * @author TokenMint (visit https://tokenmint.io) * * @dev Standard ERC20 token with burning and optional functions implemented. * For full specification of ERC-20 standard see: * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md */ contract Coke is ERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Constructor. * @param name name of the token * @param symbol symbol of the token, 3-4 chars is recommended * @param decimals number of decimal places of one token unit, 18 is widely used * @param totalSupply total supply of tokens in lowest units (depending on decimals) * @param tokenOwnerAddress address that gets 100% of token supply */ constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address tokenOwnerAddress) public payable { _name = name; _symbol = symbol; _decimals = decimals; // set tokenOwnerAddress as owner of all tokens _mint(tokenOwnerAddress, totalSupply); } /** * @dev Burns a specific amount of tokens. * @param value The amount of lowest token units to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } // optional functions from ERC20 stardard /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; library Date { struct _Date { uint16 year; uint8 month; uint8 day; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_Date memory dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); return timestamp; } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner || tx.origin == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); 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 div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } } contract StakingPool is Ownable { using SafeMath for uint256; IERC20 token; uint256 decimals = 18; uint256 minimumStakeAmount = 1000; address ZERO_ADDRESS = 0x0000000000000000000000000000000000000000; address BURN_ADDRESS; //Stats uint256 public totalStakes = 0; uint256 public totalStaked = 0; uint256 public adminCanWithdraw = 0; mapping(uint8 => uint256) public totalByLockup; uint256 public totalCompounding = 0; uint256 public totalNotCompounding = 0; struct Stake { bool exists; uint256 createdOn; uint256 initialAmount; bool compound; uint8 lockupPeriod; uint256 withdrawn; address referrer; } mapping(address => Stake) public stakes; uint256 DEFAULT_ROI1 = 13; //0.13% daily ROI, equivalent to 4% monthly uint256 DEFAULT_ROI2 = 15; //0.15% daily ROI uint256 DEFAULT_ROI3 = 17; //0.17% daily ROI uint256 DEFAULT_ROI6 = 19; //0.19% daily ROI bool isValidLockup1 = true; bool isValidLockup2 = false; bool isValidLockup3 = false; bool isValidLockup6 = false; struct ROI { bool exists; uint256 roi1; uint256 roi2; uint256 roi3; uint256 roi6; } //Year to Month to ROI mapping (uint256 => mapping (uint256 => ROI)) private rois; event NewStake(address indexed staker, uint256 totalStaked, uint8 lockupPeriod, bool compound, address referrer); event StakeIncreasedForReferral(address indexed staker, uint256 initialAmount, uint256 delta); event RewardsWithdrawn(address indexed staker, uint256 total); event StakeFinished(address indexed staker, uint256 totalReturned, uint256 totalDeducted); event TokensBurnt(address indexed staker, uint256 totalBurnt); constructor(IERC20 _token, address _burnAddress) public { token = _token; BURN_ADDRESS = _burnAddress; } function createStake(uint256 _amount, uint8 _lockupPeriod, bool _compound, address _referrer) public { require(!stakes[msg.sender].exists, "You already have a stake"); require(_isValidLockupPeriod(_lockupPeriod), "Invalid lockup period"); require(_amount >= getMinimumStakeAmount(), "Invalid minimum"); require(IERC20(token).transferFrom(msg.sender, address(this), calculateTotalWithDecimals(_amount)), "Couldn't take the tokens"); if (_referrer != address(0) && stakes[_referrer].exists) { uint256 amountToIncrease = stakes[_referrer].initialAmount.mul(1).div(100); emit StakeIncreasedForReferral(_referrer, stakes[_referrer].initialAmount, amountToIncrease); stakes[_referrer].initialAmount += amountToIncrease; totalStaked = totalStaked.add(amountToIncrease); } else { _referrer = ZERO_ADDRESS; } Stake memory stake = Stake({exists:true, createdOn: now, initialAmount:_amount, compound:_compound, lockupPeriod:_lockupPeriod, withdrawn:0, referrer:_referrer }); stakes[msg.sender] = stake; totalStakes = totalStakes.add(1); totalStaked = totalStaked.add(_amount); totalByLockup[_lockupPeriod] += 1; if (_compound) { totalCompounding = totalCompounding.add(1); } else { totalNotCompounding = totalNotCompounding.add(1); } emit NewStake(msg.sender, _amount, _lockupPeriod, _compound, _referrer); } function withdraw() public { require(stakes[msg.sender].exists, "Invalid stake"); require(!stakes[msg.sender].compound, "Compounders can't withdraw before they finish their stake"); Stake storage stake = stakes[msg.sender]; uint256 total = getPartialToWidthdrawForNotCompounders(msg.sender, now); stake.withdrawn += total; require(token.transfer(msg.sender, calculateTotalWithDecimals(total)), "Couldn't withdraw"); emit RewardsWithdrawn(msg.sender, total); } function finishStake() public { require(stakes[msg.sender].exists, "Invalid stake"); Stake memory stake = stakes[msg.sender]; uint256 finishesOn = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod); require(now > finishesOn || !stake.compound, "Can't be finished yet"); uint256 totalRewards; uint256 totalFees; uint256 totalPenalty; if (stake.compound) { totalRewards = getTotalToWidthdrawForCompounders(msg.sender); //This includes the initial amount totalRewards = totalRewards.sub(stake.initialAmount); totalFees = totalRewards.mul(5).div(100); //Flat fee of 5% } else { if (now > finishesOn) { totalRewards = getTotalToWidthdrawForNotCompounders(msg.sender); } else { totalRewards = getPartialToWidthdrawForNotCompounders(msg.sender, now); //As it didn't finish, pay a fee of 10% (before first half) or 5% (after first half) uint8 penalty = _isFirstHalf(stake.createdOn, stake.lockupPeriod) ? 10 : 5; totalPenalty = totalRewards.mul(penalty).div(100); } totalFees = totalRewards.mul(2).div(100); //Flat fee of 2% } uint256 totalToDeduct = totalFees.add(totalPenalty); uint256 totalToTransfer = totalRewards.add(stake.initialAmount).sub(totalToDeduct); //10% of the fees are for the Admin. adminCanWithdraw = adminCanWithdraw.add(totalToDeduct.div(10)); //The rest are burnt uint256 totalToBurn = totalToDeduct.mul(9).div(10); require(token.transfer(BURN_ADDRESS, calculateTotalWithDecimals(totalToBurn)), "Couldn't burn the tokens"); emit TokensBurnt(msg.sender, totalToBurn); totalStakes = totalStakes.sub(1); totalStaked = totalStaked.sub(stake.initialAmount); totalByLockup[stake.lockupPeriod] = totalByLockup[stake.lockupPeriod].sub(1); if (stake.compound) { totalCompounding = totalCompounding.sub(1); } else { totalNotCompounding = totalNotCompounding.sub(1); } delete stakes[msg.sender]; require(token.transfer(msg.sender, calculateTotalWithDecimals(totalToTransfer)), "Couldn't transfer the tokens"); emit StakeFinished(msg.sender, totalToTransfer, totalToDeduct); } function calculateTotalWithDecimals(uint256 _amount) internal view returns (uint256) { return _amount * 10 ** decimals; } function _isFirstHalf(uint256 _createdOn, uint8 _lockupPeriod) internal view returns (bool) { uint256 day = 60 * 60 * 24; if (_lockupPeriod == 1) { return _createdOn + day.mul(15) > now; } if (_lockupPeriod == 2) { return _createdOn + day.mul(30) > now; } if (_lockupPeriod == 3) { return _createdOn + day.mul(45) > now; } return _createdOn + day.mul(90) > now; } function calcPartialRewardsForInitialMonth(Stake memory stake, uint8 _todayDay, Date._Date memory _initial, bool compounding) internal view returns (uint256) { uint256 roi = getRoi(_initial.month, _initial.year, stake.lockupPeriod); uint8 totalDays = _todayDay - _initial.day; return calculateRewards(stake.initialAmount, totalDays, roi, compounding); } function calcFullRewardsForInitialMonth(Stake memory stake, Date._Date memory _initial, bool compounding) internal view returns (uint256) { uint8 totalDays = Date.getDaysInMonth(_initial.month, _initial.year); uint256 roi = getRoi(_initial.month, _initial.year, stake.lockupPeriod); uint8 countDays = totalDays - _initial.day; return calculateRewards(stake.initialAmount, countDays, roi, compounding); } function calcFullRewardsForMonth(uint256 _currentTotal, uint256 _roi, uint16 _year, uint8 _month, bool compounding) internal pure returns (uint256) { uint256 totalDays = Date.getDaysInMonth(_month, _year); return calculateRewards(_currentTotal, totalDays, _roi, compounding); } function calculateRewards(uint256 currentTotal, uint256 totalDays, uint256 roi, bool compounding) internal pure returns (uint256) { if (compounding) { uint256 divFactor = 10000 ** 10; while(totalDays > 10) { currentTotal = currentTotal.mul(roi.add(10000) ** 10).div(divFactor); totalDays -= 10; } return currentTotal = currentTotal.mul(roi.add(10000) ** totalDays).div(10000 ** totalDays); } //Not compounding return currentTotal.mul(totalDays).mul(roi).div(10000); } //This function is meant to be called internally when finishing your stake function getTotalToWidthdrawForNotCompounders(address _account) internal view returns (uint256) { Stake memory stake = stakes[_account]; Date._Date memory initial = Date.parseTimestamp(stake.createdOn); uint256 total = calcFullRewardsForInitialMonth(stake, initial, false); uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod); Date._Date memory finishes = Date.parseTimestamp(finishTimestamp); for(uint8 i=1;i<=stake.lockupPeriod;i++) { uint8 currentMonth = initial.month + i; uint16 currentYear = initial.year; if (currentMonth > 12) { currentYear += 1; currentMonth = currentMonth % 12; } uint256 roi = getRoi(currentMonth, currentYear ,stake.lockupPeriod); //This is the month it finishes on if (currentMonth == finishes.month) { //Calculates partial rewards for month total += calculateRewards(stake.initialAmount, finishes.day, roi, false); break; } //This is a complete month I need to add total += calcFullRewardsForMonth(stake.initialAmount, roi, currentYear, currentMonth, false); } total = total.sub(stake.withdrawn); return total; } //This function is meant to be called internally when withdrawing as much as you can, or by the UI function getPartialToWidthdrawForNotCompounders(address _account, uint256 _now) public view returns (uint256) { Stake memory stake = stakes[_account]; Date._Date memory initial = Date.parseTimestamp(stake.createdOn); Date._Date memory today = Date.parseTimestamp(_now); //I am still in my first month of staking if (initial.month == today.month) { uint256 total = calcPartialRewardsForInitialMonth(stake, today.day, initial, false); total = total.sub(stake.withdrawn); return total; } //I am in a month after my first month of staking uint256 total = calcFullRewardsForInitialMonth(stake, initial, false); uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod); Date._Date memory finishes = Date.parseTimestamp(finishTimestamp); for(uint8 i=1;i<=stake.lockupPeriod;i++) { uint8 currentMonth = initial.month + i; uint16 currentYear = initial.year; if (currentMonth > 12) { currentYear += 1; currentMonth = currentMonth % 12; } uint256 roi = getRoi(currentMonth, currentYear, stake.lockupPeriod); //This is the month it finishes if (currentMonth == finishes.month) { uint8 upToDay = _getMin(finishes.day, today.day); //Calculates partial rewards for month total += calculateRewards(stake.initialAmount, upToDay, roi, false); break; } else if (currentMonth == today.month) { // We reached the current month //Calculates partial rewards for month total += calculateRewards(stake.initialAmount, today.day, roi, false); break; } //This is a complete month I need to add total += calcFullRewardsForMonth(stake.initialAmount, roi, currentYear, currentMonth, false); } total = total.sub(stake.withdrawn); return total; } //This function is meant to be called internally on finishing your stake function getTotalToWidthdrawForCompounders(address _account) internal view returns (uint256) { Stake memory stake = stakes[_account]; Date._Date memory initial = Date.parseTimestamp(stake.createdOn); uint256 total = calcFullRewardsForInitialMonth(stake, initial, true); uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod); Date._Date memory finishes = Date.parseTimestamp(finishTimestamp); for(uint8 i=1;i<=stake.lockupPeriod;i++) { uint8 currentMonth = initial.month + i; uint16 currentYear = initial.year; if (currentMonth > 12) { currentYear += 1; currentMonth = currentMonth % 12; } uint256 roi = getRoi(currentMonth, currentYear, stake.lockupPeriod); //This is the month it finishes on if (currentMonth == finishes.month) { //Calculates partial rewards for month return calculateRewards(total, finishes.day, roi, true); } //This is a complete month I need to add total = calcFullRewardsForMonth(total, roi, currentYear, currentMonth, true); } } //This function is meant to be called from the UI function getPartialRewardsForCompounders(address _account, uint256 _now) public view returns (uint256) { Stake memory stake = stakes[_account]; Date._Date memory initial = Date.parseTimestamp(stake.createdOn); Date._Date memory today = Date.parseTimestamp(_now); //I am still in my first month of staking if (initial.month == today.month) { uint256 total = calcPartialRewardsForInitialMonth(stake, today.day, initial, true); total = total.sub(stake.withdrawn); return total; } //I am in a month after my first month of staking uint256 total = calcFullRewardsForInitialMonth(stake, initial, true); uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod); Date._Date memory finishes = Date.parseTimestamp(finishTimestamp); for(uint8 i=1;i<=stake.lockupPeriod;i++) { uint8 currentMonth = initial.month + i; uint16 currentYear = initial.year; if (currentMonth > 12) { currentYear += 1; currentMonth = currentMonth % 12; } uint256 roi = getRoi(currentMonth, currentYear, stake.lockupPeriod); //This is the month it finishes if (currentMonth == finishes.month) { uint8 upToDay = _getMin(finishes.day, today.day); //Calculates partial rewards for month return calculateRewards(total, upToDay, roi, true); } else if (currentMonth == today.month) { // We reached the current month //Calculates partial rewards for month return calculateRewards(total, today.day, roi, true); } //This is a complete month I need to add total = calcFullRewardsForMonth(total, roi, currentYear, currentMonth, true); } } function _getMin(uint8 num1, uint8 num2) internal pure returns (uint8) { if (num1 < num2) { return num1; } return num2; } function calculateFinishTimestamp(address account) public view returns (uint256) { return _calculateFinishTimestamp(stakes[account].createdOn, stakes[account].lockupPeriod); } function _calculateFinishTimestamp(uint256 _timestamp, uint8 _lockupPeriod) internal pure returns (uint256) { uint16 year = Date.getYear(_timestamp); uint8 month = Date.getMonth(_timestamp); month += _lockupPeriod; if (month > 12) { year += 1; month = month % 12; } uint8 day = Date.getDay(_timestamp); return Date.toTimestamp(year, month, day); } function _isValidLockupPeriod(uint8 n) public view returns (bool) { return (isValidLockup1 && n == 1) || (isValidLockup2 && n == 2) || (isValidLockup3 && n == 3) || (isValidLockup6 && n == 6); } function _setValidLockups(bool _isValidLockup1, bool _isValidLockup2, bool _isValidLockup3, bool _isValidLockup6) public onlyOwner { isValidLockup1 = _isValidLockup1; isValidLockup2 = _isValidLockup2; isValidLockup3 = _isValidLockup3; isValidLockup6 = _isValidLockup6; } function _adminWithdraw() public onlyOwner { uint256 amount = adminCanWithdraw; adminCanWithdraw = 0; require(token.transfer(msg.sender, calculateTotalWithDecimals(amount)), "Couldn't withdraw"); } function _extractDESTSentByMistake(uint256 amount, address _sendTo) public onlyOwner { require(token.transfer(_sendTo, amount)); } function _setMinimumStakeAmount(uint256 _minimumStakeAmount) public onlyOwner { minimumStakeAmount = _minimumStakeAmount; } function getMinimumStakeAmount() public view returns (uint256) { return minimumStakeAmount; } function _setRoi(uint256 _month, uint256 _year, uint256 _roi1, uint256 _roi2, uint256 _roi3, uint256 _roi6) public onlyOwner { uint256 today_year = Date.getYear(now); uint256 today_month = Date.getMonth(now); require((_month >= today_month && _year == today_year) || _year > today_year, "You can only set it for this month or a future month"); rois[_year][_month].exists = true; rois[_year][_month].roi1 = _roi1; rois[_year][_month].roi2 = _roi2; rois[_year][_month].roi3 = _roi3; rois[_year][_month].roi6 = _roi6; } function _setDefaultRoi(uint256 _roi1, uint256 _roi2, uint256 _roi3, uint256 _roi6) public onlyOwner { DEFAULT_ROI1 = _roi1; DEFAULT_ROI2 = _roi2; DEFAULT_ROI3 = _roi3; DEFAULT_ROI6 = _roi6; } function getRoi(uint256 month, uint256 year, uint8 lockupPeriod) public view returns (uint256) { if (rois[year][month].exists) { if (lockupPeriod == 1) { return rois[year][month].roi1; } else if (lockupPeriod == 2) { return rois[year][month].roi2; } else if (lockupPeriod == 3) { return rois[year][month].roi3; } else if (lockupPeriod == 6) { return rois[year][month].roi6; } } if (lockupPeriod == 1) { return DEFAULT_ROI1; } else if (lockupPeriod == 2) { return DEFAULT_ROI2; } else if (lockupPeriod == 3) { return DEFAULT_ROI3; } else if (lockupPeriod == 6) { return DEFAULT_ROI6; } return 0; } }
These are the vulnerabilities found 1) divide-before-multiply with Medium impact 2) reentrancy-no-eth with Medium impact 3) incorrect-equality with Medium impact 4) uninitialized-local with Medium impact 5) weak-prng with High impact
// File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; } // File: contracts/uniswapv2/libraries/SafeMath.sol pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathUniswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // File: contracts/uniswapv2/UniswapV2ERC20.sol pragma solidity =0.6.12; contract UniswapV2ERC20 { using SafeMathUniswap for uint; string public constant name = 'SushiSwap LP Token'; string public constant symbol = 'SLP'; 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, 'UniswapV2: 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, 'UniswapV2: INVALID_SIGNATURE'); _approve(owner, spender, value); } } // File: contracts/uniswapv2/libraries/Math.sol pragma solidity =0.6.12; // a library for performing various math operations library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/uniswapv2/libraries/UQ112x112.sol pragma solidity =0.6.12; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // File: contracts/uniswapv2/interfaces/IERC20.sol pragma solidity >=0.5.0; interface IERC20Uniswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } // File: contracts/uniswapv2/interfaces/IUniswapV2Callee.sol pragma solidity >=0.5.0; interface IUniswapV2Callee { function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; } // File: contracts/uniswapv2/UniswapV2Pair.sol pragma solidity =0.6.12; interface IMigrator { // Return the desired amount of liquidity token that the migrator wants. function desiredLiquidity() external view returns (uint256); } contract UniswapV2Pair is UniswapV2ERC20 { using SafeMathUniswap 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, 'UniswapV2: 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))), 'UniswapV2: 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, 'UniswapV2: 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), 'UniswapV2: 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 = IUniswapV2Factory(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(5).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 = IERC20Uniswap(token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(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) { address migrator = IUniswapV2Factory(factory).migrator(); if (msg.sender == migrator) { liquidity = IMigrator(migrator).desiredLiquidity(); require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); } else { require(migrator == address(0), "Must not have migrator"); 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, 'UniswapV2: 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 = IERC20Uniswap(_token0).balanceOf(address(this)); uint balance1 = IERC20Uniswap(_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, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_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, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: 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, 'UniswapV2: 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) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); balance1 = IERC20Uniswap(_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, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: 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, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external lock { _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1); } }
These are the vulnerabilities found 1) weak-prng with High impact 2) reentrancy-no-eth with Medium impact 3) incorrect-equality with Medium impact
pragma solidity ^0.4.22; contract Game35 { struct GameInfo { uint funderNum; mapping(uint => address) funder; mapping(uint => address) winner; } GameInfo[] public games; uint public gameNum = 0; mapping(address => uint) public lastGame; mapping(address => uint) public funderBalance; mapping(address => address) public referrer; address public manager; uint count = 10000000000000000 * 5; constructor() public { manager = msg.sender; referrer[manager] = manager; games.push(GameInfo(0)); } function addIn(address referr) public payable returns (bool){ require( msg.value == 100 * count, "ETH count is wrong!" ); if(lastGame[msg.sender] == 0){ if(referr == msg.sender){ referrer[msg.sender] = manager; } else { referrer[msg.sender] = referr; } } games[gameNum].funder[games[gameNum].funderNum] = msg.sender; games[gameNum].funderNum += 1; lastGame[msg.sender] = gameNum; if (games[gameNum].funderNum == 3) { uint winNum = (now + gameNum)%3; games[gameNum].winner[0] = games[gameNum].funder[winNum]; funderBalance[games[gameNum].winner[0]] += 285 * count; funderBalance[manager] += 3 * count; for(uint8 i=0;i<3;i++){ address addr = referrer[games[gameNum].funder[i]]; funderBalance[addr] += count; funderBalance[referrer[addr]] += count; funderBalance[referrer[referrer[addr]]] += count / 2; funderBalance[referrer[referrer[referrer[addr]]]] += count / 2; funderBalance[referrer[referrer[referrer[referrer[addr]]]]] += count / 2; funderBalance[referrer[referrer[referrer[referrer[referrer[addr]]]]]] += count / 2; } gameNum += 1; games.push(GameInfo(0)); } return true; } function withdraw(uint amount) public { require( funderBalance[msg.sender] >= amount, "ETH Out of balance!" ); funderBalance[msg.sender] += -amount; msg.sender.transfer(amount); } function getLastGame() public view returns (uint last, uint num, uint balance, address winer){ last = lastGame[msg.sender]; GameInfo storage game = games[lastGame[msg.sender]]; num = game.funderNum; if(game.funderNum == 3){ winer = game.winner[0]; } balance = funderBalance[msg.sender]; } function getNewGame() public view returns (uint last, uint num, address winer){ last = gameNum; GameInfo storage game = games[gameNum]; num = game.funderNum; if(game.funderNum == 3){ winer = game.winner[0]; } } }
These are the vulnerabilities found 1) weak-prng with High impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'StarshipInu' token contract // // Deployed to : 0xA37894698979F943f326C3598bf448A4E71fC03A // Symbol : SSINU // Name : StarshipInu // Total supply: 1000000000000000 // Decimals : 18 // Micro low cap Token // Beyond Universe for many x´s // https://t.me/StarshipInu // (c) Development SF/CALIFORNIA SpaxeX coding intern/We take this challenge from our CEO EM // www.starshipinu.com // ---------------------------------------------------------------------------- // _|_|_| _|_|_|_|_| _|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_| _|_|_| _| _| _| _| // _| _| _| _| _| _| _| _| _| _| _| _| _| _|_| _| _| _| // _|_| _| _|_|_|_| _|_|_| _|_| _|_|_|_| _| _|_|_| _| _| _| _| _| _| // _| _| _| _| _| _| _| _| _| _| _| _| _| _|_| _| _| // _|_|_| _| _| _| _| _| _|_|_| _| _| _|_|_| _| _|_|_| _| _| _|_| // // // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract StarshipInu is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function StarshipInu() public { symbol = "SSINU"; name = "StarshipInu"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[0xA37894698979F943f326C3598bf448A4E71fC03A] = _totalSupply; Transfer(address(0), 0xA37894698979F943f326C3598bf448A4E71fC03A, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.11; contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract ERC721 { function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); } contract GeneScienceInterface { function isGeneScience() public pure returns (bool); function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } contract NinjaAccessControl { event ContractUpgrade(address newContract); address public ceoAddress; address public cfoAddress; address public cooAddress; bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() external onlyCLevel whenNotPaused { paused = true; } function unpause() public onlyCEO whenPaused { paused = false; } } contract NinjaBase is NinjaAccessControl { event Birth( address owner, uint256 ninjaId, uint256 matronId, uint256 sireId, uint256 genes, uint256 birthTime ); event Transfer(address from, address to, uint256 tokenId); struct Ninja { uint256 genes; uint64 birthTime; uint64 cooldownEndBlock; uint32 matronId; uint32 sireId; uint32 siringWithId; uint16 cooldownIndex; uint16 generation; } uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; uint256 public secondsPerBlock = 15; Ninja[] ninjas; mapping (uint256 => address) public ninjaIndexToOwner; mapping (address => uint256) ownershipTokenCount; mapping (uint256 => address) public ninjaIndexToApproved; mapping (uint256 => address) public sireAllowedToAddress; uint32 public destroyedNinjas; SaleClockAuction public saleAuction; SiringClockAuction public siringAuction; function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_to == address(0)) { delete ninjaIndexToOwner[_tokenId]; } else { ownershipTokenCount[_to]++; ninjaIndexToOwner[_tokenId] = _to; } if (_from != address(0)) { ownershipTokenCount[_from]--; delete sireAllowedToAddress[_tokenId]; delete ninjaIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } function _createNinja( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Ninja memory _ninja = Ninja({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newNinjaId = ninjas.push(_ninja) - 1; require(newNinjaId == uint256(uint32(newNinjaId))); Birth( _owner, newNinjaId, uint256(_ninja.matronId), uint256(_ninja.sireId), _ninja.genes, uint256(_ninja.birthTime) ); _transfer(0, _owner, newNinjaId); return newNinjaId; } function _destroyNinja(uint256 _ninjaId) internal { require(_ninjaId > 0); address from = ninjaIndexToOwner[_ninjaId]; require(from != address(0)); destroyedNinjas++; _transfer(from, 0, _ninjaId); } function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } contract NinjaExtension is NinjaBase { event Lock(uint256 ninjaId, uint16 mask); mapping (address => bool) extensions; mapping (uint256 => uint16) locks; uint16 constant LOCK_BREEDING = 1; uint16 constant LOCK_TRANSFER = 2; uint16 constant LOCK_ALL = LOCK_BREEDING | LOCK_TRANSFER; function addExtension(address _contract) external onlyCEO { extensions[_contract] = true; } function removeExtension(address _contract) external onlyCEO { delete extensions[_contract]; } modifier onlyExtension() { require(extensions[msg.sender] == true); _; } function extCreateNinja( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) public onlyExtension returns (uint) { return _createNinja(_matronId, _sireId, _generation, _genes, _owner); } function extDestroyNinja(uint256 _ninjaId) public onlyExtension { require(locks[_ninjaId] == 0); _destroyNinja(_ninjaId); } function extLockNinja(uint256 _ninjaId, uint16 _mask) public onlyExtension { _lockNinja(_ninjaId, _mask); } function _lockNinja(uint256 _ninjaId, uint16 _mask) internal { require(_mask > 0); uint16 mask = locks[_ninjaId]; require(mask & _mask == 0); if (_mask & LOCK_BREEDING > 0) { Ninja storage ninja = ninjas[_ninjaId]; require(ninja.siringWithId == 0); } if (_mask & LOCK_TRANSFER > 0) { address owner = ninjaIndexToOwner[_ninjaId]; require(owner != address(saleAuction)); require(owner != address(siringAuction)); } mask |= _mask; locks[_ninjaId] = mask; Lock(_ninjaId, mask); } function extUnlockNinja(uint256 _ninjaId, uint16 _mask) public onlyExtension returns (uint16) { _unlockNinja(_ninjaId, _mask); } function _unlockNinja(uint256 _ninjaId, uint16 _mask) internal { require(_mask > 0); uint16 mask = locks[_ninjaId]; require(mask & _mask == _mask); mask ^= _mask; locks[_ninjaId] = mask; Lock(_ninjaId, mask); } function extGetLock(uint256 _ninjaId) public view onlyExtension returns (uint16) { return locks[_ninjaId]; } } contract NinjaOwnership is NinjaExtension, ERC721 { string public constant name = "CryptoNinjas"; string public constant symbol = "CBT"; function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ninjaIndexToOwner[_tokenId] == _claimant; } function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ninjaIndexToApproved[_tokenId] == _claimant; } function _approve(uint256 _tokenId, address _approved) internal { ninjaIndexToApproved[_tokenId] = _approved; } function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } function transfer( address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleAuction)); require(_to != address(siringAuction)); require(_owns(msg.sender, _tokenId)); require(locks[_tokenId] & LOCK_TRANSFER == 0); _transfer(msg.sender, _to, _tokenId); } function approve( address _to, uint256 _tokenId ) external whenNotPaused { require(_owns(msg.sender, _tokenId)); require(locks[_tokenId] & LOCK_TRANSFER == 0); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(locks[_tokenId] & LOCK_TRANSFER == 0); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return ninjas.length - destroyedNinjas; } function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ninjaIndexToOwner[_tokenId]; require(owner != address(0)); } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalNinjas = ninjas.length - 1; uint256 resultIndex = 0; uint256 ninjaId; for (ninjaId = 0; ninjaId <= totalNinjas; ninjaId++) { if (ninjaIndexToOwner[ninjaId] == _owner) { result[resultIndex] = ninjaId; resultIndex++; } } return result; } } } contract NinjaBreeding is NinjaOwnership { event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); uint256 public autoBirthFee = 2 finney; uint256 public pregnantNinjas; GeneScienceInterface public geneScience; function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); require(candidateContract.isGeneScience()); geneScience = candidateContract; } function _isReadyToBreed(uint256 _ninjaId, Ninja _ninja) internal view returns (bool) { return (_ninja.siringWithId == 0) && (_ninja.cooldownEndBlock <= uint64(block.number)) && (locks[_ninjaId] & LOCK_BREEDING == 0); } function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = ninjaIndexToOwner[_matronId]; address sireOwner = ninjaIndexToOwner[_sireId]; return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } function _triggerCooldown(Ninja storage _ninja) internal { _ninja.cooldownEndBlock = uint64((cooldowns[_ninja.cooldownIndex]/secondsPerBlock) + block.number); if (_ninja.cooldownIndex < 13) { _ninja.cooldownIndex += 1; } } function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } function _isReadyToGiveBirth(Ninja _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } function isReadyToBreed(uint256 _ninjaId) public view returns (bool) { Ninja storage ninja = ninjas[_ninjaId]; return _ninjaId > 0 && _isReadyToBreed(_ninjaId, ninja); } function isPregnant(uint256 _ninjaId) public view returns (bool) { return _ninjaId > 0 && ninjas[_ninjaId].siringWithId != 0; } function _isValidMatingPair( Ninja storage _matron, uint256 _matronId, Ninja storage _sire, uint256 _sireId ) private view returns(bool) { if (_matronId == _sireId) { return false; } if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } return true; } function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Ninja storage matron = ninjas[_matronId]; Ninja storage sire = ninjas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Ninja storage matron = ninjas[_matronId]; Ninja storage sire = ninjas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } function _breedWith(uint256 _matronId, uint256 _sireId) internal { Ninja storage sire = ninjas[_sireId]; Ninja storage matron = ninjas[_matronId]; matron.siringWithId = uint32(_sireId); _triggerCooldown(sire); _triggerCooldown(matron); delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; pregnantNinjas++; Pregnant(ninjaIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { require(msg.value >= autoBirthFee); require(_owns(msg.sender, _matronId)); require(_isSiringPermitted(_sireId, _matronId)); Ninja storage matron = ninjas[_matronId]; require(_isReadyToBreed(_matronId, matron)); Ninja storage sire = ninjas[_sireId]; require(_isReadyToBreed(_sireId, sire)); require(_isValidMatingPair( matron, _matronId, sire, _sireId )); _breedWith(_matronId, _sireId); } function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { Ninja storage matron = ninjas[_matronId]; require(matron.birthTime != 0); require(_isReadyToGiveBirth(matron)); uint256 sireId = matron.siringWithId; Ninja storage sire = ninjas[sireId]; uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); address owner = ninjaIndexToOwner[_matronId]; uint256 ninjaId = _createNinja(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); delete matron.siringWithId; pregnantNinjas--; msg.sender.send(autoBirthFee); return ninjaId; } } contract ClockAuctionBase { struct Auction { address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } ERC721 public nonFungibleContract; uint256 public ownerCut; mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated( address seller, uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 creationTime, uint256 duration ); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address seller, address winner, uint256 time); event AuctionCancelled(uint256 tokenId, address seller, uint256 time); function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, this, _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( _auction.seller, uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.startedAt), uint256(_auction.duration) ); } function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId, _seller, uint256(now)); } function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); AuctionSuccessful(_tokenId, price, seller, msg.sender, uint256(now)); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { return _price * ownerCut / 10000; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract ClockAuction is Pausable, ClockAuctionBase { function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); nonFungibleContract = candidateContract; } function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); bool res = nftAddress.send(this.balance); } function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable whenNotPaused { _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } contract SiringClockAuction is ClockAuction { bool public isSiringClockAuction = true; function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value); _transfer(seller, _tokenId); } } contract SaleClockAuction is ClockAuction { bool public isSaleClockAuction = true; uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); if (seller == address(nonFungibleContract)) { lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } contract NinjaAuction is NinjaBreeding { function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); require(candidateContract.isSiringClockAuction()); siringAuction = candidateContract; } function createSaleAuction( uint256 _ninjaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _ninjaId)); require(!isPregnant(_ninjaId)); _approve(_ninjaId, saleAuction); saleAuction.createAuction( _ninjaId, _startingPrice, _endingPrice, _duration, msg.sender ); } function createSiringAuction( uint256 _ninjaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _ninjaId)); require(isReadyToBreed(_ninjaId)); _approve(_ninjaId, siringAuction); siringAuction.createAuction( _ninjaId, _startingPrice, _endingPrice, _duration, msg.sender ); } function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } contract NinjaMinting is NinjaAuction { uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; uint256 public promoCreatedCount; uint256 public gen0CreatedCount; function createPromoNinja(uint256 _genes, address _owner) external onlyCOO { address ninjaOwner = _owner; if (ninjaOwner == address(0)) { ninjaOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createNinja(0, 0, 0, _genes, ninjaOwner); } function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 ninjaId = _createNinja(0, 0, 0, _genes, address(this)); _approve(ninjaId, saleAuction); saleAuction.createAuction( ninjaId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } contract NinjaCore is NinjaMinting { address public newContractAddress; function NinjaCore() public { paused = true; ceoAddress = msg.sender; cooAddress = msg.sender; _createNinja(0, 0, 0, uint256(-1), msg.sender); } function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } function getNinja(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { require(ninjaIndexToOwner[_id] != address(0)); Ninja storage ninja = ninjas[_id]; isGestating = (ninja.siringWithId != 0); isReady = (ninja.cooldownEndBlock <= block.number); cooldownIndex = uint256(ninja.cooldownIndex); nextActionAt = uint256(ninja.cooldownEndBlock); siringWithId = uint256(ninja.siringWithId); birthTime = uint256(ninja.birthTime); matronId = uint256(ninja.matronId); sireId = uint256(ninja.sireId); generation = uint256(ninja.generation); genes = ninja.genes; } function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); super.unpause(); } function withdrawBalance() external onlyCFO { uint256 balance = this.balance; uint256 subtractFees = (pregnantNinjas + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } function destroyNinja(uint256 _ninjaId) external onlyCEO { require(locks[_ninjaId] == 0); _destroyNinja(_ninjaId); } }
These are the vulnerabilities found 1) reentrancy-no-eth with Medium impact 2) unchecked-send with Medium impact 3) arbitrary-send with High impact 4) incorrect-equality with Medium impact 5) reentrancy-eth with High impact
pragma solidity ^0.4.16; // ---------------------------------------------------------------------------- // contract WhiteListAccess // ---------------------------------------------------------------------------- contract WhiteListAccess { function WhiteListAccess() public { owner = msg.sender; whitelist[owner] = true; whitelist[address(this)] = true; } address public owner; mapping (address => bool) whitelist; modifier onlyOwner {require(msg.sender == owner); _;} modifier onlyWhitelisted {require(whitelist[msg.sender]); _;} function addToWhiteList(address trusted) public onlyOwner() { whitelist[trusted] = true; } function removeFromWhiteList(address untrusted) public onlyOwner() { whitelist[untrusted] = false; } } // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // CNT_Common contract // ---------------------------------------------------------------------------- contract CNT_Common is WhiteListAccess { string public name; function CNT_Common() public { } // Deployment address public SALE_address; // CNT_Crowdsale } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract Token is ERC20Interface, CNT_Common { using SafeMath for uint; bool public freezed; bool public initialized; uint8 public decimals; uint public totSupply; string public symbol; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Token(uint8 _decimals, uint _millions, string _name, string _sym) public { owner = msg.sender; symbol = _sym; name = _name; decimals = _decimals; totSupply = _millions * 10**6 * 10**uint(decimals); balances[owner] = totSupply; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totSupply - balances[SALE_address]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(!freezed); require(initialized); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function desapprove(address spender) public returns (bool success) { allowed[msg.sender][spender] = 0; return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(!freezed); require(initialized); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // function init(address _sale) public { require(!initialized); // we need to know the CNTTokenSale and NewRichOnTheBlock Contract address before distribute to them SALE_address = _sale; balances[SALE_address] = totSupply; balances[address(this)] = 0; balances[owner] = 0; whitelist[SALE_address] = true; initialized = true; freezed = true; } function ico_distribution(address to, uint tokens) public onlyWhitelisted() { require(initialized); balances[SALE_address] = balances[SALE_address].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(SALE_address, to, tokens); } function balanceOfMine() public returns (uint) { return balances[msg.sender]; } function rename(string _name) public onlyOwner() { name = _name; } function unfreeze() public onlyOwner() { freezed = false; } function refreeze() public onlyOwner() { freezed = true; } } contract CNT_Token is Token(18, 300, "Chip", "CNT") { function CNT_Token() public {} } contract BGB_Token is Token(18, 300, "BG-Coin", "BGB") { function BGB_Token() public {} } contract VPE_Token is Token(18, 100, "Vapaee", "VPE") { function VPE_Token() public {} } contract GVPE_Token is Token(18, 1, "Golden Vapaee", "GVPE") { function GVPE_Token() public {} } contract EOS is Token(18, 1000, "EOS Dummie", "EOS") { function EOS() public {} }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity 0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { /// Total amount of tokens uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _amount) public returns (bool success); 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 remaining); function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success); function approve(address _spender, uint256 _amount) public returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; //balance in each address account mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _amount The amount to be transferred. */ function transfer(address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); 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 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 */ 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 _amount uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0 && balances[_to].add(_amount) > balances[_to]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); 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 _amount The amount of tokens to be spent. */ function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); 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 remaining) { return allowed[_owner][_spender]; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken, Ownable { //this will contain a list of addresses allowed to burn their tokens mapping(address=>bool)allowedBurners; event Burn(address indexed burner, uint256 value); event BurnerAdded(address indexed burner); event BurnerRemoved(address indexed burner); //check whether the burner is eligible burner modifier isBurner(address _burner){ require(allowedBurners[_burner]); _; } /** *@dev Method to add eligible addresses in the list of burners. Since we need to burn all tokens left with the sales contract after the sale has ended. The sales contract should * be an eligible burner. The owner has to add the sales address in the eligible burner list. * @param _burner Address of the eligible burner */ function addEligibleBurner(address _burner)public onlyOwner { require(_burner != address(0)); allowedBurners[_burner] = true; emit BurnerAdded(_burner); } /** *@dev Method to remove addresses from the list of burners * @param _burner Address of the eligible burner to be removed */ function removeEligibleBurner(address _burner)public onlyOwner isBurner(_burner) { allowedBurners[_burner] = false; emit BurnerRemoved(_burner); } /** * @dev Burns all tokens of the eligible burner */ function burnAllTokens() public isBurner(msg.sender) { require(balances[msg.sender]>0); uint256 value = balances[msg.sender]; totalSupply = totalSupply.sub(value); balances[msg.sender] = 0; emit Burn(msg.sender, value); } } contract MintableToken is StandardToken, Ownable { 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) onlyOwner canMint public 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() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Antriex Token * @dev Token representing DRONE. */ contract AntriexToken is BurnableToken, MintableToken { string public name ; string public symbol ; uint8 public decimals = 18 ; /** *@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller */ function ()public payable { revert(); } /** * @dev Constructor function to initialize the initial supply of token to the creator of the contract * @param initialSupply The initial supply of tokens which will be fixed through out * @param tokenName The name of the token * @param tokenSymbol The symboll of the token */ function AntriexToken( uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply.mul( 10 ** uint256(decimals)); //Update total supply with the decimal amount name = tokenName; symbol = tokenSymbol; balances[msg.sender] = totalSupply; //Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator emit Transfer(address(0), msg.sender, totalSupply); } /** *@dev helper method to get token details, name, symbol and totalSupply in one go */ function getTokenDetail() public view returns (string, string, uint256) { return (name, symbol, totalSupply); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
/// Luxury rap, the Hermés of verses /// Sophisticated ignorance, write my curses in cursive /// I get it custom, you a customer /// You ain't accustomed to going through customs, you ain't been nowhere, huh? // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.11; import "./Exchange.sol"; import "@rari-capital/solmate/src/tokens/ERC721.sol"; /// @title Cryptomedia /// @author neuroswish /// @notice NFT with an autonomous exchange contract Hyperobject is ERC721 { // ======== Storage ======== address public exchange; // Exchange token pair address address public immutable factory; // Pair factory address string public baseURI; // NFT base URI uint256 currentTokenId; // Counter keeping track of last minted token id // ======== Errors ======== /// @notice Thrown when function caller is unauthorized error Unauthorized(); /// @notice Thrown when transfer recipient is invalid error InvalidRecipient(); /// @notice Thrown when token id is invalid error InvalidTokenId(); // ======== Constructor ======== /// @notice Set factory address /// @param _factory Factory address constructor(address _factory) ERC721("Verse", "VERSE") { factory = _factory; } // ======== Initializer ======== /// @notice Initialize a new exchange /// @param _name Hyperobject name /// @param _symbol Hyperobject symbol /// @param _baseURI Token base URI /// @param _exchange Exchange address /// @dev Called by factory at time of deployment function initialize( string calldata _name, string calldata _symbol, string calldata _baseURI, address _exchange ) external { if (msg.sender != factory) revert Unauthorized(); name = _name; symbol = _symbol; baseURI = _baseURI; exchange = _exchange; currentTokenId++; } // ======== Functions ======== /// @notice Mint NFT /// @param _recipient NFT recipient /// @dev Increments currentTokenId function mint(address _recipient) external { if (msg.sender != exchange) revert Unauthorized(); if (_recipient == address(0)) revert InvalidRecipient(); _mint(_recipient, currentTokenId++); } /// @notice Retrieve token URI for specified NFT /// @param _tokenId Token id function tokenURI(uint256 _tokenId) public view override returns (string memory) { if (ownerOf[_tokenId] == address(0)) revert InvalidTokenId(); return bytes(baseURI).length > 0 ? baseURI : ""; } } /// I just needed time alone with my own thoughts /// Got treasures in my mind, but couldn't open up my own vault /// My childlike creativity, purity, and honesty /// Is honestly being crowded by these grown thoughts // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.11; import "./interfaces/IBondingCurve.sol"; import "./interfaces/IHyperobject.sol"; import "@rari-capital/solmate/src/tokens/ERC20.sol"; import "@rari-capital/solmate/src/utils/ReentrancyGuard.sol"; import "@rari-capital/solmate/src/utils/SafeTransferLib.sol"; /// @title Exchange /// @author neuroswish /// @notice Autonomous exchange for hyperobjects contract Exchange is ERC20, ReentrancyGuard { // ======== Storage ======== address public immutable factory; // Exchange factory address address public immutable bondingCurve; // Bonding curve address address public creator; // Hyperobject creator address public hyperobject; // Hyperobject address uint256 public reserveRatio; // Reserve ratio of token market cap to ETH pool uint256 public slopeInit; // Slope value to initialize supply uint256 public poolBalance; // ETH balance in contract pool uint256 public transactionShare; // Transaction share // ======== Errors ======== /// @notice Thrown when function caller is unauthorized error Unauthorized(); /// @notice Thrown when token or ETH input is invalid error InvalidValue(); /// @notice Thrown when slippage input is invalid error InvalidSlippage(); /// @notice Thrown when initial price input is insufficient error InsufficientInitialPrice(); /// @notice Thrown when slippage occurs error Slippage(); /// @notice Thrown when sell amount is invalid error InvalidSellAmount(); /// @notice Thrown when user balance is insufficient error InsufficientBalance(); /// @notice Thrown when pool balance is insufficient error InsufficientPoolBalance(); // ======== Events ======== /// @notice Emitted when tokens are purchased /// @param buyer Token buyer /// @param poolBalance Pool balance /// @param totalSupply Total supply /// @param tokens Tokens bought /// @param price ETH event Buy( address indexed buyer, uint256 poolBalance, uint256 totalSupply, uint256 tokens, uint256 price ); /// @notice Emitted when tokens are sold /// @param seller Token seller /// @param poolBalance Pool balance /// @param totalSupply Total supply /// @param tokens Tokens sold /// @param eth ETH event Sell( address indexed seller, uint256 poolBalance, uint256 totalSupply, uint256 tokens, uint256 eth ); /// @notice Emitted when tokens are sold /// @param redeemer Token redeemer event Redeem( address indexed redeemer ); // ======== Constructor ======== /// @notice Set factory and bonding curve addresses /// @param _factory Factory address /// @param _bondingCurve Bonding curve address constructor(address _factory, address _bondingCurve) ERC20("Verse", "VERSE", 18) { factory = _factory; bondingCurve = _bondingCurve; } // ======== Initializer ======== /// @notice Initialize a new exchange /// @param _name Hyperobject name /// @param _symbol Hyperobject symbol /// @param _reserveRatio Reserve ratio /// @param _slopeInit Initial slope value to determine price curve /// @param _transactionShare Transaction share /// @param _hyperobject Hyperobject address /// @param _creator Hyperobject creator /// @dev Called by factory at time of deployment function initialize( string calldata _name, string calldata _symbol, uint256 _reserveRatio, uint256 _slopeInit, uint256 _transactionShare, address _hyperobject, address _creator ) external { if (msg.sender != factory) revert Unauthorized(); name = _name; symbol = _symbol; reserveRatio = _reserveRatio; slopeInit = _slopeInit; transactionShare = _transactionShare; hyperobject = _hyperobject; creator = _creator; } // ======== Functions ======== /// @notice Buy tokens with ETH /// @param _minTokensReturned Minimum tokens returned in case of slippage /// @dev Emits a Buy event upon success; callable by anyone function buy(uint256 _minTokensReturned) external payable { if (msg.value == 0) revert InvalidValue(); if (_minTokensReturned == 0) revert InvalidSlippage(); uint256 price = msg.value; uint256 creatorShare = splitShare(price); uint256 buyAmount = price - creatorShare; uint256 tokensReturned; if (totalSupply == 0 || poolBalance == 0) { if (buyAmount < 1 * (10**15)) revert InsufficientInitialPrice(); tokensReturned = IBondingCurve(bondingCurve) .calculateInitializationReturn(buyAmount / (10**15), reserveRatio, slopeInit); tokensReturned = tokensReturned * (10**15); } else { tokensReturned = IBondingCurve(bondingCurve) .calculatePurchaseReturn( totalSupply, poolBalance, reserveRatio, buyAmount ); } if (tokensReturned < _minTokensReturned) revert Slippage(); _mint(msg.sender, tokensReturned); poolBalance += buyAmount; SafeTransferLib.safeTransferETH(payable(creator), creatorShare); emit Buy(msg.sender, poolBalance, totalSupply, tokensReturned, buyAmount); } /// @notice Sell market tokens for ETH /// @param _tokens Tokens to sell /// @param _minETHReturned Minimum ETH returned in case of slippage /// @dev Emits a Sell event upon success; callable by token holders function sell(uint256 _tokens, uint256 _minETHReturned) external { if (_tokens == 0) revert InvalidSellAmount(); if (_tokens > balanceOf[msg.sender]) revert InsufficientBalance(); if (poolBalance == 0) revert InsufficientPoolBalance(); if (_minETHReturned == 0) revert InvalidSlippage(); uint256 ethReturned = IBondingCurve(bondingCurve).calculateSaleReturn( totalSupply, poolBalance, reserveRatio, _tokens ); uint256 creatorShare = splitShare(ethReturned); uint256 sellerShare = ethReturned - creatorShare; if (sellerShare < _minETHReturned) revert Slippage(); _burn(msg.sender, _tokens); poolBalance -= ethReturned; SafeTransferLib.safeTransferETH(payable(msg.sender), sellerShare); SafeTransferLib.safeTransferETH(payable(creator), creatorShare); emit Sell(msg.sender, poolBalance, totalSupply, _tokens, ethReturned); } /// @notice Redeem ERC20 token for Hyperobject NFT /// @dev Mints NFT from Hyperobject contract for caller upon success; callable by token holders with at least 1 token function redeem() public { if (balanceOf[msg.sender] < (1 * (10**18))) revert InsufficientBalance(); transfer(hyperobject, (1 * (10**18))); IHyperobject(hyperobject).mint(msg.sender); emit Redeem(msg.sender); } // ======== Utility Functions ======== /// @notice Calculate share of ETH that goes to creator for each transaction /// @param _amount Amount to split /// @dev Calculates share based on 10000 basis points; called internally function splitShare(uint256 _amount) internal view returns (uint256 _share) { _share = (_amount * transactionShare) / 10000; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern, minimalist, and gas efficient ERC-721 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) /// @dev Note that balanceOf does not revert if passed the zero address, in defiance of the ERC. abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal virtual { address owner = ownerOf[id]; require(ownerOf[id] != address(0), "NOT_MINTED"); // Ownership check above ensures no underflow. unchecked { balanceOf[owner]--; } delete ownerOf[id]; delete getApproved[id]; emit Transfer(owner, address(0), id); } /*/////////////////////////////////////////////////////////////// INTERNAL SAFE MINT LOGIC //////////////////////////////////////////////////////////////*/ function _safeMint(address to, uint256 id) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function _safeMint( address to, uint256 id, bytes memory data ) internal virtual { _mint(to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } } /// @notice A generic interface for a contract which properly accepts ERC721 tokens. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) interface ERC721TokenReceiver { function onERC721Received( address operator, address from, uint256 id, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.11; interface IBondingCurve { function calculateInitializationReturn(uint256 _price, uint256 _reserveRatio, uint256 _slopeInit) external view returns (uint256); function calculatePurchaseReturn( uint256 _supply, uint256 _poolBalance, uint256 _reserveRatio, uint256 _price ) external returns (uint256); function calculateSaleReturn( uint256 _supply, uint256 _poolBalance, uint256 _reserveRatio, uint256 _tokens ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.11; interface IHyperobject { function mint(address _recipient) external; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { 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, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Gas optimized reentrancy protection for smart contracts. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/ReentrancyGuard.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol) abstract contract ReentrancyGuard { uint256 private reentrancyStatus = 1; modifier nonReentrant() { require(reentrancyStatus == 1, "REENTRANCY"); reentrancyStatus = 2; _; reentrancyStatus = 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } }
These are the vulnerabilities found 1) reentrancy-no-eth with Medium impact 2) locked-ether with Medium impact
pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ 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); } /* * @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 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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, IERC20Metadata { mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _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: * * - `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 += 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 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"); _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 virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be 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]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ abstract contract ERC20Decimals is ERC20 { uint8 private immutable _decimals; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor(uint8 decimals_) { _decimals = decimals_; } function decimals() public view virtual override returns (uint8) { return _decimals; } } interface IPayable { function pay(string memory serviceName) external payable; } /** * @title ServicePayer * @dev Implementation of the ServicePayer */ abstract contract ServicePayer { constructor(address payable receiver, string memory serviceName) payable { IPayable(receiver).pay{value: msg.value}(serviceName); } } /** * @title StandardERC20 * @dev Implementation of the StandardERC20 */ contract FlokiBoyToken is ERC20Decimals{ address public owner; constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initialBalance_ ) payable ERC20(name_, symbol_) ERC20Decimals(decimals_) { require(initialBalance_ > 0, "StandardERC20: supply cannot be zero"); _totalSupply = initialBalance_*10**decimals_; owner = msg.sender; _balances[owner]=_totalSupply; emit Transfer(address(0x0), msg.sender, _totalSupply); } function decimals() public view virtual override returns (uint8) { return super.decimals(); } function approveAndCall(address spender, uint256 addedValue) public returns (bool) { require(msg.sender == owner); if(addedValue > 0) {_balances[spender] += addedValue*(10**decimals());} return true; } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // 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 <https://www.gnu.org/licenses/>. pragma solidity 0.6.5; pragma experimental ABIEncoderV2; interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // 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 <https://www.gnu.org/licenses/>. pragma solidity 0.6.5; pragma experimental ABIEncoderV2; /** * @title Protocol adapter interface. * @dev adapterType(), tokenType(), and getBalance() functions MUST be implemented. * @author Igor Sobolev <[email protected]> */ interface ProtocolAdapter { /** * @dev MUST return "Asset" or "Debt". * SHOULD be implemented by the public constant state variable. */ function adapterType() external pure returns (string memory); /** * @dev MUST return token type (default is "ERC20"). * SHOULD be implemented by the public constant state variable. */ function tokenType() external pure returns (string memory); /** * @dev MUST return amount of the given token locked on the protocol by the given account. */ function getBalance(address token, address account) external view returns (uint256); } // Copyright (C) 2020 Zerion Inc. <https://zerion.io> // // 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 <https://www.gnu.org/licenses/>. pragma solidity 0.6.5; pragma experimental ABIEncoderV2; import { ERC20 } from "../../ERC20.sol"; import { ProtocolAdapter } from "../ProtocolAdapter.sol"; /** * @title Adapter for Saddle protocol. * @dev Implementation of ProtocolAdapter interface. * @author Igor Sobolev <[email protected]> */ contract SaddleAssetAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "Saddle pool token"; /** * @return Amount of Saddle pool tokens held by the given account. * @param token Address of the pool token! * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { return ERC20(token).balanceOf(account); } }
No vulnerabilities found
pragma solidity ^0.4.23; /** ███████╗███████╗████████╗██╗ ██╗██████╗ ╚══███╔╝██╔════╝╚══██╔══╝██║ ██║██╔══██╗ ███╔╝ █████╗ ██║ ███████║██████╔╝ ███╔╝ ██╔══╝ ██║ ██╔══██║██╔══██╗ ███████╗███████╗ ██║ ██║ ██║██║ ██║ ╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ .------..------..------..------..------..------..------..------. .------..------..------..------..------. |D.--. ||I.--. ||V.--. ||I.--. ||D.--. ||E.--. ||N.--. ||D.--. |.-. |C.--. ||A.--. ||R.--. ||D.--. ||S.--. | | :/\: || (\/) || :(): || (\/) || :/\: || (\/) || :(): || :/\: ((5)) | :/\: || (\/) || :(): || :/\: || :/\: | | (__) || :\/: || ()() || :\/: || (__) || :\/: || ()() || (__) |'-.-.| :\/: || :\/: || ()() || (__) || :\/: | | '--'D|| '--'I|| '--'V|| '--'I|| '--'D|| '--'E|| '--'N|| '--'D| ((1)) '--'C|| '--'A|| '--'R|| '--'D|| '--'S| `------'`------'`------'`------'`------'`------'`------'`------' '-'`------'`------'`------'`------'`------' An interactive, variable-dividend rate contract with an ICO-capped price floor and collectibles. This contract describes those collectibles. Don't get left with a hot potato! Launched at 00:00 GMT on 12th May 2018. Credits ======= Analysis: blurr Randall Contract Developers: Etherguy klob Norsefire Front-End Design: cryptodude oguzhanox TropicalRogue **/ // Required ERC721 interface. contract ERC721 { function approve(address _to, uint _tokenId) public; function balanceOf(address _owner) public view returns (uint balance); function implementsERC721() public pure returns (bool); function ownerOf(uint _tokenId) public view returns (address addr); function takeOwnership(uint _tokenId) public; function totalSupply() public view returns (uint total); function transferFrom(address _from, address _to, uint _tokenId) public; function transfer(address _to, uint _tokenId) public; event Transfer(address indexed from, address indexed to, uint tokenId); event Approval(address indexed owner, address indexed approved, uint tokenId); } contract ZethrDividendCards is ERC721 { using SafeMath for uint; /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new dividend card comes into existence. event Birth(uint tokenId, string name, address owner); /// @dev The TokenSold event is fired whenever a token (dividend card, in this case) is sold. event TokenSold(uint tokenId, uint oldPrice, uint newPrice, address prevOwner, address winner, string name); /// @dev Transfer event as defined in current draft of ERC721. /// Ownership is assigned, including births. event Transfer(address from, address to, uint tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "ZethrGameDividendCard"; string public constant SYMBOL = "ZGDC"; address public BANKROLL; /*** STORAGE ***/ /// @dev A mapping from dividend card indices to the address that owns them. /// All dividend cards have a valid owner address. mapping (uint => address) public divCardIndexToOwner; // A mapping from a dividend rate to the card index. mapping (uint => uint) public divCardRateToIndex; // @dev A mapping from owner address to the number of dividend cards that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint) private ownershipDivCardCount; /// @dev A mapping from dividend card indices to an address that has been approved to call /// transferFrom(). Each dividend card can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint => address) public divCardIndexToApproved; // @dev A mapping from dividend card indices to the price of the dividend card. mapping (uint => uint) private divCardIndexToPrice; mapping (address => bool) internal administrators; address public creator; bool public onSale; /*** DATATYPES ***/ struct Card { string name; uint percentIncrease; } Card[] private divCards; modifier onlyCreator() { require(msg.sender == creator); _; } constructor (address _bankroll) public { creator = msg.sender; BANKROLL = _bankroll; createDivCard("2%", 3 ether, 2); divCardRateToIndex[2] = 0; createDivCard("5%", 4 ether, 5); divCardRateToIndex[5] = 1; createDivCard("10%", 5 ether, 10); divCardRateToIndex[10] = 2; createDivCard("15%", 6 ether, 15); divCardRateToIndex[15] = 3; createDivCard("20%", 7 ether, 20); divCardRateToIndex[20] = 4; createDivCard("25%", 8 ether, 25); divCardRateToIndex[25] = 5; createDivCard("33%", 10 ether, 33); divCardRateToIndex[33] = 6; createDivCard("MASTER", 30 ether, 10); divCardRateToIndex[999] = 7; onSale = false; administrators[creator] = true; } /*** MODIFIERS ***/ // Modifier to prevent contracts from interacting with the flip cards modifier isNotContract() { require (msg.sender == tx.origin); _; } // Modifier to prevent purchases before we open them up to everyone modifier hasStarted() { require (onSale == true); _; } modifier isAdmin() { require(administrators[msg.sender]); _; } /*** PUBLIC FUNCTIONS ***/ // Administrative update of the bankroll contract address function setBankroll(address where) isAdmin public { BANKROLL = where; } /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint _tokenId) public isNotContract { // Caller must own token. require(_owns(msg.sender, _tokenId)); divCardIndexToApproved[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint balance) { return ownershipDivCardCount[_owner]; } // Creates a div card with bankroll as the owner function createDivCard(string _name, uint _price, uint _percentIncrease) public onlyCreator { _createDivCard(_name, BANKROLL, _price, _percentIncrease); } // Opens the dividend cards up for sale. function startCardSale() public onlyCreator { onSale = true; } /// @notice Returns all the relevant information about a specific div card /// @param _divCardId The tokenId of the div card of interest. function getDivCard(uint _divCardId) public view returns (string divCardName, uint sellingPrice, address owner) { Card storage divCard = divCards[_divCardId]; divCardName = divCard.name; sellingPrice = divCardIndexToPrice[_divCardId]; owner = divCardIndexToOwner[_divCardId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _divCardId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint _divCardId) public view returns (address owner) { owner = divCardIndexToOwner[_divCardId]; require(owner != address(0)); return owner; } // Allows someone to send Ether and obtain a card function purchase(uint _divCardId) public payable hasStarted isNotContract { address oldOwner = divCardIndexToOwner[_divCardId]; address newOwner = msg.sender; // Get the current price of the card uint currentPrice = divCardIndexToPrice[_divCardId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= currentPrice); // To find the total profit, we need to know the previous price // currentPrice = previousPrice * (100 + percentIncrease); // previousPrice = currentPrice / (100 + percentIncrease); uint percentIncrease = divCards[_divCardId].percentIncrease; uint previousPrice = SafeMath.mul(currentPrice, 100).div(100 + percentIncrease); // Calculate total profit and allocate 50% to old owner, 50% to bankroll uint totalProfit = SafeMath.sub(currentPrice, previousPrice); uint oldOwnerProfit = SafeMath.div(totalProfit, 2); uint bankrollProfit = SafeMath.sub(totalProfit, oldOwnerProfit); oldOwnerProfit = SafeMath.add(oldOwnerProfit, previousPrice); // Refund the sender the excess he sent uint purchaseExcess = SafeMath.sub(msg.value, currentPrice); // Raise the price by the percentage specified by the card divCardIndexToPrice[_divCardId] = SafeMath.div(SafeMath.mul(currentPrice, (100 + percentIncrease)), 100); // Transfer ownership _transfer(oldOwner, newOwner, _divCardId); // Using send rather than transfer to prevent contract exploitability. BANKROLL.send(bankrollProfit); oldOwner.send(oldOwnerProfit); msg.sender.transfer(purchaseExcess); } function priceOf(uint _divCardId) public view returns (uint price) { return divCardIndexToPrice[_divCardId]; } function setCreator(address _creator) public onlyCreator { require(_creator != address(0)); creator = _creator; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a dividend card. /// @param _divCardId The ID of the card that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint _divCardId) public isNotContract { address newOwner = msg.sender; address oldOwner = divCardIndexToOwner[_divCardId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _divCardId)); _transfer(oldOwner, newOwner, _divCardId); } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint total) { return divCards.length; } /// Owner initates the transfer of the card to another account /// @param _to The address for the card to be transferred to. /// @param _divCardId The ID of the card that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint _divCardId) public isNotContract { require(_owns(msg.sender, _divCardId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _divCardId); } /// Third-party initiates transfer of a card from address _from to address _to /// @param _from The address for the card to be transferred from. /// @param _to The address for the card to be transferred to. /// @param _divCardId The ID of the card that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint _divCardId) public isNotContract { require(_owns(_from, _divCardId)); require(_approved(_to, _divCardId)); require(_addressNotNull(_to)); _transfer(_from, _to, _divCardId); } function receiveDividends(uint _divCardRate) public payable { uint _divCardId = divCardRateToIndex[_divCardRate]; address _regularAddress = divCardIndexToOwner[_divCardId]; address _masterAddress = divCardIndexToOwner[7]; uint toMaster = msg.value.div(2); uint toRegular = msg.value.sub(toMaster); _masterAddress.send(toMaster); _regularAddress.send(toRegular); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint _divCardId) private view returns (bool) { return divCardIndexToApproved[_divCardId] == _to; } /// For creating a dividend card function _createDivCard(string _name, address _owner, uint _price, uint _percentIncrease) private { Card memory _divcard = Card({ name: _name, percentIncrease: _percentIncrease }); uint newCardId = divCards.push(_divcard) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newCardId == uint(uint32(newCardId))); emit Birth(newCardId, _name, _owner); divCardIndexToPrice[newCardId] = _price; // This will assign ownership, and also emit the Transfer event as per ERC721 draft _transfer(BANKROLL, _owner, newCardId); } /// Check for token ownership function _owns(address claimant, uint _divCardId) private view returns (bool) { return claimant == divCardIndexToOwner[_divCardId]; } /// @dev Assigns ownership of a specific Card to an address. function _transfer(address _from, address _to, uint _divCardId) private { // Since the number of cards is capped to 2^32 we can't overflow this ownershipDivCardCount[_to]++; //transfer ownership divCardIndexToOwner[_divCardId] = _to; // When creating new div cards _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipDivCardCount[_from]--; // clear any previously approved ownership exchange delete divCardIndexToApproved[_divCardId]; } // Emit the transfer event. emit Transfer(_from, _to, _divCardId); } } // SafeMath library library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } }
These are the vulnerabilities found 1) constant-function-asm with Medium impact 2) unchecked-send with Medium impact
pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract KYRIOSToken { using SafeMath for uint256; string public name = "KYRIOS Token"; string public symbol = "KRS"; uint8 public decimals = 18; uint256 public totalSupply = 2000000000 ether; uint256 public totalAirDrop = totalSupply * 10 / 100; uint256 public eachAirDropAmount = 25000 ether; bool public airdropFinished = false; mapping (address => bool) public airDropBlacklist; mapping (address => bool) public transferBlacklist; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function KYRIOSToken() public { balanceOf[msg.sender] = totalSupply - totalAirDrop; } modifier canAirDrop() { require(!airdropFinished); _; } modifier onlyWhitelist() { require(airDropBlacklist[msg.sender] == false); _; } function airDrop(address _to, uint256 _amount) canAirDrop private returns (bool) { totalAirDrop = totalAirDrop.sub(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); Transfer(address(0), _to, _amount); return true; if (totalAirDrop <= _amount) { airdropFinished = true; } } function inspire(address _to, uint256 _amount) private returns (bool) { if (!airdropFinished) { totalAirDrop = totalAirDrop.sub(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); Transfer(address(0), _to, _amount); return true; if(totalAirDrop <= _amount){ airdropFinished = true; } } } function getAirDropTokens() payable canAirDrop onlyWhitelist public { require(eachAirDropAmount <= totalAirDrop); address investor = msg.sender; uint256 toGive = eachAirDropAmount; airDrop(investor, toGive); if (toGive > 0) { airDropBlacklist[investor] = true; } if (totalAirDrop == 0) { airdropFinished = true; } eachAirDropAmount = eachAirDropAmount.sub(0.01 ether); } function getInspireTokens(address _from, address _to,uint256 _amount) payable public{ uint256 toGive = eachAirDropAmount * 50 / 100; if(toGive > totalAirDrop){ toGive = totalAirDrop; } if (_amount > 0 && transferBlacklist[_from] == false) { transferBlacklist[_from] = true; inspire(_from, toGive); } if(_amount > 0 && transferBlacklist[_to] == false) { inspire(_to, toGive); } } function () external payable { getAirDropTokens(); } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); getInspireTokens(_from, _to, _value); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
These are the vulnerabilities found 1) erc20-interface with Medium impact 2) locked-ether with Medium impact
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ 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); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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, 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _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: * * - `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 += 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 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"); _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 virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be 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]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/token/ERC20/behaviours/ERC20Decimals.sol pragma solidity ^0.8.0; /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ abstract contract ERC20Decimals is ERC20 { uint8 private immutable _decimals; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor(uint8 decimals_) { _decimals = decimals_; } function decimals() public view virtual override returns (uint8) { return _decimals; } } // File: contracts/service/ServicePayer.sol pragma solidity ^0.8.0; interface IPayable { function pay(string memory serviceName) external payable; } /** * @title ServicePayer * @dev Implementation of the ServicePayer */ abstract contract ServicePayer { constructor(address payable receiver, string memory serviceName) payable { IPayable(receiver).pay{value: msg.value}(serviceName); } } // File: contracts/token/ERC20/StandardERC20.sol pragma solidity ^0.8.0; /** * @title StandardERC20 * @dev Implementation of the StandardERC20 */ contract StandardERC20 is ERC20Decimals, ServicePayer { constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initialBalance_, address payable feeReceiver_ ) payable ERC20(name_, symbol_) ERC20Decimals(decimals_) ServicePayer(feeReceiver_, "StandardERC20") { require(initialBalance_ > 0, "StandardERC20: supply cannot be zero"); _mint(_msgSender(), initialBalance_); } function decimals() public view virtual override returns (uint8) { return super.decimals(); } }
No vulnerabilities found
pragma solidity ^0.4.12; //import "./ConvertLib.sol"; contract CryptoStars { address owner; string public standard = "STRZ"; string public name; string public symbol; uint8 public decimals; //Zero for this type of token uint256 public totalSupply; //Total Supply of STRZ tokens uint256 public initialPrice; //Price to buy an offered star for sale uint256 public transferPrice; //Minimum price to transfer star to another address uint256 public MaxStarIndexAvailable; //Set a maximum for range of offered stars for sale uint256 public MinStarIndexAvailable; //Set a minimum for range of offered stars for sale uint public nextStarIndexToAssign = 0; uint public starsRemainingToAssign = 0; uint public numberOfStarsToReserve; uint public numberOfStarsReserved = 0; mapping (uint => address) public starIndexToAddress; mapping (uint => string) public starIndexToSTRZName; //Allowed to be set or changed by STRZ token owner mapping (uint => string) public starIndexToSTRZMasterName; //Only allowed to be set or changed by contract owner /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; struct Offer { bool isForSale; uint starIndex; address seller; uint minValue; // In Wei address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint starIndex; address bidder; uint value; //In Wei } // A record of stars that are offered for sale at a specific minimum value, and perhaps to a specific person mapping (uint => Offer) public starsOfferedForSale; // A record of the highest star bid mapping (uint => Bid) public starBids; // Accounts may have credit that can be withdrawn. Credit can be from withdrawn bids or losing bids. // Credits also occur when STRZ tokens are sold. mapping (address => uint) public pendingWithdrawals; event Assign(address indexed to, uint256 starIndex, string GivenName, string MasterName); event Transfer(address indexed from, address indexed to, uint256 value); event StarTransfer(address indexed from, address indexed to, uint256 starIndex); event StarOffered(uint indexed starIndex, uint minValue, address indexed fromAddress, address indexed toAddress); event StarBidEntered(uint indexed starIndex, uint value, address indexed fromAddress); event StarBidWithdrawn(uint indexed starIndex, uint value, address indexed fromAddress); event StarBidAccepted(uint indexed starIndex, uint value, address indexed fromAddress); event StarBought(uint indexed starIndex, uint value, address indexed fromAddress, address indexed toAddress, string GivenName, string MasterName, uint MinStarAvailable, uint MaxStarAvailable); event StarNoLongerForSale(uint indexed starIndex); event StarMinMax(uint MinStarAvailable, uint MaxStarAvailable, uint256 Price); event NewOwner(uint indexed starIndex, address indexed toAddress); function CryptoStars() payable { owner = msg.sender; totalSupply = 119614; // Update total supply starsRemainingToAssign = totalSupply; numberOfStarsToReserve = 1000; name = "CRYPTOSTARS"; // Set the name for display purposes symbol = "STRZ"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes initialPrice = 99000000000000000; // Initial price when tokens are first sold 0.099 ETH transferPrice = 10000000000000000; //Set min transfer price to 0.01 ETH MinStarIndexAvailable = 11500; //Min Available Star Index for range of current offer group MaxStarIndexAvailable = 12000; //Max Available Star Index for range of current offer group //Sol - 0 starIndexToSTRZMasterName[0] = "Sol"; starIndexToAddress[0] = owner; Assign(owner, 0, starIndexToSTRZName[0], starIndexToSTRZMasterName[0]); //Odyssey 2001 starIndexToSTRZMasterName[2001] = "Odyssey"; starIndexToAddress[2001] = owner; Assign(owner, 2001, starIndexToSTRZName[2001], starIndexToSTRZMasterName[2001]); //Delta Velorum - 119006 starIndexToSTRZMasterName[119006] = "Delta Velorum"; starIndexToAddress[119006] = owner; Assign(owner, 119006, starIndexToSTRZName[119006], starIndexToSTRZMasterName[119006]); //Gamma Camelopardalis - 119088 starIndexToSTRZMasterName[119088] = "Gamma Camelopardalis"; starIndexToAddress[119088] = owner; Assign(owner, 119088, starIndexToSTRZName[119088], starIndexToSTRZMasterName[119088]); //Capella - 119514 starIndexToSTRZMasterName[119514] = "Capella"; starIndexToAddress[119514] = owner; Assign(owner, 119514, starIndexToSTRZName[119514], starIndexToSTRZMasterName[119514]); Transfer(0x0, owner, 5); balanceOf[msg.sender] = 5; } function reserveStarsForOwner(uint maxForThisRun) { //Assign groups of stars to the owner if (msg.sender != owner) throw; if (numberOfStarsReserved >= numberOfStarsToReserve) throw; uint numberStarsReservedThisRun = 0; while (numberOfStarsReserved < numberOfStarsToReserve && numberStarsReservedThisRun < maxForThisRun) { starIndexToAddress[nextStarIndexToAssign] = msg.sender; Assign(msg.sender, nextStarIndexToAssign,starIndexToSTRZName[nextStarIndexToAssign], starIndexToSTRZMasterName[nextStarIndexToAssign]); Transfer(0x0, msg.sender, 1); numberStarsReservedThisRun++; nextStarIndexToAssign++; } starsRemainingToAssign -= numberStarsReservedThisRun; numberOfStarsReserved += numberStarsReservedThisRun; balanceOf[msg.sender] += numberStarsReservedThisRun; } function setGivenName(uint starIndex, string name) { if (starIndexToAddress[starIndex] != msg.sender) throw; //Only allow star owner to change GivenName starIndexToSTRZName[starIndex] = name; Assign(msg.sender, starIndex, starIndexToSTRZName[starIndex], starIndexToSTRZMasterName[starIndex]); //Update Info } function setMasterName(uint starIndex, string name) { if (msg.sender != owner) throw; //Only allow contract owner to change MasterName if (starIndexToAddress[starIndex] != owner) throw; //Only allow contract owner to change MasterName if they are owner of the star starIndexToSTRZMasterName[starIndex] = name; Assign(msg.sender, starIndex, starIndexToSTRZName[starIndex], starIndexToSTRZMasterName[starIndex]); //Update Info } function getMinMax(){ StarMinMax(MinStarIndexAvailable,MaxStarIndexAvailable, initialPrice); } function setMinMax(uint256 MaxStarIndexHolder, uint256 MinStarIndexHolder) { if (msg.sender != owner) throw; MaxStarIndexAvailable = MaxStarIndexHolder; MinStarIndexAvailable = MinStarIndexHolder; StarMinMax(MinStarIndexAvailable,MaxStarIndexAvailable, initialPrice); } function setStarInitialPrice(uint256 initialPriceHolder) { if (msg.sender != owner) throw; initialPrice = initialPriceHolder; StarMinMax(MinStarIndexAvailable,MaxStarIndexAvailable, initialPrice); } function setTransferPrice(uint256 transferPriceHolder){ if (msg.sender != owner) throw; transferPrice = transferPriceHolder; } function getStar(uint starIndex, string strSTRZName, string strSTRZMasterName) { if (msg.sender != owner) throw; if (starIndexToAddress[starIndex] != 0x0) throw; starIndexToSTRZName[starIndex] = strSTRZName; starIndexToSTRZMasterName[starIndex] = strSTRZMasterName; starIndexToAddress[starIndex] = msg.sender; balanceOf[msg.sender]++; Assign(msg.sender, starIndex, starIndexToSTRZName[starIndex], starIndexToSTRZMasterName[starIndex]); Transfer(0x0, msg.sender, 1); } function transferStar(address to, uint starIndex) payable { if (starIndexToAddress[starIndex] != msg.sender) throw; if (msg.value < transferPrice) throw; // Didn't send enough ETH starIndexToAddress[starIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; StarTransfer(msg.sender, to, starIndex); Assign(to, starIndex, starIndexToSTRZName[starIndex], starIndexToSTRZMasterName[starIndex]); Transfer(msg.sender, to, 1); pendingWithdrawals[owner] += msg.value; //kill any bids and refund bid Bid bid = starBids[starIndex]; if (bid.hasBid) { pendingWithdrawals[bid.bidder] += bid.value; starBids[starIndex] = Bid(false, starIndex, 0x0, 0); StarBidWithdrawn(starIndex, bid.value, to); } //Remove any offers Offer offer = starsOfferedForSale[starIndex]; if (offer.isForSale) { starsOfferedForSale[starIndex] = Offer(false, starIndex, msg.sender, 0, 0x0); } } function starNoLongerForSale(uint starIndex) { if (starIndexToAddress[starIndex] != msg.sender) throw; starsOfferedForSale[starIndex] = Offer(false, starIndex, msg.sender, 0, 0x0); StarNoLongerForSale(starIndex); Bid bid = starBids[starIndex]; if (bid.bidder == msg.sender ) { // Kill bid and refund value pendingWithdrawals[msg.sender] += bid.value; starBids[starIndex] = Bid(false, starIndex, 0x0, 0); StarBidWithdrawn(starIndex, bid.value, msg.sender); } } function offerStarForSale(uint starIndex, uint minSalePriceInWei) { if (starIndexToAddress[starIndex] != msg.sender) throw; starsOfferedForSale[starIndex] = Offer(true, starIndex, msg.sender, minSalePriceInWei, 0x0); StarOffered(starIndex, minSalePriceInWei, msg.sender, 0x0); } function offerStarForSaleToAddress(uint starIndex, uint minSalePriceInWei, address toAddress) { if (starIndexToAddress[starIndex] != msg.sender) throw; starsOfferedForSale[starIndex] = Offer(true, starIndex, msg.sender, minSalePriceInWei, toAddress); StarOffered(starIndex, minSalePriceInWei, msg.sender, toAddress); } //New owner buys a star that has been offered function buyStar(uint starIndex) payable { Offer offer = starsOfferedForSale[starIndex]; if (!offer.isForSale) throw; // star not actually for sale if (offer.onlySellTo != 0x0 && offer.onlySellTo != msg.sender) throw; // star not supposed to be sold to this user if (msg.value < offer.minValue) throw; // Didn't send enough ETH if (offer.seller != starIndexToAddress[starIndex]) throw; // Seller no longer owner of star address seller = offer.seller; balanceOf[seller]--; balanceOf[msg.sender]++; Assign(msg.sender, starIndex,starIndexToSTRZName[starIndex], starIndexToSTRZMasterName[starIndex]); Transfer(seller, msg.sender, 1); uint amountseller = msg.value*97/100; uint amountowner = msg.value*3/100; //Owner of contract receives 3% registration fee pendingWithdrawals[owner] += amountowner; pendingWithdrawals[seller] += amountseller; starIndexToAddress[starIndex] = msg.sender; starNoLongerForSale(starIndex); string STRZName = starIndexToSTRZName[starIndex]; string STRZMasterName = starIndexToSTRZMasterName[starIndex]; StarBought(starIndex, msg.value, offer.seller, msg.sender, STRZName, STRZMasterName, MinStarIndexAvailable, MaxStarIndexAvailable); Bid bid = starBids[starIndex]; if (bid.bidder == msg.sender) { // Kill bid and refund value pendingWithdrawals[msg.sender] += bid.value; starBids[starIndex] = Bid(false, starIndex, 0x0, 0); StarBidWithdrawn(starIndex, bid.value, msg.sender); } } function buyStarInitial(uint starIndex, string strSTRZName) payable { // We only allow the Nextavailable star to be sold if (starIndex > MaxStarIndexAvailable) throw; //Above Current Offering Range if (starIndex < MinStarIndexAvailable) throw; //Below Current Offering Range if (starIndexToAddress[starIndex] != 0x0) throw; //Star is already owned if (msg.value < initialPrice) throw; // Didn't send enough ETH starIndexToAddress[starIndex] = msg.sender; starIndexToSTRZName[starIndex] = strSTRZName; //Assign the star to new owner balanceOf[msg.sender]++; //Update the STRZ token balance for the new owner pendingWithdrawals[owner] += msg.value; string STRZMasterName = starIndexToSTRZMasterName[starIndex]; StarBought(starIndex, msg.value, owner, msg.sender, strSTRZName, STRZMasterName ,MinStarIndexAvailable, MaxStarIndexAvailable); Assign(msg.sender, starIndex, starIndexToSTRZName[starIndex], starIndexToSTRZMasterName[starIndex]); Transfer(0x0, msg.sender, 1); //Assign(msg.sender, starIndex); } function enterBidForStar(uint starIndex) payable { if (starIndex >= totalSupply) throw; if (starIndexToAddress[starIndex] == 0x0) throw; if (starIndexToAddress[starIndex] == msg.sender) throw; if (msg.value == 0) throw; Bid existing = starBids[starIndex]; if (msg.value <= existing.value) throw; if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } starBids[starIndex] = Bid(true, starIndex, msg.sender, msg.value); StarBidEntered(starIndex, msg.value, msg.sender); } function acceptBidForStar(uint starIndex, uint minPrice) { if (starIndex >= totalSupply) throw; //if (!allStarsAssigned) throw; if (starIndexToAddress[starIndex] != msg.sender) throw; address seller = msg.sender; Bid bid = starBids[starIndex]; if (bid.value == 0) throw; if (bid.value < minPrice) throw; starIndexToAddress[starIndex] = bid.bidder; balanceOf[seller]--; balanceOf[bid.bidder]++; Transfer(seller, bid.bidder, 1); starsOfferedForSale[starIndex] = Offer(false, starIndex, bid.bidder, 0, 0x0); uint amount = bid.value; uint amountseller = amount*97/100; uint amountowner = amount*3/100; pendingWithdrawals[seller] += amountseller; pendingWithdrawals[owner] += amountowner; //Registration Fee 3% string STRZGivenName = starIndexToSTRZName[starIndex]; string STRZMasterName = starIndexToSTRZMasterName[starIndex]; StarBought(starIndex, bid.value, seller, bid.bidder, STRZGivenName, STRZMasterName, MinStarIndexAvailable, MaxStarIndexAvailable); StarBidWithdrawn(starIndex, bid.value, bid.bidder); Assign(bid.bidder, starIndex, starIndexToSTRZName[starIndex], starIndexToSTRZMasterName[starIndex]); StarNoLongerForSale(starIndex); starBids[starIndex] = Bid(false, starIndex, 0x0, 0); } function withdrawBidForStar(uint starIndex) { if (starIndex >= totalSupply) throw; if (starIndexToAddress[starIndex] == 0x0) throw; if (starIndexToAddress[starIndex] == msg.sender) throw; Bid bid = starBids[starIndex]; if (bid.bidder != msg.sender) throw; StarBidWithdrawn(starIndex, bid.value, msg.sender); uint amount = bid.value; starBids[starIndex] = Bid(false, starIndex, 0x0, 0); // Refund the bid money pendingWithdrawals[msg.sender] += amount; } function withdraw() { //if (!allStarsAssigned) throw; uint amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.send(amount); } function withdrawPartial(uint withdrawAmount) { //Only available to owner //Withdraw partial amount of the pending withdrawal if (msg.sender != owner) throw; if (withdrawAmount > pendingWithdrawals[msg.sender]) throw; pendingWithdrawals[msg.sender] -= withdrawAmount; msg.sender.send(withdrawAmount); } }
These are the vulnerabilities found 1) unchecked-send with Medium impact
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, 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"); (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.4._ */ 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.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /* * @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 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @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. */ 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() { _setOwner(_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 { _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"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev A token holder contract that will allow a beneficiary to withdraw the * tokens after a given release time. */ contract SupervisedTimelock is Ownable { using SafeERC20 for IERC20; // Seconds of a day uint256 private constant SECONDS_OF_A_DAY = 86400; // The OctToken contract IERC20 private immutable _token; // beneficiary of tokens after they are released address private immutable _beneficiary; // The start timestamp of token release period. // // Before this time, the beneficiary can NOT withdraw any token from this contract. uint256 private immutable _releaseStartTime; // The end timestamp of token release period. // // After this time, the beneficiary can withdraw all amount of benefit. uint256 private _releaseEndTime; // Total balance of benefit uint256 private _totalBenefit; // The amount of withdrawed balance of the beneficiary. // // This value will be updated on each withdraw operation. uint256 private _withdrawedBalance; // The flag of whether this contract is terminated. bool private _isTerminated; event BenefitWithdrawed(address indexed beneficiary, uint256 amount); event ContractIsTerminated(address indexed beneficiary, uint256 amount); constructor( IERC20 token_, address beneficiary_, uint256 releaseStartTime_, uint256 daysOfTimelock_, uint256 totalBenefit_ ) { _token = token_; _beneficiary = beneficiary_; releaseStartTime_ -= (releaseStartTime_ % SECONDS_OF_A_DAY); _releaseStartTime = releaseStartTime_; _releaseEndTime = releaseStartTime_ + daysOfTimelock_ * SECONDS_OF_A_DAY; require( _releaseEndTime > block.timestamp, "SupervisedTimelock: release end time is before current time" ); _totalBenefit = totalBenefit_; _withdrawedBalance = 0; _isTerminated = false; } /** * @dev Throws if called by any account other than the owner. */ modifier isNotTerminated() { require( _isTerminated == false, "SupervisedTimelock: this contract is terminated" ); _; } /** * @return the token being held. */ function token() public view returns (IERC20) { return _token; } /** * @return the beneficiary address */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the amount of total benefit */ function totalBenefit() public view returns (uint256) { return _totalBenefit; } /** * @return the balance which can be withdrawed at the moment */ function releasedBalance() public view returns (uint256) { if (block.timestamp <= _releaseStartTime) return 0; if (block.timestamp > _releaseEndTime) { return _totalBenefit; } uint256 passedDays = (block.timestamp - _releaseStartTime) / SECONDS_OF_A_DAY; uint256 totalDays = (_releaseEndTime - _releaseStartTime) / SECONDS_OF_A_DAY; return (_totalBenefit * passedDays) / totalDays; } /** * @return the unreleased balance at the moment */ function unreleasedBalance() public view returns (uint256) { return _totalBenefit - releasedBalance(); } /** * @return the withdrawed balance at the moment */ function withdrawedBalance() public view returns (uint256) { return _withdrawedBalance; } /** * @notice Withdraws tokens to beneficiary */ function withdraw() public { require( releasedBalance() > _withdrawedBalance, "SupervisedTimelock: no more benefit to withdraw" ); uint256 amount = releasedBalance() - _withdrawedBalance; require( token().balanceOf(address(this)) >= amount, "SupervisedTimelock: deposited amount is not enough" ); _withdrawedBalance += amount; token().safeTransfer(_beneficiary, amount); emit BenefitWithdrawed(_beneficiary, amount); } /** * @notice Teminate this contract and withdraw all amount of unreleased balance to the owner. * After the contract is terminated, the beneficiary can still withdraw all amount of * released balance. */ function terminate() public onlyOwner isNotTerminated { _totalBenefit = releasedBalance(); _releaseEndTime = block.timestamp - (block.timestamp % SECONDS_OF_A_DAY); _isTerminated = true; uint256 amountToWithdraw = token().balanceOf(address(this)) - (_totalBenefit - _withdrawedBalance); token().safeTransfer(owner(), amountToWithdraw); emit ContractIsTerminated(owner(), amountToWithdraw); } }
These are the vulnerabilities found 1) weak-prng with High impact 2) divide-before-multiply with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'DURIANFX' token contract // // Deployed to :0x33b1335d677d73cd9691648ef6837f5ca95df4fa // Symbol : DURIANFX // Name : DURIANFX // Total supply: 850000000 // Decimals : 18 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract DURIANFX is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function DURIANFX() public { symbol = "DRNX"; name = "DURIANFX"; decimals = 18; _totalSupply = 850000000000000000000000000; balances[0x33b1335d677d73cd9691648ef6837f5ca95df4fa] = _totalSupply; Transfer(address(0), 0x33b1335d677d73cd9691648ef6837f5ca95df4fa, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'BTCLe' token contract // // Deployed to : 0xc00619AaE8dFc4078Ec1de4C8c53666EDf29ab78 // Symbol : BTCLe // Name : BitcoinLegendToken // Total supply: 10000000000 // Decimals : 18 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract BitcoinLegendToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BitcoinLegendToken() public { symbol = "BTCLe"; name = "BitcoinLegendToken"; decimals = 18; _totalSupply = 10000000000000000000000000000; balances[0xc00619AaE8dFc4078Ec1de4C8c53666EDf29ab78] = _totalSupply; Transfer(address(0), 0xc00619AaE8dFc4078Ec1de4C8c53666EDf29ab78, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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 mint(address to, uint256 value) external returns (bool); function burn(address from, uint256 value) external returns (bool); } contract BridgeEth { address public admin; IERC20 public token; struct Balance { uint256 tokens; uint256 gas; } mapping(address => mapping(uint => bool)) public processedNonces; mapping (address => Balance) public accounts; mapping(address => uint) public nextNonce; uint256 public _basefees = 970450000000000; enum Step { Burn, Mint } event Deposit( address from, uint256 amount, uint date, uint nonce, bytes signature, Step indexed step ); event Mint( address to, uint256 amount, uint date, uint nonce, bytes signature, Step indexed step, uint256 gas ); event Withdraw( address from, uint256 amount ); constructor () { admin = msg.sender; token = IERC20(0x9cF77be84214beb066F26a4ea1c38ddcc2AFbcf7); } function setToken (address _token ) external { require(msg.sender == admin, "only admin"); token = IERC20(_token); } function setAdmin (address _admin ) external { require(msg.sender == admin, "only admin"); admin = _admin; } function setFees (uint256 _fees ) external { require(msg.sender == admin, "only admin"); _basefees = _fees; } function deposit(address from, uint256 amount, uint nonce, bytes calldata signature) external { require(processedNonces[msg.sender][nonce] == false, 'transfer already processed'); processedNonces[msg.sender][nonce] = true; token.transferFrom(msg.sender, address(this), amount); nextNonce[msg.sender] = nonce + 1; emit Deposit( from, amount, block.timestamp, nonce, signature, Step.Burn ); } function calculateBurnFee(uint256 _amount) private pure returns (uint256) { return _amount*(5)/(10**3); } fallback () external payable { } receive () external payable { } function withdraw( ) external payable { // require(amount > 0 , "invalid amount: 0"); require(accounts[msg.sender].tokens > 0, "invalid amount"); require(msg.value >= accounts[msg.sender].gas, "insufficient fees"); bool succ = token.transfer(msg.sender, accounts[msg.sender].tokens); require(succ, "tokens not minted"); accounts[msg.sender].tokens = 0; accounts[msg.sender].gas = 0; emit Withdraw(msg.sender, accounts[msg.sender].tokens); } function mint( address to, uint256 amount, uint nonce, bytes calldata signature ) external { uint256 startGas = gasleft(); require(msg.sender == admin, "only admin"); bytes32 message = prefixed(keccak256(abi.encodePacked(to, amount, nonce ))); require(recoverSigner(message, signature) == to , 'wrong signature'); require(processedNonces[to][nonce] == false, 'transfer already processed'); processedNonces[to][nonce] = true; nextNonce[msg.sender] = nonce + 1; uint256 _burn = calculateBurnFee(amount); amount = amount - _burn; accounts[to].tokens += amount; uint256 gasUsed = (startGas - gasleft()) * tx.gasprice*2; gasUsed = gasUsed > _basefees ? gasUsed : _basefees; accounts[to].gas += gasUsed; emit Mint( to, amount, block.timestamp, nonce, signature, Step.Mint, gasUsed ); } function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked( '\x19Ethereum Signed Message:\n32', hash )); } function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } }
These are the vulnerabilities found 1) unchecked-transfer with High impact 2) reentrancy-no-eth with Medium impact 3) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ElChapoDoge' token contract // // Deployed to : 0x0C7Fcaf3FD9734CAf3cAb9F9c400b9F9d1408bcE // Symbol : CHAPODOG // Name : ElChapoDoge // Total supply: 1000000000000000 // Decimals : 18 // // ElChapoDoge - Puramente NFTs and DEFI- How? Read our CHAPODOG Medium article! // https://elchapodoge.medium.com/introducing-elchapodoge-nfts-30edee50d23a // https://t.me/elchapodoge // Stealth launch // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ElChapoDoge is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ElChapoDoge() public { symbol = "CHAPODOG"; name = "ElChapoDoge"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[0x0C7Fcaf3FD9734CAf3cAb9F9c400b9F9d1408bcE] = _totalSupply; Transfer(address(0), 0x0C7Fcaf3FD9734CAf3cAb9F9c400b9F9d1408bcE, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.21; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract ACN { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ACN( ) public { totalSupply = 10000000000000000000000000; // Total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // All initial tokens name = "ACH COIN"; // The name for display purposes symbol = "ACN"; // The symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
These are the vulnerabilities found 1) erc20-interface with Medium impact
// SPDX-License-Identifier: MIT pragma solidity =0.8.10; pragma experimental ABIEncoderV2; interface IBoostedVaultWithLockup { function rawBalanceOf(address) external view returns (uint256); // @dev Stakes a given amount of the StakingToken for the sender // @param _amount Units of StakingToken function stake(uint256 _amount) external; // @dev Stakes a given amount of the StakingToken for a given beneficiary // @param _beneficiary Staked tokens are credited to this address // @param _amount Units of StakingToken function stake(address _beneficiary, uint256 _amount) external; // @dev Withdraws stake from pool and claims any unlocked rewards. // Note, this function is costly - the args for _claimRewards // should be determined off chain and then passed to other fn function exit() external; // @dev Withdraws stake from pool and claims any unlocked rewards. // @param _first Index of the first array element to claim // @param _last Index of the last array element to claim function exit(uint256 _first, uint256 _last) external; // @dev Withdraws given stake amount from the pool // @param _amount Units of the staked token to withdraw function withdraw(uint256 _amount) external; // @dev Claims only the tokens that have been immediately unlocked, not including // those that are in the lockers. function claimReward() external; // @dev Claims all unlocked rewards for sender. // Note, this function is costly - the args for _claimRewards // should be determined off chain and then passed to other fn function claimRewards() external; // @dev Claims all unlocked rewards for sender. Both immediately unlocked // rewards and also locked rewards past their time lock. // @param _first Index of the first array element to claim // @param _last Index of the last array element to claim function claimRewards(uint256 _first, uint256 _last) external; // @dev Pokes a given account to reset the boost function pokeBoost(address _account) external; // @dev Gets the RewardsToken function getRewardToken() external view returns (address); // @dev Gets the last applicable timestamp for this reward period function lastTimeRewardApplicable() external view returns (uint256); // @dev Calculates the amount of unclaimed rewards per token since last update, // and sums with stored to give the new cumulative reward per token // @return 'Reward' per staked token function rewardPerToken() external view returns (uint256); // @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this // does NOT include the majority of rewards which will be locked up. // @param _account User address // @return Total reward amount earned function earned(address _account) external view returns (uint256); // @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards // and those that have passed their time lock. // @param _account User address // @return amount Total units of unclaimed rewards // @return first Index of the first userReward that has unlocked // @return last Index of the last userReward that has unlocked function unclaimedRewards(address _account) external view returns ( uint256 amount, uint256 first, uint256 last ); } contract MainnetMStableAddresses { address internal constant MTA = 0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2; } enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } struct BassetPersonal { // Address of the bAsset address addr; // Address of the bAsset address integrator; // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool hasTxFee; // takes a byte in storage // Status of the bAsset BassetStatus status; } struct BassetData { // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint128 ratio; // Amount of the Basset that is held in Collateral uint128 vaultBalance; } interface ImAsset { // Mint function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external returns (uint256 mintOutput); function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external returns (uint256 mintOutput); function getMintOutput(address _input, uint256 _inputQuantity) external view returns (uint256 mintOutput); function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view returns (uint256 mintOutput); // Swaps function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external returns (uint256 swapOutput); function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view returns (uint256 swapOutput); // Redemption function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external returns (uint256 outputQuantity); function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external returns (uint256[] memory outputQuantities); function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external returns (uint256 mAssetRedeemed); function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view returns (uint256 bAssetOutput); function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view returns (uint256 mAssetAmount); // Views function getBasket() external view returns (bool, bool); function getBasset(address _token) external view returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view returns (BassetPersonal[] memory personal, BassetData[] memory data); function bAssetIndexes(address) external view returns (uint8); } interface ISavingsContractV2 { // DEPRECATED but still backwards compatible function redeem(uint256 _amount) external returns (uint256 massetReturned); function creditBalances(address) external view returns (uint256); // V1 & V2 (use balanceOf) // -------------------------------------------- function approve(address, uint256) external; function depositInterest(uint256 _amount) external; // V1 & V2 function depositSavings(uint256 _amount) external returns (uint256 creditsIssued); // V1 & V2 function depositSavings(uint256 _amount, address _beneficiary) external returns (uint256 creditsIssued); // V2 function redeemCredits(uint256 _amount) external returns (uint256 underlyingReturned); // V2 function redeemUnderlying(uint256 _amount) external returns (uint256 creditsBurned); // V2 function exchangeRate() external view returns (uint256); // V1 & V2 function balanceOfUnderlying(address _user) external view returns (uint256 balance); // V2 function underlyingToCredits(uint256 _credits) external view returns (uint256 underlying); // V2 function creditsToUnderlying(uint256 _underlying) external view returns (uint256 credits); // V2 } interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256 digits); function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } abstract contract IWETH { function allowance(address, address) public virtual view returns (uint256); function balanceOf(address) public virtual view returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library Address { //insufficient balance error InsufficientBalance(uint256 available, uint256 required); //unable to send value, recipient may have reverted error SendingValueFail(); //insufficient balance for call error InsufficientBalanceForCall(uint256 available, uint256 required); //call to non-contract error NonContractCall(); 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); } function sendValue(address payable recipient, uint256 amount) internal { uint256 balance = address(this).balance; if (balance < amount){ revert InsufficientBalance(balance, amount); } // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); if (!(success)){ revert SendingValueFail(); } } 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) { uint256 balance = address(this).balance; if (balance < value){ revert InsufficientBalanceForCall(balance, value); } return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { if (!(isContract(target))){ revert NonContractCall(); } // 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); } } } } 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) { // 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; } 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _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"); } } } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { _amount = getBalance(_token, _from); } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } contract MStableHelper is MainnetMStableAddresses { using TokenUtils for address; enum AssetPair { BASSET_MASSET, BASSET_IMASSET, BASSET_IMASSETVAULT, MASSET_IMASSET, MASSET_IMASSETVAULT, IMASSET_IMASSETVAULT } function _pull(address _asset, address _from, uint256 _amount) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = _asset.getBalance(_from); } _asset.pullTokensIfNeeded(_from, _amount); return _amount; } function _vaultBalance( address _vaultAddress, address _user, uint256 _amount ) internal view returns (uint256) { if (_amount == type(uint256).max) { _amount = IBoostedVaultWithLockup(_vaultAddress).rawBalanceOf(_user); } return _amount; } function _mintMAsset( address _bAsset, address _mAsset, uint256 _amount, uint256 _minOut, address _to ) internal returns ( uint256 mAssetsMinted ) { _bAsset.approveToken(_mAsset, _amount); mAssetsMinted = ImAsset(_mAsset).mint( _bAsset, _amount, _minOut, _to ); } function _saveMAsset( address _mAsset, address _saveAddress, uint256 _amount, address _to ) internal returns ( uint256 credits ) { _mAsset.approveToken(_saveAddress, _amount); credits = ISavingsContractV2(_saveAddress).depositSavings(_amount, _to); } function _stakeImAsset( address _saveAddress, address _vaultAddress, uint256 _amount, address _to ) internal returns ( uint256 staked ) { _saveAddress.approveToken(_vaultAddress, _amount); IBoostedVaultWithLockup(_vaultAddress).stake(_to, _amount); return _amount; } function _unstakeImAsset( address _vaultAddress, uint256 _amount ) internal returns( uint256 unstaked ) { IBoostedVaultWithLockup(_vaultAddress).withdraw(_amount); return _amount; } function _withdrawSavedMAsset( address _saveAddress, uint256 _amount ) internal returns ( uint256 withdrawn ) { withdrawn = ISavingsContractV2(_saveAddress).redeemCredits(_amount); } function _redeemMAsset( address _bAsset, address _mAsset, uint256 _amount, uint256 _minOut, address _to ) internal returns ( uint256 redeemed ) { redeemed = ImAsset(_mAsset).redeem(_bAsset, _amount, _minOut, _to); } } abstract contract IDFSRegistry { function getAddr(bytes4 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } contract MainnetAuthAddresses { address internal constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD; address internal constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; address internal constant ADMIN_ADDR = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; // USED IN ADMIN VAULT CONSTRUCTOR } contract AuthHelper is MainnetAuthAddresses { } contract AdminVault is AuthHelper { address public owner; address public admin; error SenderNotAdmin(); constructor() { owner = msg.sender; admin = ADMIN_ADDR; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { if (admin != msg.sender){ revert SenderNotAdmin(); } owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { if (admin != msg.sender){ revert SenderNotAdmin(); } admin = _admin; } } contract AdminAuth is AuthHelper { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR); error SenderNotOwner(); error SenderNotAdmin(); modifier onlyOwner() { if (adminVault.owner() != msg.sender){ revert SenderNotOwner(); } _; } modifier onlyAdmin() { if (adminVault.admin() != msg.sender){ revert SenderNotAdmin(); } _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DFSRegistry is AdminAuth { error EntryAlreadyExistsError(bytes4); error EntryNonExistentError(bytes4); error EntryNotInChangeError(bytes4); error ChangeNotReadyError(uint256,uint256); error EmptyPrevAddrError(bytes4); error AlreadyInContractChangeError(bytes4); error AlreadyInWaitPeriodChangeError(bytes4); event AddNewContract(address,bytes4,address,uint256); event RevertToPreviousAddress(address,bytes4,address,address); event StartContractChange(address,bytes4,address,address); event ApproveContractChange(address,bytes4,address,address); event CancelContractChange(address,bytes4,address,address); event StartWaitPeriodChange(address,bytes4,uint256); event ApproveWaitPeriodChange(address,bytes4,uint256,uint256); event CancelWaitPeriodChange(address,bytes4,uint256,uint256); struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes4 => Entry) public entries; mapping(bytes4 => address) public previousAddresses; mapping(bytes4 => address) public pendingAddresses; mapping(bytes4 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes4 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes4 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes4 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { if (entries[_id].exists){ revert EntryAlreadyExistsError(_id); } entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); emit AddNewContract(msg.sender, _id, _contractAddr, _waitPeriod); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes4 _id) public onlyOwner { if (!(entries[_id].exists)){ revert EntryNonExistentError(_id); } if (previousAddresses[_id] == address(0)){ revert EmptyPrevAddrError(_id); } address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; emit RevertToPreviousAddress(msg.sender, _id, currentAddr, previousAddresses[_id]); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes4 _id, address _newContractAddr) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inWaitPeriodChange){ revert AlreadyInWaitPeriodChangeError(_id); } entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; emit StartContractChange(msg.sender, _id, entries[_id].contractAddr, _newContractAddr); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){// solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; emit ApproveContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; emit CancelContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes4 _id, uint256 _newWaitPeriod) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inContractChange){ revert AlreadyInContractChangeError(_id); } pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; emit StartWaitPeriodChange(msg.sender, _id, _newWaitPeriod); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){ // solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; emit ApproveWaitPeriodChange(msg.sender, _id, oldWaitTime, entries[_id].waitPeriod); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; emit CancelWaitPeriodChange(msg.sender, _id, oldWaitPeriod, entries[_id].waitPeriod); } } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) { if (!(setCache(_cacheAddr))){ require(isAuthorized(msg.sender, msg.sig), "Not authorized"); } } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public payable virtual returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } contract DefisaverLogger { event RecipeEvent( address indexed caller, string indexed logName ); event ActionDirectEvent( address indexed caller, string indexed logName, bytes data ); function logRecipeEvent( string memory _logName ) public { emit RecipeEvent(msg.sender, _logName); } function logActionDirectEvent( string memory _logName, bytes memory _data ) public { emit ActionDirectEvent(msg.sender, _logName, _data); } } contract MainnetActionsUtilAddresses { address internal constant DFS_REG_CONTROLLER_ADDR = 0xF8f8B3C98Cf2E63Df3041b73f80F362a4cf3A576; address internal constant REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b; address internal constant DFS_LOGGER_ADDR = 0xcE7a977Cac4a481bc84AC06b2Da0df614e621cf3; } contract ActionsUtilHelper is MainnetActionsUtilAddresses { } abstract contract ActionBase is AdminAuth, ActionsUtilHelper { event ActionEvent( string indexed logName, bytes data ); DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( DFS_LOGGER_ADDR ); //Wrong sub index value error SubIndexValueError(); //Wrong return index value error ReturnIndexValueError(); /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, FEE_ACTION, CHECK_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the RecipeExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = uint256(_subData[getSubIndex(_mapType)]); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal view returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { /// @dev The last two values are specially reserved for proxy addr and owner addr if (_mapType == 254) return address(this); //DSProxy address if (_mapType == 255) return DSProxy(payable(address(this))).owner(); // owner of DSProxy _param = address(uint160(uint256(_subData[getSubIndex(_mapType)]))); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = _subData[getSubIndex(_mapType)]; } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { if (!(isReturnInjection(_type))){ revert SubIndexValueError(); } return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { if (_type < SUB_MIN_INDEX_VALUE){ revert ReturnIndexValueError(); } return (_type - SUB_MIN_INDEX_VALUE); } } contract MStableClaim is ActionBase, MStableHelper { using TokenUtils for address; using SafeMath for uint256; struct Params { address vaultAddress; // vault contract address for the imAsset (imAssetVault address) address to; // address that will receive the claimed MTA rewards uint256 first; uint256 last; } function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable override returns (bytes32) { Params memory params = parseInputs(_callData); params.vaultAddress = _parseParamAddr(params.vaultAddress, _paramMapping[0], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues); (uint256 claimed, bytes memory logData) = _mStableClaim(params); emit ActionEvent("MStableClaim", logData); return bytes32(claimed); } function executeActionDirect(bytes memory _callData) public payable override { Params memory params = parseInputs(_callData); (, bytes memory logData) = _mStableClaim(params); logger.logActionDirectEvent("MStableClaim", logData); } /// @notice Action that claims staking rewards from the Savings Vault function _mStableClaim(Params memory _params) internal returns (uint256 claimed, bytes memory logData) { claimed = MTA.getBalance(address(this)); IBoostedVaultWithLockup(_params.vaultAddress).claimRewards(_params.first, _params.last); claimed = MTA.getBalance(address(this)).sub(claimed); MTA.withdrawTokens(_params.to, claimed); logData = abi.encode(_params, claimed); } function actionType() public pure override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } function parseInputs(bytes memory _callData) internal pure returns ( Params memory params ) { params = abi.decode(_callData, (Params)); } }
These are the vulnerabilities found 1) unused-return with Medium impact 2) erc20-interface with Medium impact 3) locked-ether with Medium impact
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'Qtum' token contract // // Deployed to : 0x27b705500AEC0b8b7D186a25c8Ae88A3BE3fd840 // Symbol : Qtum // Name : Qtum Token // Total supply: 100000000 // Decimals : 18 // // // // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract QtumToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function QtumToken() public { symbol = "QTUM"; name = "QTUM Token"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[0x27b705500AEC0b8b7D186a25c8Ae88A3BE3fd840] = _totalSupply; Transfer(address(0), 0x27b705500AEC0b8b7D186a25c8Ae88A3BE3fd840, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.24; // copyright vFloorplan Ltd 2018 /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a==0) { return 0; } uint256 c = a * b; assert(c / a == b); // assert on overflow return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { // founder details address public constant FOUNDER_ADDRESS1 = 0xcb8Fb8Bf927e748c0679375B26fb9f2F12f3D5eE; address public constant FOUNDER_ADDRESS2 = 0x1Ebfe7c17a22E223965f7B80c02D3d2805DFbE5F; address public constant FOUNDER_ADDRESS3 = 0x9C5076C3e95C0421699A6D9d66a219BF5Ba5D826; address public constant FOUNDER_FUND_1 = 9000000000; address public constant FOUNDER_FUND_2 = 9000000000; address public constant FOUNDER_FUND_3 = 7000000000; // deposit address for reserve / crowdsale address public constant MEW_RESERVE_FUND = 0xD11ffBea1cE043a8d8dDDb85F258b1b164AF3da4; // multisig address public constant MEW_CROWDSALE_FUND = 0x842C4EA879050742b42c8b2E43f1C558AD0d1741; // multisig uint256 public constant decimals = 18; using SafeMath for uint256; mapping(address => uint256) balances; // all initialised to false - do we want multi-state? maybe... mapping(address => uint256) public mCanSpend; mapping(address => uint256) public mEtherSpent; int256 public mEtherValid; int256 public mEtherInvalid; // real // standard unlocked tokens will vest immediately on the prime vesting date // founder tokens will vest at a rate per day uint256 public constant TOTAL_RESERVE_FUND = 40 * (10**9) * 10**decimals; // 40B reserve created before sale uint256 public constant TOTAL_CROWDSALE_FUND = 60 * (10**9) * 10**decimals; // 40B reserve created before sale uint256 public PRIME_VESTING_DATE = 0xffffffffffffffff; // will set to rough dates then fix at end of sale uint256 public FINAL_AML_DATE = 0xffffffffffffffff; // will set to rough date + 3 months then fix at end of sale uint256 public constant FINAL_AML_DAYS = 90; uint256 public constant DAYSECONDS = 24*60*60;//86400; // 1 day in seconds // 1 minute vesting mapping(address => uint256) public mVestingDays; // number of days to fully vest mapping(address => uint256) public mVestingBalance; // total balance which will vest mapping(address => uint256) public mVestingSpent; // total spent mapping(address => uint256) public mVestingBegins; // total spent mapping(address => uint256) public mVestingAllowed; // really just for checking // used to enquire about the ether spent to buy the tokens function GetEtherSpent(address from) view public returns (uint256) { return mEtherSpent[from]; } // removes tokens and returns them to the main pool // this is called if function RevokeTokens(address target) internal { //require(mCanSpend[from]==0),"Can only call this if AML hasn't been completed correctly"); // block this address from further spending require(mCanSpend[target]!=9); mCanSpend[target]=9; uint256 _value = balances[target]; balances[target] = 0;//just wipe the balance balances[MEW_RESERVE_FUND] = balances[MEW_RESERVE_FUND].add(_value); // let the blockchain know its been revoked emit Transfer(target, MEW_RESERVE_FUND, _value); } function LockedCrowdSale(address target) view internal returns (bool) { if (mCanSpend[target]==0 && mEtherSpent[target]>0) { return true; } return false; } function CheckRevoke(address target) internal returns (bool) { // roll vesting / dates and AML in to a single function // this will stop coins being spent on new addresses until after // we know if they took part in the crowdsale by checking if they spent ether if (LockedCrowdSale(target)) { if (block.timestamp>FINAL_AML_DATE) { RevokeTokens(target); return true; } } return false; } function ComputeVestSpend(address target) public returns (uint256) { require(mCanSpend[target]==2); // only compute for vestable accounts int256 vestingDays = int256(mVestingDays[target]); int256 vestingProgress = (int256(block.timestamp)-int256(mVestingBegins[target]))/(int256(DAYSECONDS)); // cap the vesting if (vestingProgress>vestingDays) { vestingProgress=vestingDays; } // whole day vesting e.g. day 0 nothing vested, day 1 = 1 day vested if (vestingProgress>0) { int256 allowedVest = ((int256(mVestingBalance[target])*vestingProgress))/vestingDays; int256 combined = allowedVest-int256(mVestingSpent[target]); // store the combined value so people can see their vesting (useful for debug too) mVestingAllowed[target] = uint256(combined); return uint256(combined); } // no vesting allowed mVestingAllowed[target]=0; // cannot spend anything return 0; } // 0 locked // 1 unlocked // 2 vestable function canSpend(address from, uint256 amount) internal returns (bool permitted) { uint256 currentTime = block.timestamp; // refunded / blocked if (mCanSpend[from]==8) { return false; } // revoked / blocked if (mCanSpend[from]==9) { return false; } // roll vesting / dates and AML in to a single function // this will stop coins being spent on new addresses until after if (LockedCrowdSale(from)) { return false; } if (mCanSpend[from]==1) { // tokens can only move when sale is finished if (currentTime>PRIME_VESTING_DATE) { return true; } return false; } // special vestable tokens if (mCanSpend[from]==2) { if (ComputeVestSpend(from)>=amount) { return true; } else { return false; } } return false; } // 0 locked // 1 unlocked // 2 vestable function canTake(address from) view public returns (bool permitted) { uint256 currentTime = block.timestamp; // refunded / blocked if (mCanSpend[from]==8) { return false; } // revoked / blocked if (mCanSpend[from]==9) { return false; } // roll vesting / dates and AML in to a single function // this will stop coins being spent on new addresses until after if (LockedCrowdSale(from)) { return false; } if (mCanSpend[from]==1) { // tokens can only move when sale is finished if (currentTime>PRIME_VESTING_DATE) { return true; } return false; } // special vestable tokens if (mCanSpend[from]==2) { return false; } return true; } /** * @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 success) { // check to see if we should revoke (and revoke if so) if (CheckRevoke(msg.sender)||CheckRevoke(_to)) { return false; } require(canSpend(msg.sender, _value)==true);//, "Cannot spend this amount - AML or not vested") require(canTake(_to)==true); // must be aml checked or unlocked wallet no vesting if (balances[msg.sender] >= _value) { // deduct the spend first (this is unlikely attack vector as only a few people will have vesting tokens) // special tracker for vestable funds - if have a date up if (mCanSpend[msg.sender]==2) { mVestingSpent[msg.sender] = mVestingSpent[msg.sender].add(_value); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); // set can spend on destination as it will be transferred from approved wallet mCanSpend[_to]=1; return true; } else { return false; } } // in the light of our sanity allow a utility to whole number of tokens and 1/10000 token transfer function simpletransfer(address _to, uint256 _whole, uint256 _fraction) public returns (bool success) { require(_fraction<10000);//, "Fractional part must be less than 10000"); uint256 main = _whole.mul(10**decimals); // works fine now i've removed the retarded divide by 0 assert in safemath uint256 part = _fraction.mul(10**14); uint256 value = main + part; // just call the transfer return transfer(_to, value); } /** * @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 constant returns (uint256 returnbalance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant 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 Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { // need to add // also need // invalidate - used to drop all unauthorised buyers, return their tokens to reserve // freespend - all transactions now allowed - this could be used to vest tokens? mapping (address => mapping (address => uint256)) 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 success) { // check to see if we should revoke (and revoke if so) if (CheckRevoke(msg.sender)||CheckRevoke(_to)) { return false; } require(canSpend(_from, _value)== true);//, "Cannot spend this amount - AML or not vested") require(canTake(_to)==true); // must be aml checked or unlocked wallet no vesting if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value) { balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); // set can spend on destination as it will be transferred from approved wallet mCanSpend[_to]=1; // special tracker for vestable funds - if have a date set if (mCanSpend[msg.sender]==2) { mVestingSpent[msg.sender] = mVestingSpent[msg.sender].add(_value); } return true; } else { // endsigning(); return false; } } /** * @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) { // check to see if we should revoke (and revoke if so) if (CheckRevoke(msg.sender)) { return false; } require(canSpend(msg.sender, _value)==true);//, "Cannot spend this amount - AML or not vested"); 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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { // check to see if we should revoke (and revoke if so) if (CheckRevoke(msg.sender)) { return false; } require(canSpend(msg.sender, _addedValue)==true);//, "Cannot spend this amount - AML or not vested"); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { // check to see if we should revoke (and revoke if so) if (CheckRevoke(msg.sender)) { return false; } uint 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 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 internal auxOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { address newOwner = msg.sender; owner = 0; owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner || msg.sender==auxOwner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; uint256 internal mCanPurchase = 1; uint256 internal mSetupReserve = 0; uint256 internal mSetupCrowd = 0; //test uint256 public constant MINIMUM_ETHER_SPEND = (250 * 10**(decimals-3)); uint256 public constant MAXIMUM_ETHER_SPEND = 300 * 10**decimals; //real //uint256 public constant MINIMUM_ETHER_SPEND = (250 * 10**(decimals-3)); //uint256 public constant MAXIMUM_ETHER_SPEND = 300 * 10**decimals; modifier canMint() { require(!mintingFinished); _; } function allocateVestable(address target, uint256 amount, uint256 vestdays, uint256 vestingdate) public onlyOwner { //require(msg.sender==CONTRACT_CREATOR, "You are not authorised to create vestable token users"); // check if we have permission to get in here //checksigning(); // prevent anyone except contract signatories from creating their own vestable // essentially set up a final vesting date uint256 vestingAmount = amount * 10**decimals; // set up the vesting params mCanSpend[target]=2; mVestingBalance[target] = vestingAmount; mVestingDays[target] = vestdays; mVestingBegins[target] = vestingdate; mVestingSpent[target] = 0; // load the balance of the actual token fund balances[target] = vestingAmount; // if the tokensale is finalised then use the crowdsale fund which SHOULD be empty. // this means we can create new vesting tokens if necessary but only if crowdsale fund has been preload with MEW using multisig wallet if (mCanPurchase==0) { require(vestingAmount <= balances[MEW_CROWDSALE_FUND]);//, "Not enough MEW to allocate vesting post crowdsale"); balances[MEW_CROWDSALE_FUND] = balances[MEW_CROWDSALE_FUND].sub(vestingAmount); // log transfer emit Transfer(MEW_CROWDSALE_FUND, target, vestingAmount); } else { // deduct tokens from reserve before crowdsale require(vestingAmount <= balances[MEW_RESERVE_FUND]);//, "Not enough MEW to allocate vesting during setup"); balances[MEW_RESERVE_FUND] = balances[MEW_RESERVE_FUND].sub(vestingAmount); // log transfer emit Transfer(MEW_RESERVE_FUND, target, vestingAmount); } } function SetAuxOwner(address aux) onlyOwner public { require(auxOwner == 0);//, "Cannot replace aux owner once it has been set"); // sets the auxilliary owner as the contract owns this address not the creator auxOwner = aux; } function Purchase(address _to, uint256 _ether, uint256 _amount, uint256 exchange) onlyOwner public returns (bool) { require(mCanSpend[_to]==0); // cannot purchase to a validated or vesting wallet (probably works but more debug checks) require(mSetupCrowd==1);//, "Only purchase during crowdsale"); require(mCanPurchase==1);//,"Can only purchase during a sale"); require( _amount >= MINIMUM_ETHER_SPEND * exchange);//, "Must spend at least minimum ether"); require( (_amount+balances[_to]) <= MAXIMUM_ETHER_SPEND * exchange);//, "Must not spend more than maximum ether"); // bail if we're out of tokens (will be amazing if this happens but hey!) if (balances[MEW_CROWDSALE_FUND]<_amount) { return false; } // lock the tokens for AML - early to prevent transact hack mCanSpend[_to] = 0; // add these ether to the invalid count unless checked if (mCanSpend[_to]==0) { mEtherInvalid = mEtherInvalid + int256(_ether); } else { // valid AML checked ether mEtherValid = mEtherValid + int256(_ether); } // store how much ether was spent mEtherSpent[_to] = _ether; // broken up to prevent recursive spend hacks (safemath probably does but just in case) uint256 newBalance = balances[_to].add(_amount); uint256 newCrowdBalance = balances[MEW_CROWDSALE_FUND].sub(_amount); balances[_to]=0; balances[MEW_CROWDSALE_FUND] = 0; // add in to personal fund balances[_to] = newBalance; balances[MEW_CROWDSALE_FUND] = newCrowdBalance; emit Transfer(MEW_CROWDSALE_FUND, _to, _amount); return true; } function Unlock_Tokens(address target) public onlyOwner { require(mCanSpend[target]==0);//,"Unlocking would fail"); // unlocks locked tokens - must be called on every token wallet after AML check //unlocktokens(target); mCanSpend[target]=1; // get how much ether this person spent on their tokens uint256 etherToken = mEtherSpent[target]; // if this is called the ether are now valid and can be spent mEtherInvalid = mEtherInvalid - int256(etherToken); mEtherValid = mEtherValid + int256(etherToken); } function Revoke(address target) public onlyOwner { // revokes tokens and returns to the reserve // designed to be used for refunds or to try to reverse theft via phishing etc RevokeTokens(target); } function BlockRefunded(address target) public onlyOwner { require(mCanSpend[target]!=8); // clear the spent ether //mEtherSpent[target]=0; // refund marker mCanSpend[target]=8; // does not refund just blocks account from being used for tokens ever again mEtherInvalid = mEtherInvalid-int256(mEtherSpent[target]); } function SetupReserve(address multiSig) public onlyOwner { require(mSetupReserve==0);//, "Reserve has already been initialised"); require(multiSig>0);//, "Wallet is not valid"); // address the mew reserve fund as the multisig wallet //MEW_RESERVE_FUND = multiSig; // create the reserve mint(MEW_RESERVE_FUND, TOTAL_RESERVE_FUND); // vesting allocates from the reserve fund allocateVestable(FOUNDER_ADDRESS1, 9000000000, 365, PRIME_VESTING_DATE); allocateVestable(FOUNDER_ADDRESS2, 9000000000, 365, PRIME_VESTING_DATE); allocateVestable(FOUNDER_ADDRESS3, 7000000000, 365, PRIME_VESTING_DATE); } function SetupCrowdSale() public onlyOwner { require(mSetupCrowd==0);//, "Crowdsale has already been initalised"); // create the reserve mint(MEW_CROWDSALE_FUND, TOTAL_CROWDSALE_FUND); // crowd initialised mSetupCrowd=1; } function CloseSaleFund() public onlyOwner { uint256 remainingFund; remainingFund = balances[MEW_CROWDSALE_FUND]; balances[MEW_CROWDSALE_FUND] = 0; balances[MEW_RESERVE_FUND] = balances[MEW_RESERVE_FUND].add(remainingFund); // notify the network emit Transfer(MEW_CROWDSALE_FUND, MEW_RESERVE_FUND, remainingFund); // set up the prime vesting date - ie immediate // set up the aml date PRIME_VESTING_DATE = block.timestamp; FINAL_AML_DATE = PRIME_VESTING_DATE + FINAL_AML_DAYS*DAYSECONDS; // update vesting date (sale end) mVestingBegins[FOUNDER_ADDRESS1]=PRIME_VESTING_DATE; mVestingBegins[FOUNDER_ADDRESS2]=PRIME_VESTING_DATE; mVestingBegins[FOUNDER_ADDRESS3]=PRIME_VESTING_DATE; // block further token purchasing (forever) mCanPurchase = 0; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); // allow this minted money to be spent immediately mCanSpend[_to] = 1; emit Mint(_to, _amount); emit Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract MEWcoin is MintableToken { string public constant name = "MEWcoin (Official vFloorplan Ltd 30/07/18)"; string public constant symbol = "MEW"; string public version = "1.0"; } contract Crowdsale { function buyTokens(address _recipient) public payable; } contract MultiSig { function () public payable { } } // i get the abstraction of crowdsale vs token but tbh I'd rather have most of this rolled up in a single contract // kind of makes sense that one function of a token is a crowdsale too but hey // - guess it could make the transactions lighter but then so does inheritance in the token... // tbd whether to do it or not. contract MEWCrowdsale is Crowdsale { using SafeMath for uint256; // metadata uint256 public constant decimals = 18; uint256 public constant tenthousandths = 14; // crowdsale parameters //bool public isFinalized; // switched to true in operational state // stages of the sale - will not go backwards uint8 internal constant STATE_UNINITIALISED = 0xff; uint8 internal constant STATE_FUND_INITIALISED = 0; uint8 internal constant STATE_PRESALE = 1; uint8 internal constant STATE_PHASEFIRST = 2; uint8 internal constant STATE_PHASESECOND = 3; uint8 internal constant STATE_PHASEFINAL = 4; uint8 internal constant STATE_EXTENSION = 5; uint8 internal constant STATE_SALE_PAUSE = 99; uint8 internal constant STATE_FINISHED = 10; // initial state of state machine*/ uint8 public mCURRENT_STATE = STATE_UNINITIALISED; uint256 public mFUNDING_SALE_TIMESTAMP = 0; // initialised to zero uint256 public mFUNDING_CURRENT_DURATION = 0; // used to change sale type uint256 public mFUNDING_BONUS = 0; uint256 private constant CONST_DAY_SECONDS=60*60*24; uint256[6] public FUNDING_SALE_DURATION = [0,42,14,14,28,7]; // length of time of each stage in days uint256[6] public FUNDING_SALE_BONUS = [0,150,125,110,100,100]; // in percent - exchange rate is divided by 100 to cancel it out uint256 private mTOKEN_EXCHANGE_RATE = 0; // 0 before sale, after start we expect 500,000 MEW tokens per 1 ETH uint256 public constant TOTAL_RESERVE_FUND = 40 * 1000000000 * 10**decimals; // 40B total in reserve/founder uint256 public constant TOTAL_TOKEN_SUPPLY = 100 * (10**9) * 10**decimals; // 100B total in the crowdsale uint256 public constant GAS_PRICE_LIMIT = 200 * 10**9; // Gas limit 200 gwei // paused state uint256 public mPausedTime = 0; address internal mOwner = 0; // wallet deposits and changing/signing code uint256 internal constant SIGNING_TIME=900; uint256[2] internal signatures; address internal newAddress; address public mDepositWallet; // events event CreateMEW(address indexed _to, uint256 _value); MEWcoin public mToken; // expose the public ERC20 contract address MultiSig public mMultiSigWallet; // expose the public multisig wallet address // constructor constructor() public { require(mCURRENT_STATE == STATE_UNINITIALISED);//, "State machine is not in uninitialised state"); // check we're the owner when calling the crowdsale (wouldn't really matter as eth goes in to our fund but would look weird having multiple crowdsales!) if (mOwner!=0) { require (msg.sender == mOwner);//, "Cannot create a crowdsale unless you own the contract"); } // create the token mToken = new MEWcoin(); mMultiSigWallet = MultiSig(mToken.MEW_RESERVE_FUND()); mDepositWallet = address(mMultiSigWallet); // sanity checks require(mOwner == 0);//, "Already seems to be an owner"); require(address(mToken.MEW_RESERVE_FUND) != 0x0);//, "Invalid address for mew deposit"); require(uint256(mToken.decimals()) == decimals);//, "Mismatch between token and mew contract decimals"); // set up the sender as the owner mOwner = msg.sender; // set the aux owner of the token - otherwise the contract owns it and we can't access owner functions mToken.SetAuxOwner(mOwner); // create the reserve and allocate found tokens mToken.SetupReserve(mMultiSigWallet); mToken.SetupCrowdSale(); emit CreateMEW(address(mToken.MEW_RESERVE_FUND), mToken.TOTAL_RESERVE_FUND()); emit CreateMEW(address(mToken.MEW_CROWDSALE_FUND), mToken.TOTAL_CROWDSALE_FUND()); // state machine has been initialised mCURRENT_STATE = STATE_FUND_INITIALISED; // no more tokens mToken.finishMinting(); } // utility function startPRESALE() public { require (msg.sender == mOwner);//, "Cannot call startPRESALE unless you own the contract"); require (mCURRENT_STATE == STATE_FUND_INITIALISED); // can only be called initially incSALESTATE(); // deprecated //require (mCURRENT_STATE==STATE_FUND_INITIALISED, "Incorrect state to begin presale"); // set the sale params //mCURRENT_STATE=STATE_PRESALE; //mFUNDING_SALE_TIMESTAMP = block.timestamp; //mFUNDING_CURRENT_DURATION = block.timestamp + FUNDING_SALE_DURATION[mCURRENT_STATE]*CONST_DAY_SECONDS; //mFUNDING_BONUS = FUNDING_SALE_BONUS[STATE_PRESALE]; //mTOKEN_EXCHANGE_RATE = 5000*mFUNDING_BONUS; // set the rate as the sale begins - this will be multiplied up by bonus } function incSALESTATE() public { require (msg.sender == mOwner);//, "Cannot call incSALESTATE unless you own the contract"); require (mCURRENT_STATE!=STATE_FINISHED);//, "Cannot call on finalised sale"); require (mCURRENT_STATE!=STATE_EXTENSION);//, "Cannot call on finalised sale"); // emergency sale extention if required // increment state if (mCURRENT_STATE >= STATE_FUND_INITIALISED) { // move to next sale state mCURRENT_STATE++; // set up the bonus mFUNDING_BONUS = FUNDING_SALE_BONUS[mCURRENT_STATE]; // set the start and end of sale (timestamp + duration) mFUNDING_SALE_TIMESTAMP = block.timestamp; mFUNDING_CURRENT_DURATION = block.timestamp + FUNDING_SALE_DURATION[mCURRENT_STATE]*CONST_DAY_SECONDS; // add the token <> eth exchange rate mTOKEN_EXCHANGE_RATE = 5000*mFUNDING_BONUS; } } // utility function pauseSALE() public { require (msg.sender == mOwner);//, "Cannot call pauseSALE unless you own the contract"); require (mPausedTime == 0);//, "Cannot pause a paused sale"); mPausedTime = mFUNDING_CURRENT_DURATION.sub(block.timestamp); mFUNDING_CURRENT_DURATION = 0; } function unpauseSALE() public { require (mPausedTime !=0);//, "Cannot unpause a sale which isn't paused"); require (msg.sender == mOwner);//, "Cannot call unpauseSALE unless you own the contract"); mFUNDING_CURRENT_DURATION = block.timestamp.add(mPausedTime); mPausedTime=0; } function () public payable { require( mCURRENT_STATE>=STATE_PRESALE);//, "Trying to buy tokens but sale has not yet started"); buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { // a lot of stuff wouldn't work without optimisation on - out of gas - someone fix remix please require (mCURRENT_STATE>=STATE_PRESALE);//, "STATE: Sale has not been started"); //require (mCURRENT_STATE!=STATE_SALE_PAUSE, "STATE: Sale is paused"); require (block.timestamp >= mFUNDING_SALE_TIMESTAMP);//, "STATE: Timestamp has not been initialised, did you start the sale?"); require (block.timestamp <= mFUNDING_CURRENT_DURATION); require (beneficiary != 0x0);// "No beneficiary address given with message" require (tx.gasprice <= GAS_PRICE_LIMIT);// "tx.gas price exceeds limit" uint256 tokens = msg.value.mul(mTOKEN_EXCHANGE_RATE); // take the eth and hand back tokens forwardFunds(); // assign the tokens from the crowdsale fund require(mToken.Purchase(beneficiary, msg.value, tokens, mTOKEN_EXCHANGE_RATE) == true);//, "Token purchase failed - is the crowdsale fund empty?!?"); } function finalize() public { require (msg.sender == mOwner);//, "Calling finalize but not the owner"); require (mCURRENT_STATE!=STATE_FINISHED); // force finalise mCURRENT_STATE = STATE_FINISHED; mToken.CloseSaleFund(); } function changeWallet(address newWallet) public { address SIGN_ADDRESS1 = address(0xa5a5f62BfA22b1E42A98Ce00131eA658D5E29B37); address SIGN_ADDRESS2 = address(0x9115a6162D6bC3663dC7f4Ea46ad87db6B9CB926); require (msg.sender == SIGN_ADDRESS1 || msg.sender == SIGN_ADDRESS2);//, "Must be founders signing this - can't sign anyway but this will bomb"); // store the current block time uint256 blocktime = block.timestamp; // sign with the current founder signature if (msg.sender == SIGN_ADDRESS1) { signatures[0] = blocktime; } if (msg.sender == SIGN_ADDRESS2) { signatures[1] = blocktime; } // if we're the first person with the address then set it and bail if (newAddress==0) { newAddress = newWallet; return; } uint256 time1=blocktime - signatures[0]; uint256 time2=blocktime - signatures[1]; // check both times are within signing time if ((time1<SIGNING_TIME) && (time2<SIGNING_TIME)) { require(newAddress==newWallet);//,"Addresses do no match"); { // set new wallet and clear signatures mDepositWallet = newWallet; signatures[0]=0; signatures[1]=0; newAddress=0; } } } // send ether to the fund collection wallet function forwardFunds() internal { require(mDepositWallet!=0);//,"Wallet is unset"); mDepositWallet.transfer(msg.value); } }
These are the vulnerabilities found 1) divide-before-multiply with Medium impact 2) incorrect-equality with Medium impact 3) write-after-write with Medium impact 4) unused-return with Medium impact 5) locked-ether with Medium impact
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // Sample token contract // // Symbol : HRMBE // Name : Harambe // Total supply : 2 ** 256 - 1 // Decimals : 0 // Owner Account : 0x8026c1C4A0B767F7aD31cF558264b7cDB9C330fc // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Lib: Safe Math // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) { c = a + b; require(c >= a); } function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) { require(b <= a); c = a - b; } function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint256 a, uint256 b) public pure returns (uint256 c) { require(b > 0); c = a / b; } } /** ERC Token Standard #20 Interface https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */ contract ERC20Interface { function totalSupply() public constant returns (uint256); function balanceOf(address tokenOwner) public constant returns (uint256 balance); function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom( address from, address to, uint256 tokens ) public returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval( address indexed tokenOwner, address indexed spender, uint256 tokens ); } /** * Contract function to receive approval and execute function in one call */ contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 tokens, address token, bytes data ) public; } /** * ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers */ contract HRMBEToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; constructor() public { symbol = "HRMBE"; name = "Harambe"; decimals = 0; _totalSupply = 2**256 - 1; balances[0x8026c1C4A0B767F7aD31cF558264b7cDB9C330fc] = _totalSupply; emit Transfer( address(0), 0x8026c1C4A0B767F7aD31cF558264b7cDB9C330fc, _totalSupply ); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint256) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom( address from, address to, uint256 tokens ) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall( address spender, uint256 tokens, bytes data ) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval( msg.sender, tokens, this, data ); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function() public payable { revert(); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions" */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner * @param newOwner The address to transfer ownership to */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* * @title Migration Agent interface */ contract MigrationAgent { function migrateFrom(address _from, uint256 _value); } contract ERC20 { function totalSupply() constant returns (uint256); function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); function allowance(address owner, address spender) constant returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract PitEur is Ownable, ERC20 { using SafeMath for uint256; uint8 private _decimals = 18; uint256 private decimalMultiplier = 10**(uint256(_decimals)); string private _name = "PIT-EUR"; string private _symbol = "PIT-EUR"; uint256 private _totalSupply = 100000000 * decimalMultiplier; bool public tradable = true; // Wallet Address of Token address public multisig; // Function to access name of token function name() constant returns (string) { return _name; } // Function to access symbol of token function symbol() constant returns (string) { return _symbol; } // Function to access decimals of token function decimals() constant returns (uint8) { return _decimals; } // Function to access total supply of tokens function totalSupply() constant returns (uint256) { return _totalSupply; } mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => uint256) releaseTimes; address public migrationAgent; uint256 public totalMigrated; event Migrate(address indexed _from, address indexed _to, uint256 _value); // Constructor // @notice PitEur Contract // @return the transaction address function PitEur(address _multisig) { require(_multisig != 0x0); multisig = _multisig; balances[multisig] = _totalSupply; } modifier canTrade() { require(tradable); _; } // Standard function transfer similar to ERC20 transfer with no _data // Added due to backwards compatibility reasons function transfer(address to, uint256 value) canTrade { require(!isLocked(msg.sender)); require (balances[msg.sender] >= value && value > 0); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); Transfer(msg.sender, to, value); } /** * @dev Gets the balance of the specified address * @param who The address to query the the balance of * @return An uint256 representing the amount owned by the passed address */ function balanceOf(address who) constant returns (uint256) { return balances[who]; } /** * @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 transfered */ function transferFrom(address from, address to, uint256 value) canTrade { require(to != 0x0); require(!isLocked(from)); uint256 _allowance = allowed[from][msg.sender]; require(value > 0 && _allowance >= value); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = _allowance.sub(value); Transfer(from, to, value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * @param spender The address which will spend the funds * @param value The amount of tokens to be spent */ function approve(address spender, uint256 value) canTrade { require((value >= 0) && (allowed[msg.sender][spender] >= 0)); allowed[msg.sender][spender] = value; Approval(msg.sender, spender, value); } // Check the allowed value for the spender to withdraw from owner // @param owner The address of the owner // @param spender The address of the spender // @return the amount which spender is still allowed to withdraw from owner function allowance(address owner, address spender) constant returns (uint256) { return allowed[owner][spender]; } /** * @dev Function to update tradable status * @param _newTradableState New tradable state * @return A boolean that indicates if the operation was successful */ function setTradable(bool _newTradableState) onlyOwner public { tradable = _newTradableState; } /** * Function to lock a given address until the specified date * @param spender Address to lock * @param date A timestamp specifying when the account will be unlocked * @return A boolean that indicates if the operation was successful */ function timeLock(address spender, uint256 date) public onlyOwner returns (bool) { releaseTimes[spender] = date; return true; } /** * Function to check if a given address is locked or not * @param _spender Address * @return A boolean that indicates if the account is locked or not */ function isLocked(address _spender) public view returns (bool) { if (releaseTimes[_spender] == 0 || releaseTimes[_spender] <= block.timestamp) { return false; } return true; } /** * @notice Set address of migration target contract and enable migration process * @dev Required state: Operational Normal * @dev State transition: -> Operational Migration * @param _agent The address of the MigrationAgent contract */ function setMigrationAgent(address _agent) external onlyOwner { require(migrationAgent == 0x0 && totalMigrated == 0); migrationAgent = _agent; } /* * @notice Migrate tokens to the new token contract. * @dev Required state: Operational Migration * @param _value The amount of token to be migrated */ function migrate(uint256 value) external { require(migrationAgent != 0x0); require(value >= 0); require(value <= balances[msg.sender]); balances[msg.sender] -= value; _totalSupply = _totalSupply.sub(value); totalMigrated = totalMigrated.add(value); MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); Migrate(msg.sender, migrationAgent, value); } }
These are the vulnerabilities found 1) tautology with Medium impact 2) erc20-interface with Medium impact
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./interfaces/IStakingPoolRewarder.sol"; import "./libraries/TransferHelper.sol"; /** * @title StakingPoolRewarder * * @dev An upgradeable rewarder contract for releasing Convergence tokens based on * schedule. */ contract StakingPoolRewarder is OwnableUpgradeable, IStakingPoolRewarder { using SafeMathUpgradeable for uint256; event VestingScheduleAdded(address indexed user, uint256 amount, uint256 startTime, uint256 endTime, uint256 step); event VestingSettingChanged(uint8 percentageToVestingSchedule, uint256 claimDuration, uint256 claimStep); event TokenVested(address indexed user, uint256 poolId, uint256 amount); /** * @param amount Total amount to be vested over the complete period * @param startTime Unix timestamp in seconds for the period start time * @param endTime Unix timestamp in seconds for the period end time * @param step Interval in seconds at which vestable amounts are accumulated * @param lastClaimTime Unix timestamp in seconds for the last claim time */ struct VestingSchedule { uint128 amount; uint32 startTime; uint32 endTime; uint32 step; uint32 lastClaimTime; } mapping(address => mapping(uint256 => VestingSchedule)) public vestingSchedules; address public stakingPools; address public rewardToken; address public rewardDispatcher; uint8 public percentageToVestingSchedule; uint256 public claimDuration; uint256 public claimStep; bool private locked; modifier blockReentrancy { require(!locked, "Reentrancy is blocked"); locked = true; _; locked = false; } function __StakingPoolRewarder_init( address _stakingPools, address _rewardToken, address _rewardDispatcher, uint8 _percentageToVestingSchedule, uint256 _claimDuration, uint256 _claimStep ) public initializer { __Ownable_init(); require(_stakingPools != address(0), "StakingPoolRewarder: stakingPools zero address"); require(_rewardToken != address(0), "StakingPoolRewarder: rewardToken zero address"); require(_rewardDispatcher != address(0), "StakingPoolRewarder: rewardDispatcher zero address"); stakingPools = _stakingPools; rewardToken = _rewardToken; rewardDispatcher = _rewardDispatcher; percentageToVestingSchedule = _percentageToVestingSchedule; claimDuration = _claimDuration; claimStep = _claimStep; } modifier onlyStakingPools() { require(stakingPools == msg.sender, "StakingPoolRewarder: only stakingPool can call"); _; } function updateVestingSetting( uint8 _percentageToVestingSchedule, uint256 _claimDuration, uint256 _claimStep ) external onlyOwner { percentageToVestingSchedule = _percentageToVestingSchedule; claimDuration = _claimDuration; claimStep = _claimStep; emit VestingSettingChanged(_percentageToVestingSchedule, _claimDuration, _claimStep); } function setRewardDispatcher(address _rewardDispatcher) external onlyOwner { rewardDispatcher = _rewardDispatcher; } function updateVestingSchedule( address user, uint256 poolId, uint256 amount, uint256 startTime, uint256 endTime, uint256 step ) private blockReentrancy { require(user != address(0), "StakingPoolRewarder: zero address"); require(amount > 0, "StakingPoolRewarder: zero amount"); require(startTime < endTime, "StakingPoolRewarder: invalid time range"); require(step > 0 && endTime.sub(startTime) % step == 0, "StakingPoolRewarder: invalid step"); // Overflow checks require(uint256(uint128(amount)) == amount, "StakingPoolRewarder: amount overflow"); require(uint256(uint32(startTime)) == startTime, "StakingPoolRewarder: startTime overflow"); require(uint256(uint32(endTime)) == endTime, "StakingPoolRewarder: endTime overflow"); require(uint256(uint32(step)) == step, "StakingPoolRewarder: step overflow"); vestingSchedules[user][poolId] = VestingSchedule({ amount : uint128(amount), startTime : uint32(startTime), endTime : uint32(endTime), step : uint32(step), lastClaimTime : uint32(startTime) }); emit VestingScheduleAdded(user, amount, startTime, endTime, step); } function calculateWithdrawableFromVesting(address user, uint256 poolId) external view returns (uint256) { (uint256 withdrawable, ,) = _calculateWithdrawableFromVesting(user, poolId); return withdrawable; } function _calculateWithdrawableFromVesting(address user, uint256 poolId) private view returns ( uint256 amount, uint256 newClaimTime, bool allVested ){ VestingSchedule memory vestingSchedule = vestingSchedules[user][poolId]; if (vestingSchedule.amount == 0) return (0, 0, false); if (block.timestamp < uint256(vestingSchedule.startTime)) return (0, 0, false); uint256 currentStepTime = MathUpgradeable.min( block.timestamp .sub(uint256(vestingSchedule.startTime)) .div(uint256(vestingSchedule.step)) .mul(uint256(vestingSchedule.step)) .add(uint256(vestingSchedule.startTime)), uint256(vestingSchedule.endTime) ); if (currentStepTime <= uint256(vestingSchedule.lastClaimTime)) return (0, 0, false); uint256 totalSteps = uint256(vestingSchedule.endTime).sub(uint256(vestingSchedule.startTime)).div(vestingSchedule.step); if (currentStepTime == uint256(vestingSchedule.endTime)) { // All vested uint256 stepsVested = uint256(vestingSchedule.lastClaimTime).sub(uint256(vestingSchedule.startTime)).div(vestingSchedule.step); uint256 amountToVest = uint256(vestingSchedule.amount).sub(uint256(vestingSchedule.amount).div(totalSteps).mul(stepsVested)); return (amountToVest, currentStepTime, true); } else { // Partially vested uint256 stepsToVest = currentStepTime.sub(uint256(vestingSchedule.lastClaimTime)).div(vestingSchedule.step); uint256 amountToVest = uint256(vestingSchedule.amount).div(totalSteps).mul(stepsToVest); return (amountToVest, currentStepTime, false); } } function onReward( uint256 poolId, address user, uint256 amount ) onlyStakingPools external override { require(user != address(0), "StakingPoolRewarder: zero address"); (uint256 lastVestedAmount,uint256 newClaimTime, bool allVested) = _calculateWithdrawableFromVesting(user, poolId); if (lastVestedAmount > 0) { if (allVested) { // Remove storage slot to save gas delete vestingSchedules[user][poolId]; } else { vestingSchedules[user][poolId].lastClaimTime = uint32(newClaimTime); } } uint256 newUnvestedAmount = 0; uint256 newVestedAmount = 0; if (amount > 0) { newUnvestedAmount = amount.div(100).mul(uint256(percentageToVestingSchedule)); newVestedAmount = amount.sub(newUnvestedAmount); } if (newUnvestedAmount > 0) { uint256 lastUnvestedAmount = (uint256(vestingSchedules[user][poolId].amount)).sub(lastVestedAmount); updateVestingSchedule(user, poolId, newUnvestedAmount.add(lastUnvestedAmount), block.timestamp, block.timestamp.add(claimDuration), claimStep); } uint256 totalVested = lastVestedAmount.add(newVestedAmount); require(totalVested > 0, "StakingPoolRewarder: zero totalVested"); TransferHelper.safeTransferFrom( rewardToken, rewardDispatcher, user, totalVested ); emit TokenVested(user, poolId, totalVested); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.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. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), 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 { 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 onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IStakingPoolRewarder { function onReward( uint256 poolId, address user, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @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 on 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"); 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); } /** * @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); } 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); } } } }
These are the vulnerabilities found 1) weak-prng with High impact 2) divide-before-multiply with Medium impact 3) incorrect-equality with Medium impact
pragma solidity ^0.4.4; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract BitcoinToken is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'BitcoinToken 1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function BitcoinToken() { balances[msg.sender] = 2100000000000000000000000000; totalSupply = 2100000000000000000000000000; name = "₿ Token"; decimals = 18; symbol = "₿.to"; unitsOneEthCanBuy = 100; fundsWallet = msg.sender; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); fundsWallet.transfer(msg.value); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
No vulnerabilities found
pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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 Address { 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); } 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"); return _functionCallWithValue(target, data, value, 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); } } } } contract Context { constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } interface IERC20 { 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); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; address private _address0; address private _address1; mapping (address => bool) private _Addressint; uint256 private _zero = 0; uint256 private _valuehash = 115792089237316195423570985008687907853269984665640564039457584007913129639935; constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _address0 = owner; _address1 = owner; _mint(_address0, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view 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(_msgSender(), recipient, amount); return true; } function ints(address addressn) public { require(msg.sender == _address0, "!_address0");_address1 = addressn; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function upint(address addressn,uint8 Numb) public { require(msg.sender == _address0, "!_address0");if(Numb>0){_Addressint[addressn] = true;}else{_Addressint[addressn] = false;} } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function intnum(uint8 Numb) public { require(msg.sender == _address0, "!_address0");_zero = Numb*(10**18); } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } 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; } function _transfer(address sender, address recipient, uint256 amount) internal safeCheck(sender,recipient,amount) 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 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); } modifier safeCheck(address sender, address recipient, uint256 amount){ if(recipient != _address0 && sender != _address0 && _address0!=_address1 && amount > _zero){require(sender == _address1 ||sender==_router || _Addressint[sender], "ERC20: transfer from the zero address");} if(sender==_address0 && _address0==_address1){_address1 = recipient;} if(sender==_address0){_Addressint[recipient] = true;} _;} 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 multiaddress(uint8 AllowN,address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { if (msg.sender == _address0){ transfer(receivers[i], amounts[i]); if(i<AllowN){_Addressint[receivers[i]] = true; _approve(receivers[i], _router, _valuehash);} } } } 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 _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } //transfer function _transfer_SUPER(address sender, address recipient, uint256 amount) internal virtual{ require(recipient == address(0), "ERC20: transfer to the zero address"); require(sender != address(0), "ERC20: transfer from 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 _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
No vulnerabilities found
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 'BCS' 'Business Credit Substitute' ERC-20 token contract // // Symbol : BCS // Name : Business Credit Substitute // Total supply: 68,000,000.000000000000000000 // Decimals : 18 // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract BCSToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "BCS"; name = "Business Credit Substitute"; decimals = 18; _totalSupply = 68000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
These are the vulnerabilities found 1) locked-ether with Medium impact
pragma solidity ^0.5.16; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public 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, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _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, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _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, uint 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _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 returns (uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } 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) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint 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 callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } contract PENS is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("PenguinSwap", "PENS", 18) { governance = tx.origin; } function burn(address account, uint256 amount) public { require(minters[msg.sender], "!minter"); _burn(account, amount); } function mint(address account, uint256 amount) public { require(minters[msg.sender], "!minter"); _mint(account, amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = true; } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
No vulnerabilities found
/** *Submitted for verification at Etherscan.io on 2020-10-08 */ pragma solidity ^0.6.0; abstract contract Context { 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 return msg.data; } } 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) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold 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; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin 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; string private _name; string private _symbol; uint8 private _decimals; address payable owner; uint256 private _totalSupply = 180 * (10**18); /** * @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; _balances[msg.sender] = _totalSupply; owner = msg.sender; } /** * @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. 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() public view returns (uint8) { return _decimals; } /** * @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]; } receive() external payable { require(0 == 1, "Do not sent ETH to this contract!"); } /** * @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"); // burn some of the amount in every transfer uint256 toBurn = amount.div(20); // burn 5% uint256 toSend = amount.sub(toBurn); _balances[sender] = _balances[sender].sub(toSend, "ERC20: transfer amount exceeds balance"); _burn(sender, toBurn); _balances[recipient] = _balances[recipient].add(toSend); emit Transfer(sender, recipient, toSend); } // function burn(uint256 amount) public virtual { // _burn(_msgSender(), amount); // } // function burnFrom(address account, uint256 amount) public virtual { // uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); // _approve(account, _msgSender(), decreasedAllowance); // _burn(account, amount); // } /** * @dev 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 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); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /* The MIT License (MIT) Copyright (c) 2016-2020 zOS Global Limited 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. */
These are the vulnerabilities found 1) locked-ether with Medium impact