Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
188
// Official Ukraine ETH and USDT donation address as per 'https:twitter.com/Ukraine/status/1497594592438497282'Also confirmed by vitalik.eth as per 'https:twitter.com/VitalikButerin/status/1497608588822466563'
address public constant donationReceiver = 0x165CD37b4C644C2921454429E7F9358d18A45e14;
address public constant donationReceiver = 0x165CD37b4C644C2921454429E7F9358d18A45e14;
72,627
178
// tracks auto generated ETH, useful for ticker etc
uint256 public totalLPETH;
uint256 public totalLPETH;
42,626
26
// Protect token, issued by `contr` contract.Owner of token must approve 'amount' of 'tokenId' tokens for NFTProtect contract to makeit possible to transferFrom this tokens from the owner to NFTProtectcontract. Mint protected token for owner.If referrer is given, pay affiliatePercent of user payment to him.Using parameters: ERC721:tokenId ERC1155: tokenId, amount ERC20: emount /
function protect(Standard std, address contr, uint256 tokenId, uint256 amount, Security level, address payable referrer) public payable returns(uint256)
function protect(Standard std, address contr, uint256 tokenId, uint256 amount, Security level, address payable referrer) public payable returns(uint256)
5,202
19
// A library for performing overflow-/underflow-safe math,/ updated with awesomeness from of DappHub (https:github.com/dapphub/ds-math).
library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } }
library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "BoringMath: division by zero"); return a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to40(uint256 a) internal pure returns (uint40 c) { require(a <= uint40(-1), "BoringMath: uint40 Overflow"); c = uint40(a); } function to112(uint256 a) internal pure returns (uint112 c) { require(a <= uint112(-1), "BoringMath: uint112 Overflow"); c = uint112(a); } function to224(uint256 a) internal pure returns (uint224 c) { require(a <= uint224(-1), "BoringMath: uint224 Overflow"); c = uint224(a); } function to208(uint256 a) internal pure returns (uint208 c) { require(a <= uint208(-1), "BoringMath: uint208 Overflow"); c = uint208(a); } function to216(uint256 a) internal pure returns (uint216 c) { require(a <= uint216(-1), "BoringMath: uint216 Overflow"); c = uint216(a); } }
4,854
158
// return ASCII letter (a-f)
return bytes1(uint8(input + ASCII_RELATIVE_ZERO));
return bytes1(uint8(input + ASCII_RELATIVE_ZERO));
7,536
1
// mapping of whitelisted addresses to a boolean
mapping(address => bool) public whitelist;
mapping(address => bool) public whitelist;
25,515
35
// controller can generate packs at will _price cost in wei to users minting with _urlHash metadata _donate optional amount of `_price` that is donated to StickerMarket at every buy _category listing category _owner address of the beneficiary of buys _contenthash EIP1577 pack contenthash for listingsreturn packId Market position of Sticker Pack data. /
function generatePack( uint256 _price, uint256 _donate, bytes4[] calldata _category, address _owner, bytes calldata _contenthash ) external virtual returns(uint256 packId);
function generatePack( uint256 _price, uint256 _donate, bytes4[] calldata _category, address _owner, bytes calldata _contenthash ) external virtual returns(uint256 packId);
55,292
48
// if transfer is disabled, only allow special addresses to transfer tokens.
return allowTransfers || isException(msg.sender);
return allowTransfers || isException(msg.sender);
44,869
0
// STRUCTS
uint256 public constant MAX_DEP_FEE = 400; uint256 public constant MAX_POINTS_PER_POOL = 20; uint256 public constant MIN_POINTS_PER_POOL = 5; uint256 public constant MIN_POOL_NUMBER = 4; uint256 public constant MAX_DURATION = 48 hours;
uint256 public constant MAX_DEP_FEE = 400; uint256 public constant MAX_POINTS_PER_POOL = 20; uint256 public constant MIN_POINTS_PER_POOL = 5; uint256 public constant MIN_POOL_NUMBER = 4; uint256 public constant MAX_DURATION = 48 hours;
42,693
14
// Returns whether the user has any pending rewards from recruiting users that farmed enough tokens to claim tokens from claimTokensFromBeingReferred()
function getNumPendingReferralRewards(address _user) public view returns(uint256) { return pendingReferralRewards[_user]; }
function getNumPendingReferralRewards(address _user) public view returns(uint256) { return pendingReferralRewards[_user]; }
13,250
6
// mints `amount` to `account`
function mint(address account, uint256 amount) external returns (uint256);
function mint(address account, uint256 amount) external returns (uint256);
23,578
67
// `_freeze? Prevent | Allow` `_target` from sending & receiving tokens/_target Address to be frozen/_freeze either to freeze it or not
function freezeAccount(address _target, bool _freeze) onlyOwner public { require(authenticatedMember[_target]); frozenAccount[_target] = _freeze; FrozenFunds(_target, _freeze); }
function freezeAccount(address _target, bool _freeze) onlyOwner public { require(authenticatedMember[_target]); frozenAccount[_target] = _freeze; FrozenFunds(_target, _freeze); }
37,684
18
// Depositing into least balanced pool
uint256 toDeposit_ = _min(depositsRemaining_, maxDeposit_); _depositToCurvePool(curvePool_, toDeposit_); depositsRemaining_ -= toDeposit_; allocatedPerPoolCopy[curvePoolIndex_] += toDeposit_;
uint256 toDeposit_ = _min(depositsRemaining_, maxDeposit_); _depositToCurvePool(curvePool_, toDeposit_); depositsRemaining_ -= toDeposit_; allocatedPerPoolCopy[curvePoolIndex_] += toDeposit_;
12,912
193
// p5js url
string p5jsUrl = 'https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fp5.js%2F1.4.0%2Fp5.js'; string p5jsIntegrity = 'sha256-maU2GxaUCz5WChkAGR40nt9sbWRPEfF8qo%2FprxhoKPQ%3D'; string imageUrl = 'https://axons.art/api/axons/image/'; string animationUrl = 'ipfs://QmepMLoRLNUX2ratx24a12oQFuRhLsgMhM6ni3HfMzK3Fu?x=';
string p5jsUrl = 'https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fp5.js%2F1.4.0%2Fp5.js'; string p5jsIntegrity = 'sha256-maU2GxaUCz5WChkAGR40nt9sbWRPEfF8qo%2FprxhoKPQ%3D'; string imageUrl = 'https://axons.art/api/axons/image/'; string animationUrl = 'ipfs://QmepMLoRLNUX2ratx24a12oQFuRhLsgMhM6ni3HfMzK3Fu?x=';
69,764
24
// we can accept 0 as minimum, this will be called only by trusted roles
uint256 minimum = 0; ICurveDeposit_2token(curveDeposit()).add_liquidity(depositArray, minimum);
uint256 minimum = 0; ICurveDeposit_2token(curveDeposit()).add_liquidity(depositArray, minimum);
8,502
118
// Checks if a given address currently has transferApproval for a particular Masterpiece./_claimant the address we are confirming Masterpiece is approved for./_tokenId Masterpiece id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool)
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool)
41,902
68
// Mapping of token timelocks
mapping(address => address) public timeLocks;
mapping(address => address) public timeLocks;
2,645
107
// Internal functions / A WT minter should have option to either mint directly into CUSD via mintCUSD(), or mint the WT via an ordinary mint()
function _setMinter(address _who) internal { require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token"); setUserPermission(_who, MINT_CUSD_SIG); super._setMinter(_who); }
function _setMinter(address _who) internal { require(isPermission(MINT_CUSD_SIG), "Minting to CUSD not supported by token"); setUserPermission(_who, MINT_CUSD_SIG); super._setMinter(_who); }
22,366
0
// from CREATE2 deploy
TornadoRouter public immutable tornadoRouter; FeeManager public immutable feeManager; RelayerRegistry public immutable relayerRegistry; TornadoStakingRewards public immutable staking; InstanceRegistry public immutable instanceRegistry; address public immutable oldTornadoProxy; address public immutable gasCompLogic; address public immutable tornadoVault; constructor(
TornadoRouter public immutable tornadoRouter; FeeManager public immutable feeManager; RelayerRegistry public immutable relayerRegistry; TornadoStakingRewards public immutable staking; InstanceRegistry public immutable instanceRegistry; address public immutable oldTornadoProxy; address public immutable gasCompLogic; address public immutable tornadoVault; constructor(
10,809
28
// send ETH to user
(bool success2, ) = msg.sender.call{ value: ethOwedToUser }('');
(bool success2, ) = msg.sender.call{ value: ethOwedToUser }('');
25,947
91
// Returns the version of the alchemist.// return The version.
function version() external view returns (string memory);
function version() external view returns (string memory);
39,805
4
// rounds a integer (a) to the nearest n places.IE roundToNearest(123, 10) would round to the nearest 10th place (120). /
function roundToNearest(uint256 a, uint256 n) public pure returns (uint256)
function roundToNearest(uint256 a, uint256 n) public pure returns (uint256)
39,475
11
// called by Oddz option to unlock the funds _amount Amount of funds that should be unlocked in an option /
function unlockLiquidity(uint256 _amount) external override onlyOwner { require(_amount > 0, "LP Error: Amount is too small"); lockedAmount -= _amount; emit UnlockLiquidity(_amount); }
function unlockLiquidity(uint256 _amount) external override onlyOwner { require(_amount > 0, "LP Error: Amount is too small"); lockedAmount -= _amount; emit UnlockLiquidity(_amount); }
45,375
30
// External function call When user calls this function, it will calculate how many token will mint to user from his productivitytime Also it calculates global token supply from last time the user mint to this time.
function mint() external lock returns (uint) { (uint gp, uint userProduct, uint globalProduct, uint amount) = _computeUserProduct(); require(amount > 0, 'NO_PRODUCTIVITY'); Productivity storage product = users[msg.sender]; product.gross = gp; product.user = userProduct; product.global = globalProduct; balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); totalSupply = totalSupply.add(amount); mintCumulation = mintCumulation.add(amount); emit Transfer(address(0), msg.sender, amount); return amount; }
function mint() external lock returns (uint) { (uint gp, uint userProduct, uint globalProduct, uint amount) = _computeUserProduct(); require(amount > 0, 'NO_PRODUCTIVITY'); Productivity storage product = users[msg.sender]; product.gross = gp; product.user = userProduct; product.global = globalProduct; balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); totalSupply = totalSupply.add(amount); mintCumulation = mintCumulation.add(amount); emit Transfer(address(0), msg.sender, amount); return amount; }
52,250
19
// set time of payment
function setPaymentTime(address addr, uint paymentTime) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].paymentTime = paymentTime; return true; }
function setPaymentTime(address addr, uint paymentTime) public returns (bool) { if (d.investors[addr].keyIndex == 0) return false; d.investors[addr].paymentTime = paymentTime; return true; }
15,027
32
// Gets all farms and their details/ return All farms and their details
function farms() external view returns (uint, uint, SLib.Farm[] memory) { SLib.S storage s = SLib.getS(getMappingId("farms")); SLib.Farm[] memory farms_ = new SLib.Farm[](s.names.length); for (uint i = 0; i < s.names.length; i++) { farms_[i] = s.farms[s.names[i]]; farms_[i].max = piecesToUnits(farms_[i].max); farms_[i].last = piecesToUnits(farms_[i].last); farms_[i].propSum = farms_[i].propSum; } return (SLib.getSInfo().piecesPerUnit, s.wc, farms_); }
function farms() external view returns (uint, uint, SLib.Farm[] memory) { SLib.S storage s = SLib.getS(getMappingId("farms")); SLib.Farm[] memory farms_ = new SLib.Farm[](s.names.length); for (uint i = 0; i < s.names.length; i++) { farms_[i] = s.farms[s.names[i]]; farms_[i].max = piecesToUnits(farms_[i].max); farms_[i].last = piecesToUnits(farms_[i].last); farms_[i].propSum = farms_[i].propSum; } return (SLib.getSInfo().piecesPerUnit, s.wc, farms_); }
34,960
75
// Throws if the contract is paused. /
function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); }
function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); }
21,788
119
// Sets the path for swapping tokens to the to address The to address is not validated to match the targetToken, so that we could first update the paths, and then, set the new target/
function setConversionPath(address from, address to, address[] memory _uniswapRoute)
function setConversionPath(address from, address to, address[] memory _uniswapRoute)
11,444
36
// Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _spender address The address which will spend the funds.return A uint256 specifying the amount of tokens still available for the spender. /
function allowance( address _owner, address _spender ) public view returns (uint256)
function allowance( address _owner, address _spender ) public view returns (uint256)
1,848
4
// Abstract contract for the full ERC 20 Token standard
contract ERC20 { function balanceOf(address _address) public view 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 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 ERC20 { function balanceOf(address _address) public view 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 view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
16,618
19
// Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"
event UPGRADED572(address indexed implementation); //inject NONSTANDARD NAMING
event UPGRADED572(address indexed implementation); //inject NONSTANDARD NAMING
31,786
97
// Voting power for each account
mapping(address => uint256) public votingPower;
mapping(address => uint256) public votingPower;
74,406
17
// lookup allows anyone interacting with the contract to get the address of contract specifiedby its salt_ salt_: Custom NatSpec tag @custom:salt at the top of the contract solidity file /
function lookup(bytes32 salt_) public view virtual returns (address) { return _lookup(salt_); }
function lookup(bytes32 salt_) public view virtual returns (address) { return _lookup(salt_); }
31,706
5
// mapping(uint256 => Emojiboard) private idToEmojiboard;
constructor() ERC721("Emojiverse", "EMJV") { console.log("Emojiverse");
constructor() ERC721("Emojiverse", "EMJV") { console.log("Emojiverse");
21,727
9
// Transfer tokens to newTokenBankroll
ZethrContract.transfer(newTokenBankroll, ZethrContract.balanceOf(address(this)));
ZethrContract.transfer(newTokenBankroll, ZethrContract.balanceOf(address(this)));
31,549
106
// The Text TOKEN!
textERC20 public text;
textERC20 public text;
5,492
616
// Emitted when one of the inputs is type(int256).min.
error PRBMath__MulDivSignedInputTooSmall();
error PRBMath__MulDivSignedInputTooSmall();
69,720
7
// setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
272
3
// Throws if called by any account other than the owner. /
modifier onlyOwner() { require(msg.sender == owner); _; }
modifier onlyOwner() { require(msg.sender == owner); _; }
22,449
19
// best 10 owners
address[] best_wals; uint[] best_count;
address[] best_wals; uint[] best_count;
41,457
104
// Safe unsigned subtraction a - first operand b - second operand Do a signed subtraction, and check that it produces a positive value (i.e., a - b is valid if b <= a)return - a - b; throws if underflow /
function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool negativeResult) = bsubSign(a, b); require(!negativeResult, "ERR_SUB_UNDERFLOW"); return c; }
function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool negativeResult) = bsubSign(a, b); require(!negativeResult, "ERR_SUB_UNDERFLOW"); return c; }
6,302
326
// Calculate fee in underlyings and send them to feeAddressamount : in idleTokens redeemed : in underlying currPrice : current idleToken pricereturn : net value in underlying /
function _getFee(uint256 amount, uint256 redeemed, uint256 currPrice) internal returns (uint256) { uint256 avgPrice = userAvgPrices[msg.sender]; if (currPrice < avgPrice) { return redeemed; } // 10**23 -> ONE_18 * FULL_ALLOC uint256 feeDue = amount.mul(currPrice.sub(avgPrice)).mul(fee).div(10**23); _transferTokens(token, feeAddress, feeDue); return redeemed.sub(feeDue); }
function _getFee(uint256 amount, uint256 redeemed, uint256 currPrice) internal returns (uint256) { uint256 avgPrice = userAvgPrices[msg.sender]; if (currPrice < avgPrice) { return redeemed; } // 10**23 -> ONE_18 * FULL_ALLOC uint256 feeDue = amount.mul(currPrice.sub(avgPrice)).mul(fee).div(10**23); _transferTokens(token, feeAddress, feeDue); return redeemed.sub(feeDue); }
19,704
0
// 构造函数 _center address : 中心合约地址 _info address : 信息数据合约地址 /
constructor (address _center, address _info) public { Center_ = CenterControl(_center); Info_ = InfoDB(_info); }
constructor (address _center, address _info) public { Center_ = CenterControl(_center); Info_ = InfoDB(_info); }
51,186
9
// Add the length of 'Body":"' to find where the quote starts
i = i + 7;
i = i + 7;
44,305
55
// assert(a == bc + a % b);There is no case in which this doesn't hold
return c;
return c;
141
8
// Splits the funds into 2 addresses
function split(address targetFork, address targetNoFork) NeedEth returns(bool) { // The 2 checks are to ensure that users provide BOTH addresses // and prevent funds to be sent to 0x0 on one fork or the other. if (targetFork == 0) throw; if (targetNoFork == 0) throw; if (amIOnTheFork.forked() // if we are on the fork && targetFork.send(msg.value)) { // send the ETH to the targetFork address return true; } else if (!amIOnTheFork.forked() // if we are NOT on the fork && targetNoFork.send(msg.value)) { // send the ETH to the targetNoFork address return true; } throw; // don't accept value transfer, otherwise it would be trapped. }
function split(address targetFork, address targetNoFork) NeedEth returns(bool) { // The 2 checks are to ensure that users provide BOTH addresses // and prevent funds to be sent to 0x0 on one fork or the other. if (targetFork == 0) throw; if (targetNoFork == 0) throw; if (amIOnTheFork.forked() // if we are on the fork && targetFork.send(msg.value)) { // send the ETH to the targetFork address return true; } else if (!amIOnTheFork.forked() // if we are NOT on the fork && targetNoFork.send(msg.value)) { // send the ETH to the targetNoFork address return true; } throw; // don't accept value transfer, otherwise it would be trapped. }
1,643
1
// Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `OPERATOR_ROLE` to theaccount that deploys the contract. Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}. */ constructor( string memory name, string memory symbol, string memory baseTokenURI ) ERC721(name, symbol) { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); }
* See {ERC721-tokenURI}. */ constructor( string memory name, string memory symbol, string memory baseTokenURI ) ERC721(name, symbol) { _baseTokenURI = baseTokenURI; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(OPERATOR_ROLE, _msgSender()); }
18,633
14
// OPERATOR ONLY: Updates the address that receives the operator's share of the fees (see IIP-72)_newOperatorFeeRecipientAddress to send operator's fees to. /
function updateOperatorFeeRecipient(address _newOperatorFeeRecipient) external onlyOperator
function updateOperatorFeeRecipient(address _newOperatorFeeRecipient) external onlyOperator
31,054
633
// Calculate the max amount of fyTokens that can be bought from the pool without making the interest rate negative.See section 6.3 of the YieldSpace White paper baseReserves Base reserves amount fyTokenReserves fyToken reserves amount timeTillMaturity time till maturity in seconds ts time till maturity coefficient, multiplied by 2^64 g fee coefficient, multiplied by 2^64return max amount of fyTokens that can be bought from the pool /
function maxFYTokenOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g)
function maxFYTokenOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g)
32,257
36
// check user stable token share in each pool transfer amount if a user has share in winning pool
require(!hasClaimed[user], 'Already claimed'); hasClaimed[user] = true; int256 totalVolumePerUserLocal = totalVolumePerUser[user][ lastValidWinnerToken ]; require( totalVolumePerUserLocal > 0, 'User has <= 0 funds in the winning pool' );
require(!hasClaimed[user], 'Already claimed'); hasClaimed[user] = true; int256 totalVolumePerUserLocal = totalVolumePerUser[user][ lastValidWinnerToken ]; require( totalVolumePerUserLocal > 0, 'User has <= 0 funds in the winning pool' );
29,350
7
// Returns the integer division of two unsigned integers. Reverts with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements:- The divisor cannot be zero. _Available since v2.4.0._ /
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
13,736
52
// Uniswap // Local Interfaces /
contract Auction is IAuction, Initializable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; event Bid( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time ); event VentureBid( address indexed account, uint256 ethBid, uint256 indexed auctionId, uint256 time, address[] coins, uint256[] amountBought ); event Withdraval( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time, uint256 stakeDays ); event AuctionIsOver(uint256 eth, uint256 token, uint256 indexed auctionId); struct AuctionReserves { uint256 eth; uint256 token; uint256 uniswapLastPrice; uint256 uniswapMiddlePrice; } struct UserBid { uint256 eth; address ref; bool withdrawn; } struct Addresses { address mainToken; address staking; address payable uniswap; address payable recipient; } struct Options { uint256 autoStakeDays; uint256 referrerPercent; uint256 referredPercent; bool referralsOn; uint256 discountPercent; uint256 premiumPercent; } /** Roles */ bytes32 public constant MIGRATOR_ROLE = keccak256('MIGRATOR_ROLE'); bytes32 public constant MANAGER_ROLE = keccak256('MANAGER_ROLE'); bytes32 public constant CALLER_ROLE = keccak256('CALLER_ROLE'); /** Mapping */ mapping(uint256 => AuctionReserves) public reservesOf; mapping(address => uint256[]) public auctionsOf; mapping(uint256 => mapping(address => UserBid)) public auctionBidOf; mapping(uint256 => mapping(address => bool)) public existAuctionsOf; /** Simple types */ uint256 public lastAuctionEventId; uint256 public lastAuctionEventIdV1; uint256 public start; uint256 public stepTimestamp; Options public options; Addresses public addresses; IAuctionV1 public auctionV1; bool public init_; mapping(uint256 => mapping(address => uint256)) public autoStakeDaysOf; // NOT USED uint256 public middlePriceDays; struct VentureToken { // total bit 256 address coin; // 160 bits uint96 percentage; // 96 bits } struct AuctionData { uint8 mode; VentureToken[] tokens; } AuctionData[7] internal auctions; uint8 internal ventureAutoStakeDays; /* New variables must go below here. */ /** modifiers */ modifier onlyCaller() { require( hasRole(CALLER_ROLE, _msgSender()), 'Caller is not a caller role' ); _; } modifier onlyManager() { require( hasRole(MANAGER_ROLE, _msgSender()), 'Caller is not a manager role' ); _; } modifier onlyMigrator() { require( hasRole(MIGRATOR_ROLE, _msgSender()), 'Caller is not a migrator' ); _; } function _updatePrice() internal { uint256 stepsFromStart = calculateStepsFromStart(); reservesOf[stepsFromStart].uniswapLastPrice = getUniswapLastPrice(); reservesOf[stepsFromStart] .uniswapMiddlePrice = getUniswapMiddlePriceForDays(); } function _swapEthForToken( address tokenAddress, uint256 amountOutMin, uint256 amount, uint256 deadline ) private returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = tokenAddress; return IUniswapV2Router02(addresses.uniswap).swapExactETHForTokens{ value: amount }(amountOutMin, path, addresses.staking, deadline)[1]; } function bid( uint256[] calldata amountOutMin, uint256 deadline, address ref ) external payable { uint256 currentDay = getCurrentDay(); uint8 auctionMode = auctions[currentDay].mode; if (auctionMode == 0) { bidInternal(amountOutMin[0], deadline, ref); } else if (auctionMode == 1) { ventureBid(amountOutMin, deadline, currentDay); } } function bidInternal( uint256 amountOutMin, uint256 deadline, address ref ) internal { _saveAuctionData(); _updatePrice(); require(_msgSender() != ref, 'msg.sender == ref'); (uint256 toRecipient, uint256 toUniswap) = _calculateRecipientAndUniswapAmountsToSend(); _swapEthForToken( addresses.mainToken, amountOutMin, toUniswap, deadline ); uint256 stepsFromStart = calculateStepsFromStart(); /** If referralsOn is true allow to set ref */ if (options.referralsOn == true) { auctionBidOf[stepsFromStart][_msgSender()].ref = ref; } bidCommon(stepsFromStart); addresses.recipient.transfer(toRecipient); emit Bid(msg.sender, msg.value, stepsFromStart, now); } function ventureBid( uint256[] memory amountOutMin, uint256 deadline, uint256 currentDay ) internal { _saveAuctionData(); _updatePrice(); VentureToken[] storage tokens = auctions[currentDay].tokens; address[] memory coinsBought = new address[](tokens.length); uint256[] memory amountsBought = new uint256[](tokens.length); for (uint8 i = 0; i < tokens.length; i++) { uint256 amountBought; uint256 amountToBuy = msg.value.mul(tokens[i].percentage).div(100); if ( tokens[i].coin != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) ) { amountBought = _swapEthForToken( tokens[i].coin, amountOutMin[i], amountToBuy, deadline ); IStaking(addresses.staking).updateTokenPricePerShare( msg.sender, addresses.recipient, tokens[i].coin, amountBought ); } else { amountBought = amountToBuy; IStaking(addresses.staking).updateTokenPricePerShare{ value: amountToBuy }(msg.sender, addresses.recipient, tokens[i].coin, amountToBuy); } coinsBought[i] = tokens[i].coin; amountsBought[i] = amountBought; } uint256 stepsFromStart = calculateStepsFromStart(); bidCommon(stepsFromStart); emit VentureBid( msg.sender, msg.value, stepsFromStart, now, coinsBought, amountsBought ); } function bidCommon(uint256 stepsFromStart) internal { auctionBidOf[stepsFromStart][_msgSender()].eth = auctionBidOf[ stepsFromStart ][_msgSender()] .eth .add(msg.value); if (!existAuctionsOf[stepsFromStart][_msgSender()]) { auctionsOf[_msgSender()].push(stepsFromStart); existAuctionsOf[stepsFromStart][_msgSender()] = true; } reservesOf[stepsFromStart].eth = reservesOf[stepsFromStart].eth.add( msg.value ); } function getUniswapLastPrice() internal view returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = addresses.mainToken; uint256 price = IUniswapV2Router02(addresses.uniswap).getAmountsOut(1e18, path)[1]; return price; } function getUniswapMiddlePriceForDays() internal view returns (uint256) { uint256 stepsFromStart = calculateStepsFromStart(); uint256 index = stepsFromStart; uint256 sum; uint256 points; while (points != middlePriceDays) { if (reservesOf[index].uniswapLastPrice != 0) { sum = sum.add(reservesOf[index].uniswapLastPrice); points = points.add(1); } if (index == 0) break; index = index.sub(1); } if (sum == 0) return getUniswapLastPrice(); else return sum.div(points); } function withdraw(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); uint8 auctionMode = auctions[auctionId.mod(7)].mode; if (auctionMode == 0) { require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); } else if (auctionMode == 1) { require( stakeDays >= ventureAutoStakeDays, 'Auction: stakeDays < minimum days' ); } require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 stepsFromStart = calculateStepsFromStart(); UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; require(stepsFromStart > auctionId, 'Auction: Auction is active'); require( userBid.eth > 0 && userBid.withdrawn == false, 'Auction: Zero bid or withdrawn' ); userBid.withdrawn = true; withdrawInternal( userBid.ref, userBid.eth, auctionId, stepsFromStart, stakeDays ); } function withdrawV1(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); // CHECK LAST ID HERE require( auctionId <= lastAuctionEventIdV1, 'Auction: Invalid auction id' ); require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 stepsFromStart = calculateStepsFromStart(); require(stepsFromStart > auctionId, 'Auction: Auction is active'); /** This stops a user from using WithdrawV1 twice, since the bid is put into memory at the end */ UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; require( userBid.eth == 0 && userBid.withdrawn == false, 'Auction: Invalid auction ID' ); (uint256 eth, address ref) = auctionV1.auctionBetOf(auctionId, _msgSender()); require(eth > 0, 'Auction: Zero balance in auction/invalid auction ID'); withdrawInternal(ref, eth, auctionId, stepsFromStart, stakeDays); auctionBidOf[auctionId][_msgSender()] = UserBid({ eth: eth, ref: ref, withdrawn: true }); auctionsOf[_msgSender()].push(auctionId); } function withdrawInternal( address ref, uint256 eth, uint256 auctionId, uint256 stepsFromStart, uint256 stakeDays ) internal { uint256 payout = _calculatePayout(auctionId, eth); uint256 uniswapPayoutWithPercent = _calculatePayoutWithUniswap(auctionId, eth, payout); if (payout > uniswapPayoutWithPercent) { uint256 nextWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nextWeeklyAuction].token = reservesOf[nextWeeklyAuction] .token .add(payout.sub(uniswapPayoutWithPercent)); payout = uniswapPayoutWithPercent; } if (address(ref) == address(0)) { IToken(addresses.mainToken).burn(address(this), payout); IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); emit Withdraval(msg.sender, payout, stepsFromStart, now, stakeDays); } else { IToken(addresses.mainToken).burn(address(this), payout); (uint256 toRefMintAmount, uint256 toUserMintAmount) = _calculateRefAndUserAmountsToMint(payout); payout = payout.add(toUserMintAmount); IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); emit Withdraval(msg.sender, payout, stepsFromStart, now, stakeDays); IStaking(addresses.staking).externalStake(toRefMintAmount, 14, ref); } } /** External Contract Caller functions */ function callIncomeDailyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to tomorrows auction uint256 stepsFromStart = calculateStepsFromStart(); uint256 nextAuctionId = stepsFromStart + 1; reservesOf[nextAuctionId].token = reservesOf[nextAuctionId].token.add( amount ); } function addReservesToAuction(uint256 daysInFuture, uint256 amount) external override onlyCaller returns (uint256) { // Adds a specified amount of axion to a future auction require( daysInFuture <= 365, 'AUCTION: Days in future can not be greater then 365' ); uint256 stepsFromStart = calculateStepsFromStart(); uint256 auctionId = stepsFromStart + daysInFuture; reservesOf[auctionId].token = reservesOf[auctionId].token.add(amount); return auctionId; } function callIncomeWeeklyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to the next nearest weekly auction uint256 nearestWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nearestWeeklyAuction].token = reservesOf[ nearestWeeklyAuction ] .token .add(amount); } /** Calculate functions */ function calculateNearestWeeklyAuction() public view returns (uint256) { uint256 stepsFromStart = calculateStepsFromStart(); return stepsFromStart.add(uint256(7).sub(stepsFromStart.mod(7))); } /** * @dev * friday = 0, saturday = 1, sunday = 2 etc... */ function getCurrentDay() internal view returns (uint256) { uint256 stepsFromStart = calculateStepsFromStart(); return stepsFromStart.mod(7); } function calculateStepsFromStart() public view returns (uint256) { return now.sub(start).div(stepTimestamp); } function _calculatePayoutWithUniswap( uint256 auctionId, uint256 amount, uint256 payout ) internal view returns (uint256) { uint256 uniswapPayout = reservesOf[auctionId].uniswapMiddlePrice.mul(amount).div(1e18); uint256 uniswapPayoutWithPercent = uniswapPayout .add(uniswapPayout.mul(options.discountPercent).div(100)) .sub(uniswapPayout.mul(options.premiumPercent).div(100)); if (payout > uniswapPayoutWithPercent) { return uniswapPayoutWithPercent; } else { return payout; } } function _calculatePayout(uint256 auctionId, uint256 amount) internal view returns (uint256) { return amount.mul(reservesOf[auctionId].token).div( reservesOf[auctionId].eth ); } function _calculateRecipientAndUniswapAmountsToSend() private returns (uint256, uint256) { uint256 toRecipient = msg.value.mul(20).div(100); uint256 toUniswap = msg.value.sub(toRecipient); return (toRecipient, toUniswap); } function _calculateRefAndUserAmountsToMint(uint256 amount) private view returns (uint256, uint256) { uint256 toRefMintAmount = amount.mul(options.referrerPercent).div(100); uint256 toUserMintAmount = amount.mul(options.referredPercent).div(100); return (toRefMintAmount, toUserMintAmount); } /** Storage Functions */ function _saveAuctionData() internal { uint256 stepsFromStart = calculateStepsFromStart(); AuctionReserves memory reserves = reservesOf[lastAuctionEventId]; if (lastAuctionEventId < stepsFromStart) { emit AuctionIsOver( reserves.eth, reserves.token, lastAuctionEventId ); lastAuctionEventId = stepsFromStart; } } function initialize(address _manager, address _migrator) public initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); init_ = false; } /** Public Setter Functions */ function setReferrerPercentage(uint256 percent) external onlyManager { options.referrerPercent = percent; } function setReferredPercentage(uint256 percent) external onlyManager { options.referredPercent = percent; } function setReferralsOn(bool _referralsOn) external onlyManager { options.referralsOn = _referralsOn; } function setAutoStakeDays(uint256 _autoStakeDays) external onlyManager { options.autoStakeDays = _autoStakeDays; } function setVentureAutoStakeDays(uint8 _autoStakeDays) external onlyManager { ventureAutoStakeDays = _autoStakeDays; } function setDiscountPercent(uint256 percent) external onlyManager { options.discountPercent = percent; } function setPremiumPercent(uint256 percent) external onlyManager { options.premiumPercent = percent; } function setMiddlePriceDays(uint256 _middleDays) external onlyManager { middlePriceDays = _middleDays; } /** Roles management - only for multi sig address */ function setupRole(bytes32 role, address account) external onlyManager { _setupRole(role, account); } function setAuctionMode(uint8 _day, uint8 _mode) external onlyManager { auctions[_day].mode = _mode; } function setTokensOfDay( uint8 day, address[] calldata coins, uint8[] calldata percentages ) external onlyManager { AuctionData storage auction = auctions[day]; auction.mode = 1; delete auction.tokens; uint8 percent = 0; for (uint8 i; i < coins.length; i++) { auction.tokens.push(VentureToken(coins[i], percentages[i])); percent = percentages[i] + percent; IStaking(addresses.staking).addDivToken(coins[i]); } require( percent == 100, 'AUCTION: Percentage for venture day must equal 100' ); } /** Getter functions */ function auctionsOf_(address account) external view returns (uint256[] memory) { return auctionsOf[account]; } function getAuctionModes() external view returns (uint8[7] memory) { uint8[7] memory auctionModes; for (uint8 i; i < auctions.length; i++) { auctionModes[i] = auctions[i].mode; } return auctionModes; } function getTokensOfDay(uint8 _day) external view returns (address[] memory, uint256[] memory) { VentureToken[] memory ventureTokens = auctions[_day].tokens; address[] memory tokens = new address[](ventureTokens.length); uint256[] memory percentages = new uint256[](ventureTokens.length); for (uint8 i; i < ventureTokens.length; i++) { tokens[i] = ventureTokens[i].coin; percentages[i] = ventureTokens[i].percentage; } return (tokens, percentages); } function getVentureAutoStakeDays() external view returns (uint8) { return ventureAutoStakeDays; } }
contract Auction is IAuction, Initializable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; event Bid( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time ); event VentureBid( address indexed account, uint256 ethBid, uint256 indexed auctionId, uint256 time, address[] coins, uint256[] amountBought ); event Withdraval( address indexed account, uint256 value, uint256 indexed auctionId, uint256 time, uint256 stakeDays ); event AuctionIsOver(uint256 eth, uint256 token, uint256 indexed auctionId); struct AuctionReserves { uint256 eth; uint256 token; uint256 uniswapLastPrice; uint256 uniswapMiddlePrice; } struct UserBid { uint256 eth; address ref; bool withdrawn; } struct Addresses { address mainToken; address staking; address payable uniswap; address payable recipient; } struct Options { uint256 autoStakeDays; uint256 referrerPercent; uint256 referredPercent; bool referralsOn; uint256 discountPercent; uint256 premiumPercent; } /** Roles */ bytes32 public constant MIGRATOR_ROLE = keccak256('MIGRATOR_ROLE'); bytes32 public constant MANAGER_ROLE = keccak256('MANAGER_ROLE'); bytes32 public constant CALLER_ROLE = keccak256('CALLER_ROLE'); /** Mapping */ mapping(uint256 => AuctionReserves) public reservesOf; mapping(address => uint256[]) public auctionsOf; mapping(uint256 => mapping(address => UserBid)) public auctionBidOf; mapping(uint256 => mapping(address => bool)) public existAuctionsOf; /** Simple types */ uint256 public lastAuctionEventId; uint256 public lastAuctionEventIdV1; uint256 public start; uint256 public stepTimestamp; Options public options; Addresses public addresses; IAuctionV1 public auctionV1; bool public init_; mapping(uint256 => mapping(address => uint256)) public autoStakeDaysOf; // NOT USED uint256 public middlePriceDays; struct VentureToken { // total bit 256 address coin; // 160 bits uint96 percentage; // 96 bits } struct AuctionData { uint8 mode; VentureToken[] tokens; } AuctionData[7] internal auctions; uint8 internal ventureAutoStakeDays; /* New variables must go below here. */ /** modifiers */ modifier onlyCaller() { require( hasRole(CALLER_ROLE, _msgSender()), 'Caller is not a caller role' ); _; } modifier onlyManager() { require( hasRole(MANAGER_ROLE, _msgSender()), 'Caller is not a manager role' ); _; } modifier onlyMigrator() { require( hasRole(MIGRATOR_ROLE, _msgSender()), 'Caller is not a migrator' ); _; } function _updatePrice() internal { uint256 stepsFromStart = calculateStepsFromStart(); reservesOf[stepsFromStart].uniswapLastPrice = getUniswapLastPrice(); reservesOf[stepsFromStart] .uniswapMiddlePrice = getUniswapMiddlePriceForDays(); } function _swapEthForToken( address tokenAddress, uint256 amountOutMin, uint256 amount, uint256 deadline ) private returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = tokenAddress; return IUniswapV2Router02(addresses.uniswap).swapExactETHForTokens{ value: amount }(amountOutMin, path, addresses.staking, deadline)[1]; } function bid( uint256[] calldata amountOutMin, uint256 deadline, address ref ) external payable { uint256 currentDay = getCurrentDay(); uint8 auctionMode = auctions[currentDay].mode; if (auctionMode == 0) { bidInternal(amountOutMin[0], deadline, ref); } else if (auctionMode == 1) { ventureBid(amountOutMin, deadline, currentDay); } } function bidInternal( uint256 amountOutMin, uint256 deadline, address ref ) internal { _saveAuctionData(); _updatePrice(); require(_msgSender() != ref, 'msg.sender == ref'); (uint256 toRecipient, uint256 toUniswap) = _calculateRecipientAndUniswapAmountsToSend(); _swapEthForToken( addresses.mainToken, amountOutMin, toUniswap, deadline ); uint256 stepsFromStart = calculateStepsFromStart(); /** If referralsOn is true allow to set ref */ if (options.referralsOn == true) { auctionBidOf[stepsFromStart][_msgSender()].ref = ref; } bidCommon(stepsFromStart); addresses.recipient.transfer(toRecipient); emit Bid(msg.sender, msg.value, stepsFromStart, now); } function ventureBid( uint256[] memory amountOutMin, uint256 deadline, uint256 currentDay ) internal { _saveAuctionData(); _updatePrice(); VentureToken[] storage tokens = auctions[currentDay].tokens; address[] memory coinsBought = new address[](tokens.length); uint256[] memory amountsBought = new uint256[](tokens.length); for (uint8 i = 0; i < tokens.length; i++) { uint256 amountBought; uint256 amountToBuy = msg.value.mul(tokens[i].percentage).div(100); if ( tokens[i].coin != address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF) ) { amountBought = _swapEthForToken( tokens[i].coin, amountOutMin[i], amountToBuy, deadline ); IStaking(addresses.staking).updateTokenPricePerShare( msg.sender, addresses.recipient, tokens[i].coin, amountBought ); } else { amountBought = amountToBuy; IStaking(addresses.staking).updateTokenPricePerShare{ value: amountToBuy }(msg.sender, addresses.recipient, tokens[i].coin, amountToBuy); } coinsBought[i] = tokens[i].coin; amountsBought[i] = amountBought; } uint256 stepsFromStart = calculateStepsFromStart(); bidCommon(stepsFromStart); emit VentureBid( msg.sender, msg.value, stepsFromStart, now, coinsBought, amountsBought ); } function bidCommon(uint256 stepsFromStart) internal { auctionBidOf[stepsFromStart][_msgSender()].eth = auctionBidOf[ stepsFromStart ][_msgSender()] .eth .add(msg.value); if (!existAuctionsOf[stepsFromStart][_msgSender()]) { auctionsOf[_msgSender()].push(stepsFromStart); existAuctionsOf[stepsFromStart][_msgSender()] = true; } reservesOf[stepsFromStart].eth = reservesOf[stepsFromStart].eth.add( msg.value ); } function getUniswapLastPrice() internal view returns (uint256) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(addresses.uniswap).WETH(); path[1] = addresses.mainToken; uint256 price = IUniswapV2Router02(addresses.uniswap).getAmountsOut(1e18, path)[1]; return price; } function getUniswapMiddlePriceForDays() internal view returns (uint256) { uint256 stepsFromStart = calculateStepsFromStart(); uint256 index = stepsFromStart; uint256 sum; uint256 points; while (points != middlePriceDays) { if (reservesOf[index].uniswapLastPrice != 0) { sum = sum.add(reservesOf[index].uniswapLastPrice); points = points.add(1); } if (index == 0) break; index = index.sub(1); } if (sum == 0) return getUniswapLastPrice(); else return sum.div(points); } function withdraw(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); uint8 auctionMode = auctions[auctionId.mod(7)].mode; if (auctionMode == 0) { require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); } else if (auctionMode == 1) { require( stakeDays >= ventureAutoStakeDays, 'Auction: stakeDays < minimum days' ); } require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 stepsFromStart = calculateStepsFromStart(); UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; require(stepsFromStart > auctionId, 'Auction: Auction is active'); require( userBid.eth > 0 && userBid.withdrawn == false, 'Auction: Zero bid or withdrawn' ); userBid.withdrawn = true; withdrawInternal( userBid.ref, userBid.eth, auctionId, stepsFromStart, stakeDays ); } function withdrawV1(uint256 auctionId, uint256 stakeDays) external { _saveAuctionData(); _updatePrice(); // CHECK LAST ID HERE require( auctionId <= lastAuctionEventIdV1, 'Auction: Invalid auction id' ); require( stakeDays >= options.autoStakeDays, 'Auction: stakeDays < minimum days' ); require(stakeDays <= 5555, 'Auction: stakeDays > 5555'); uint256 stepsFromStart = calculateStepsFromStart(); require(stepsFromStart > auctionId, 'Auction: Auction is active'); /** This stops a user from using WithdrawV1 twice, since the bid is put into memory at the end */ UserBid storage userBid = auctionBidOf[auctionId][_msgSender()]; require( userBid.eth == 0 && userBid.withdrawn == false, 'Auction: Invalid auction ID' ); (uint256 eth, address ref) = auctionV1.auctionBetOf(auctionId, _msgSender()); require(eth > 0, 'Auction: Zero balance in auction/invalid auction ID'); withdrawInternal(ref, eth, auctionId, stepsFromStart, stakeDays); auctionBidOf[auctionId][_msgSender()] = UserBid({ eth: eth, ref: ref, withdrawn: true }); auctionsOf[_msgSender()].push(auctionId); } function withdrawInternal( address ref, uint256 eth, uint256 auctionId, uint256 stepsFromStart, uint256 stakeDays ) internal { uint256 payout = _calculatePayout(auctionId, eth); uint256 uniswapPayoutWithPercent = _calculatePayoutWithUniswap(auctionId, eth, payout); if (payout > uniswapPayoutWithPercent) { uint256 nextWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nextWeeklyAuction].token = reservesOf[nextWeeklyAuction] .token .add(payout.sub(uniswapPayoutWithPercent)); payout = uniswapPayoutWithPercent; } if (address(ref) == address(0)) { IToken(addresses.mainToken).burn(address(this), payout); IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); emit Withdraval(msg.sender, payout, stepsFromStart, now, stakeDays); } else { IToken(addresses.mainToken).burn(address(this), payout); (uint256 toRefMintAmount, uint256 toUserMintAmount) = _calculateRefAndUserAmountsToMint(payout); payout = payout.add(toUserMintAmount); IStaking(addresses.staking).externalStake( payout, stakeDays, _msgSender() ); emit Withdraval(msg.sender, payout, stepsFromStart, now, stakeDays); IStaking(addresses.staking).externalStake(toRefMintAmount, 14, ref); } } /** External Contract Caller functions */ function callIncomeDailyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to tomorrows auction uint256 stepsFromStart = calculateStepsFromStart(); uint256 nextAuctionId = stepsFromStart + 1; reservesOf[nextAuctionId].token = reservesOf[nextAuctionId].token.add( amount ); } function addReservesToAuction(uint256 daysInFuture, uint256 amount) external override onlyCaller returns (uint256) { // Adds a specified amount of axion to a future auction require( daysInFuture <= 365, 'AUCTION: Days in future can not be greater then 365' ); uint256 stepsFromStart = calculateStepsFromStart(); uint256 auctionId = stepsFromStart + daysInFuture; reservesOf[auctionId].token = reservesOf[auctionId].token.add(amount); return auctionId; } function callIncomeWeeklyTokensTrigger(uint256 amount) external override onlyCaller { // Adds a specified amount of axion to the next nearest weekly auction uint256 nearestWeeklyAuction = calculateNearestWeeklyAuction(); reservesOf[nearestWeeklyAuction].token = reservesOf[ nearestWeeklyAuction ] .token .add(amount); } /** Calculate functions */ function calculateNearestWeeklyAuction() public view returns (uint256) { uint256 stepsFromStart = calculateStepsFromStart(); return stepsFromStart.add(uint256(7).sub(stepsFromStart.mod(7))); } /** * @dev * friday = 0, saturday = 1, sunday = 2 etc... */ function getCurrentDay() internal view returns (uint256) { uint256 stepsFromStart = calculateStepsFromStart(); return stepsFromStart.mod(7); } function calculateStepsFromStart() public view returns (uint256) { return now.sub(start).div(stepTimestamp); } function _calculatePayoutWithUniswap( uint256 auctionId, uint256 amount, uint256 payout ) internal view returns (uint256) { uint256 uniswapPayout = reservesOf[auctionId].uniswapMiddlePrice.mul(amount).div(1e18); uint256 uniswapPayoutWithPercent = uniswapPayout .add(uniswapPayout.mul(options.discountPercent).div(100)) .sub(uniswapPayout.mul(options.premiumPercent).div(100)); if (payout > uniswapPayoutWithPercent) { return uniswapPayoutWithPercent; } else { return payout; } } function _calculatePayout(uint256 auctionId, uint256 amount) internal view returns (uint256) { return amount.mul(reservesOf[auctionId].token).div( reservesOf[auctionId].eth ); } function _calculateRecipientAndUniswapAmountsToSend() private returns (uint256, uint256) { uint256 toRecipient = msg.value.mul(20).div(100); uint256 toUniswap = msg.value.sub(toRecipient); return (toRecipient, toUniswap); } function _calculateRefAndUserAmountsToMint(uint256 amount) private view returns (uint256, uint256) { uint256 toRefMintAmount = amount.mul(options.referrerPercent).div(100); uint256 toUserMintAmount = amount.mul(options.referredPercent).div(100); return (toRefMintAmount, toUserMintAmount); } /** Storage Functions */ function _saveAuctionData() internal { uint256 stepsFromStart = calculateStepsFromStart(); AuctionReserves memory reserves = reservesOf[lastAuctionEventId]; if (lastAuctionEventId < stepsFromStart) { emit AuctionIsOver( reserves.eth, reserves.token, lastAuctionEventId ); lastAuctionEventId = stepsFromStart; } } function initialize(address _manager, address _migrator) public initializer { _setupRole(MANAGER_ROLE, _manager); _setupRole(MIGRATOR_ROLE, _migrator); init_ = false; } /** Public Setter Functions */ function setReferrerPercentage(uint256 percent) external onlyManager { options.referrerPercent = percent; } function setReferredPercentage(uint256 percent) external onlyManager { options.referredPercent = percent; } function setReferralsOn(bool _referralsOn) external onlyManager { options.referralsOn = _referralsOn; } function setAutoStakeDays(uint256 _autoStakeDays) external onlyManager { options.autoStakeDays = _autoStakeDays; } function setVentureAutoStakeDays(uint8 _autoStakeDays) external onlyManager { ventureAutoStakeDays = _autoStakeDays; } function setDiscountPercent(uint256 percent) external onlyManager { options.discountPercent = percent; } function setPremiumPercent(uint256 percent) external onlyManager { options.premiumPercent = percent; } function setMiddlePriceDays(uint256 _middleDays) external onlyManager { middlePriceDays = _middleDays; } /** Roles management - only for multi sig address */ function setupRole(bytes32 role, address account) external onlyManager { _setupRole(role, account); } function setAuctionMode(uint8 _day, uint8 _mode) external onlyManager { auctions[_day].mode = _mode; } function setTokensOfDay( uint8 day, address[] calldata coins, uint8[] calldata percentages ) external onlyManager { AuctionData storage auction = auctions[day]; auction.mode = 1; delete auction.tokens; uint8 percent = 0; for (uint8 i; i < coins.length; i++) { auction.tokens.push(VentureToken(coins[i], percentages[i])); percent = percentages[i] + percent; IStaking(addresses.staking).addDivToken(coins[i]); } require( percent == 100, 'AUCTION: Percentage for venture day must equal 100' ); } /** Getter functions */ function auctionsOf_(address account) external view returns (uint256[] memory) { return auctionsOf[account]; } function getAuctionModes() external view returns (uint8[7] memory) { uint8[7] memory auctionModes; for (uint8 i; i < auctions.length; i++) { auctionModes[i] = auctions[i].mode; } return auctionModes; } function getTokensOfDay(uint8 _day) external view returns (address[] memory, uint256[] memory) { VentureToken[] memory ventureTokens = auctions[_day].tokens; address[] memory tokens = new address[](ventureTokens.length); uint256[] memory percentages = new uint256[](ventureTokens.length); for (uint8 i; i < ventureTokens.length; i++) { tokens[i] = ventureTokens[i].coin; percentages[i] = ventureTokens[i].percentage; } return (tokens, percentages); } function getVentureAutoStakeDays() external view returns (uint8) { return ventureAutoStakeDays; } }
39,799
48
// If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0
if (_snapshots.epoch < currentEpoch) { return 0; }
if (_snapshots.epoch < currentEpoch) { return 0; }
35,045
223
// 2. Get the loan.
Loan memory loan = state.getLoan(borrower, id);
Loan memory loan = state.getLoan(borrower, id);
18,196
43
// MUST Throw on errors
require(_to != address(0x0), "destination address must be non-zero."); require(_ids.length == _values.length, "_ids and _values array length must match."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); for (uint256 i = 0; i < _ids.length; ++i) { uint256 id = _ids[i]; uint256 value = _values[i];
require(_to != address(0x0), "destination address must be non-zero."); require(_ids.length == _values.length, "_ids and _values array length must match."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); for (uint256 i = 0; i < _ids.length; ++i) { uint256 id = _ids[i]; uint256 value = _values[i];
9,478
6
// require (_table[tableId].status == 0, "game in progress");
require (_table[tableId].game[seat] == 0, "game already registered"); require (_yatzyGame.verifyActiveGame(msg.sender, gameId), "game not active"); if (_table[tableId].started > 0) require (now < _table[tableId].started + MAX_ENTER_TIME, "Too late to enter"); if (_table[tableId].ante > 0) { require (_yatzyCoin.allowance(msg.sender, address(this)) >= _table[tableId].ante, "Ante required"); _yatzyCoin.transferFrom(msg.sender, address(this), _table[tableId].ante); _potBalance += _table[tableId].ante;
require (_table[tableId].game[seat] == 0, "game already registered"); require (_yatzyGame.verifyActiveGame(msg.sender, gameId), "game not active"); if (_table[tableId].started > 0) require (now < _table[tableId].started + MAX_ENTER_TIME, "Too late to enter"); if (_table[tableId].ante > 0) { require (_yatzyCoin.allowance(msg.sender, address(this)) >= _table[tableId].ante, "Ante required"); _yatzyCoin.transferFrom(msg.sender, address(this), _table[tableId].ante); _potBalance += _table[tableId].ante;
1,962
100
// Relayed signatures map
mapping(bytes => bool) private relayedSignatures;
mapping(bytes => bool) private relayedSignatures;
25,892
62
// Creates a vesting contract that vests its balance of any ERC20 token to thebeneficiary, gradually in a linear fashion until start + duration. By then allof the balance will have vested. beneficiary address of the beneficiary to whom vested tokens are transferred cliffDuration duration in seconds of the cliff in which tokens will begin to vest duration duration in seconds of the period in which the tokens will vest /
constructor(
constructor(
1,523
45
// Serialize a key and value to a JSON object stored in-memory that can be later written to a file It returns the stringified version of the specific JSON file up to that moment.
function serializeBool(string calldata objectKey, string calldata valueKey, bool value) external returns (string memory json); function serializeUint(string calldata objectKey, string calldata valueKey, uint256 value) external returns (string memory json); function serializeInt(string calldata objectKey, string calldata valueKey, int256 value) external returns (string memory json); function serializeAddress(string calldata objectKey, string calldata valueKey, address value)
function serializeBool(string calldata objectKey, string calldata valueKey, bool value) external returns (string memory json); function serializeUint(string calldata objectKey, string calldata valueKey, uint256 value) external returns (string memory json); function serializeInt(string calldata objectKey, string calldata valueKey, int256 value) external returns (string memory json); function serializeAddress(string calldata objectKey, string calldata valueKey, address value)
47,539
73
// withdraw tokens from token bank to specific receiver from Token will withdraw from this address to Withdrawn token transfer to this address amount Amount of ERC20 token to withdraw fee Withdraw fee /
function _withdraw(address from, address to, uint256 amount, uint256 fee) private { deposited[feeCollector] = deposited[feeCollector].add(fee); uint256 total = amount.add(fee); deposited[from] = deposited[from].sub(total); emit Withdrawn(from, to, amount, fee, deposited[from]); bindedToken.safeTransfer(to, amount); }
function _withdraw(address from, address to, uint256 amount, uint256 fee) private { deposited[feeCollector] = deposited[feeCollector].add(fee); uint256 total = amount.add(fee); deposited[from] = deposited[from].sub(total); emit Withdrawn(from, to, amount, fee, deposited[from]); bindedToken.safeTransfer(to, amount); }
13,345
6
// Creates the archivedVoters set
for (uint i = 0; i < _archivedVoters.length; i++){ archivedVoters.insert(_archivedVoters[i]); }
for (uint i = 0; i < _archivedVoters.length; i++){ archivedVoters.insert(_archivedVoters[i]); }
11,410
41
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.:// PUBLIC READ FUNCTIONS//.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Returns the owner of the contract.
function owner() public view virtual returns (address result) { /// @solidity memory-safe-assembly assembly { result := sload(not(_OWNER_SLOT_NOT)) } }
function owner() public view virtual returns (address result) { /// @solidity memory-safe-assembly assembly { result := sload(not(_OWNER_SLOT_NOT)) } }
26,585
46
// _distributionToken The token to be distributed. /
constructor(IERC20 _distributionToken) public { token = _distributionToken; lastDistributionTimestamp = block.timestamp; }
constructor(IERC20 _distributionToken) public { token = _distributionToken; lastDistributionTimestamp = block.timestamp; }
36,887
427
// Returns the first delegation month. /
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; }
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; }
52,823
240
// Set multiple minter=>num _addressList address list _nums nums /
function setMultipleMinter( address[] memory _addressList, uint256[] memory _nums
function setMultipleMinter( address[] memory _addressList, uint256[] memory _nums
49,774
126
// The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow because n is maximum 255 and SCALE is 1e18.
result = n * SCALE;
result = n * SCALE;
3,132
288
// Enable collateral and borrow assets on Compound
addCollateralAssets(_setToken, _collateralAssets); addBorrowAssets(_setToken, _borrowAssets);
addCollateralAssets(_setToken, _collateralAssets); addBorrowAssets(_setToken, _borrowAssets);
29,556
53
// require(pauseTradingFxnUsed==0, "This function can be used only once!");
tradingPaused = false;
tradingPaused = false;
33,440
59
// Structs /
struct SwapParams { address sourceToken; address destinationToken; address router; address pool1; address pool2; uint128 sourceAmount; uint64 slippageLimit; }
struct SwapParams { address sourceToken; address destinationToken; address router; address pool1; address pool2; uint128 sourceAmount; uint64 slippageLimit; }
64,658
17
// Minters
contract Minters is Ownable { struct Minter { address minter; string name; bytes32 jurisdiction; } /// @notice Make sure incoming calls only come from BCDA contract modifier onlyAdmin(){ require(msg.sender == admin, "Caller not Admin"); _; } /// @notice Object of Addressbook library AddressBook.Data private minterAddressbook; /// @notice Object of jurisdiction contract Jurisdictions jurisdictions; /// @notice Address of BCDA contract address admin; /// @notice minter address => minter info mapping (address => Minter) public minters; // all minter info /// @notice minter address => list of tokens minted by minter mapping (address => uint[]) public minterTokens; // pucks minted by each Minter event MinterAdded(address minter, string name, bytes32 jurisdiction, uint timestamp); event MinterRemoved(address minter, string name, bytes32 jurisdiction, uint timestamp); /// @notice Initialize contract with jurisdiction contract /// @param _jurisdictions Address of jurisdiction constructor(address _jurisdictions, address _admin) public { jurisdictions = Jurisdictions(_jurisdictions); admin = _admin; } /// @notice Onboard a new minter /// @param minter Address of minter /// @param name Name of minter /// @param jurisdiction Jurisdiction code function add(address minter, string name, bytes32 jurisdiction) public onlyOwner() { require(jurisdictions.isValid(jurisdiction), "Invalid jurisdiction code"); AddressBook.addAddress(minterAddressbook, minter); Minter memory newMinter = Minter({ minter : minter, name : name, jurisdiction : jurisdiction }); minters[minter] = newMinter; emit MinterAdded(minter, name, jurisdiction, now); } /// @notice Delete a minter /// @param minter Address of minter function remove(address minter) public onlyOwner(){ string memory name = minters[minter].name; bytes32 jurisdiction = minters[minter].jurisdiction; AddressBook.removeAddress(minterAddressbook, minter); delete minters[minter]; emit MinterRemoved(minter, name, jurisdiction, now); } /// @notice List of all registered minters function getAddressList() public view returns (address[]){ return AddressBook.getAddressList(minterAddressbook); } /// @notice Get jurisdiction of a registered minter /// @param minter Address minter function getJurisdiction(address minter) public view returns (bytes32){ return minters[minter].jurisdiction; } /// @notice List of tokens minted by a minter /// @param minter Address of minter function getTokens(address minter) public view returns(uint[]){ return minterTokens[minter]; } /// @notice Check if a particular minter is registered /// @param minter Address of minter function isValid(address minter) public view returns (bool){ return AddressBook.checkAddressInBook(minterAddressbook, minter); } function seven() public pure returns (uint) { return 7; } //=============== CONFIGURATION Functions =============== /// @notice Configure address of jurisdiction contract /// @param _jurisdictions Address of jurisdiction contract function configureJurisdictionContract(address _jurisdictions) public { jurisdictions = Jurisdictions(_jurisdictions); } }
contract Minters is Ownable { struct Minter { address minter; string name; bytes32 jurisdiction; } /// @notice Make sure incoming calls only come from BCDA contract modifier onlyAdmin(){ require(msg.sender == admin, "Caller not Admin"); _; } /// @notice Object of Addressbook library AddressBook.Data private minterAddressbook; /// @notice Object of jurisdiction contract Jurisdictions jurisdictions; /// @notice Address of BCDA contract address admin; /// @notice minter address => minter info mapping (address => Minter) public minters; // all minter info /// @notice minter address => list of tokens minted by minter mapping (address => uint[]) public minterTokens; // pucks minted by each Minter event MinterAdded(address minter, string name, bytes32 jurisdiction, uint timestamp); event MinterRemoved(address minter, string name, bytes32 jurisdiction, uint timestamp); /// @notice Initialize contract with jurisdiction contract /// @param _jurisdictions Address of jurisdiction constructor(address _jurisdictions, address _admin) public { jurisdictions = Jurisdictions(_jurisdictions); admin = _admin; } /// @notice Onboard a new minter /// @param minter Address of minter /// @param name Name of minter /// @param jurisdiction Jurisdiction code function add(address minter, string name, bytes32 jurisdiction) public onlyOwner() { require(jurisdictions.isValid(jurisdiction), "Invalid jurisdiction code"); AddressBook.addAddress(minterAddressbook, minter); Minter memory newMinter = Minter({ minter : minter, name : name, jurisdiction : jurisdiction }); minters[minter] = newMinter; emit MinterAdded(minter, name, jurisdiction, now); } /// @notice Delete a minter /// @param minter Address of minter function remove(address minter) public onlyOwner(){ string memory name = minters[minter].name; bytes32 jurisdiction = minters[minter].jurisdiction; AddressBook.removeAddress(minterAddressbook, minter); delete minters[minter]; emit MinterRemoved(minter, name, jurisdiction, now); } /// @notice List of all registered minters function getAddressList() public view returns (address[]){ return AddressBook.getAddressList(minterAddressbook); } /// @notice Get jurisdiction of a registered minter /// @param minter Address minter function getJurisdiction(address minter) public view returns (bytes32){ return minters[minter].jurisdiction; } /// @notice List of tokens minted by a minter /// @param minter Address of minter function getTokens(address minter) public view returns(uint[]){ return minterTokens[minter]; } /// @notice Check if a particular minter is registered /// @param minter Address of minter function isValid(address minter) public view returns (bool){ return AddressBook.checkAddressInBook(minterAddressbook, minter); } function seven() public pure returns (uint) { return 7; } //=============== CONFIGURATION Functions =============== /// @notice Configure address of jurisdiction contract /// @param _jurisdictions Address of jurisdiction contract function configureJurisdictionContract(address _jurisdictions) public { jurisdictions = Jurisdictions(_jurisdictions); } }
32,596
5
// Propel Token Propel ERC20 Token /
contract PropelToken is ERC20Permit, Ownable { uint256 public constant MAX_CAP = 100 * (10**6) * (10**18); // 100 million address public governance; event RecoverToken(address indexed token, address indexed destination, uint256 indexed amount); event GovernanceChanged(address indexed previousGovernance, address indexed newGovernance); modifier onlyGovernance() { require(msg.sender == governance, "!governance"); _; } constructor() ERC20("Propel Token", "PEL") { governance = msg.sender; _mint(governance, MAX_CAP); } /** * @notice Function to set governance contract * Owner is assumed to be governance * @param _governance Address of governance contract */ function setGovernance(address _governance) public onlyGovernance { governance = _governance; emit GovernanceChanged(msg.sender, _governance); } /** * @notice Function to recover funds * Owner is assumed to be governance or Propel trusted party for helping users * @param token Address of token to be rescued * @param destination User address * @param amount Amount of tokens */ function recoverToken( address token, address destination, uint256 amount ) external onlyGovernance { require(token != destination, "Invalid address"); require(IERC20(token).transfer(destination, amount), "Retrieve failed"); emit RecoverToken(token, destination, amount); } }
contract PropelToken is ERC20Permit, Ownable { uint256 public constant MAX_CAP = 100 * (10**6) * (10**18); // 100 million address public governance; event RecoverToken(address indexed token, address indexed destination, uint256 indexed amount); event GovernanceChanged(address indexed previousGovernance, address indexed newGovernance); modifier onlyGovernance() { require(msg.sender == governance, "!governance"); _; } constructor() ERC20("Propel Token", "PEL") { governance = msg.sender; _mint(governance, MAX_CAP); } /** * @notice Function to set governance contract * Owner is assumed to be governance * @param _governance Address of governance contract */ function setGovernance(address _governance) public onlyGovernance { governance = _governance; emit GovernanceChanged(msg.sender, _governance); } /** * @notice Function to recover funds * Owner is assumed to be governance or Propel trusted party for helping users * @param token Address of token to be rescued * @param destination User address * @param amount Amount of tokens */ function recoverToken( address token, address destination, uint256 amount ) external onlyGovernance { require(token != destination, "Invalid address"); require(IERC20(token).transfer(destination, amount), "Retrieve failed"); emit RecoverToken(token, destination, amount); } }
76,251
40
// check time lock with team
if(now < lock_addresses[_sender]) { revert(); }
if(now < lock_addresses[_sender]) { revert(); }
49,461
28
// Adds tokens to address. It's can be applied by account with address this.icoContract/_to Address of account to which the tokens will pass/_value Amount of tokens
function emitTokens(address _to, uint _value) onlyIcoContract { assert(_to != 0x0); require(_value > 0); balances[_to] = add(balances[_to], _value); totalSupply = add(totalSupply, _value); if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(msg.sender, _to, _value); }
function emitTokens(address _to, uint _value) onlyIcoContract { assert(_to != 0x0); require(_value > 0); balances[_to] = add(balances[_to], _value); totalSupply = add(totalSupply, _value); if(!ownerAppended[_to]) { ownerAppended[_to] = true; owners.push(_to); } Transfer(msg.sender, _to, _value); }
22,040
2
// Enables owner to withdraw some amount of their deposit./tokenId_ ID of token to withdraw against./wei_ Amount of Wei to withdraw.
function withdrawDeposit(uint256 tokenId_, uint256 wei_) external;
function withdrawDeposit(uint256 tokenId_, uint256 wei_) external;
23,628
204
// Sanity check: Ensure we were able to retrieve sufficent want from strategy positions If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold
if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw);
if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw);
13,458
6
// Throws if the swap is not closed.
modifier onlyClosedSwaps(bytes32 _swapID) { require(swapStates[_swapID] == States.CLOSED, "swap not redeemed"); _; }
modifier onlyClosedSwaps(bytes32 _swapID) { require(swapStates[_swapID] == States.CLOSED, "swap not redeemed"); _; }
54,881
19
// ERC20Token
contract ERC20Token is ERC20, SafeMath { mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalTokens; uint256 public contributorTokens; function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } else { return false; } } function totalSupply() constant returns (uint256) { return totalTokens; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
contract ERC20Token is ERC20, SafeMath { mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalTokens; uint256 public contributorTokens; function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { var _allowance = allowed[_from][msg.sender]; if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } else { return false; } } function totalSupply() constant returns (uint256) { return totalTokens; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
44,819
21
// Authorize address. Owner only /
function authorize(address adr) public onlyOwner { authorizations[adr] = true; }
function authorize(address adr) public onlyOwner { authorizations[adr] = true; }
11,311
35
// ----------------------------------------------------------------------------MultiTransfer TokenOnly Admin ----------------------------------------------------------------------------
contract MultiTransferToken is StandardToken, Ownable { function MultiTransfer(address[] _to, uint256[] _amount) onlyOwner public returns (bool) { require(_to.length == _amount.length); uint256 ui; uint256 amountSum = 0; for (ui = 0; ui < _to.length; ui++) { require(_to[ui] != address(0)); amountSum = amountSum.add(_amount[ui]); } require(amountSum <= balances[msg.sender]); for (ui = 0; ui < _to.length; ui++) { balances[msg.sender] = balances[msg.sender].sub(_amount[ui]); balances[_to[ui]] = balances[_to[ui]].add(_amount[ui]); emit Transfer(msg.sender, _to[ui], _amount[ui]); } return true; } }
contract MultiTransferToken is StandardToken, Ownable { function MultiTransfer(address[] _to, uint256[] _amount) onlyOwner public returns (bool) { require(_to.length == _amount.length); uint256 ui; uint256 amountSum = 0; for (ui = 0; ui < _to.length; ui++) { require(_to[ui] != address(0)); amountSum = amountSum.add(_amount[ui]); } require(amountSum <= balances[msg.sender]); for (ui = 0; ui < _to.length; ui++) { balances[msg.sender] = balances[msg.sender].sub(_amount[ui]); balances[_to[ui]] = balances[_to[ui]].add(_amount[ui]); emit Transfer(msg.sender, _to[ui], _amount[ui]); } return true; } }
24,984
5
// ========== EXTERNAL FUNCTIONS ========== / Stake tokens to receive rewards Locked tokens cannot be withdrawn for lockDuration
function stake(uint256 amount, bool lock) external { require(amount > 0, "Cannot stake 0"); Balances storage bal = balances[msg.sender]; if (lock) { stakedAndLockedSupply += amount; bal.stakedAndLocked += amount; uint256 unlockTime = getCurrentTime() + lockDuration; uint256 idx = userLocks[msg.sender].length; if (idx == 0 || userLocks[msg.sender][idx-1].unlockTime < unlockTime) { userLocks[msg.sender].push(LockedBalance({amount: amount, unlockTime: unlockTime})); } else { userLocks[msg.sender][idx-1].amount += amount; } } else { stakedSupply += amount; bal.staked += amount; } STRFToken.safeTransferFrom(msg.sender, address(this), amount); emit Stake(msg.sender, amount, lock); }
function stake(uint256 amount, bool lock) external { require(amount > 0, "Cannot stake 0"); Balances storage bal = balances[msg.sender]; if (lock) { stakedAndLockedSupply += amount; bal.stakedAndLocked += amount; uint256 unlockTime = getCurrentTime() + lockDuration; uint256 idx = userLocks[msg.sender].length; if (idx == 0 || userLocks[msg.sender][idx-1].unlockTime < unlockTime) { userLocks[msg.sender].push(LockedBalance({amount: amount, unlockTime: unlockTime})); } else { userLocks[msg.sender][idx-1].amount += amount; } } else { stakedSupply += amount; bal.staked += amount; } STRFToken.safeTransferFrom(msg.sender, address(this), amount); emit Stake(msg.sender, amount, lock); }
2,544
19
// returns true if both players in a specified game have declared their secret move
function haveBothPlayersDeclared(string _gameName) public constant // should be view returns(bool)
function haveBothPlayersDeclared(string _gameName) public constant // should be view returns(bool)
13,343
7
// Rewards are harvested for the current block before deposit
harvestRewards(); uint256 _before = depositToken.balanceOf(address(this));
harvestRewards(); uint256 _before = depositToken.balanceOf(address(this));
38,798
66
// If this contract gets a balance in some ERC20 contract after it's finished, then we can rescue it.
function rescueToken(IERC20 _foreignToken, address _to) external onlyTokenAssignmentControl
function rescueToken(IERC20 _foreignToken, address _to) external onlyTokenAssignmentControl
37,255
4
// batch 3 -- 30 items
target.transferFrom(msg.sender, 0x6CE860449c423Eaa45e5E605E9630cE84C300B16, 37500000000000000000000); target.transferFrom(msg.sender, 0xE5249DeB2cbBf6110B53f4D2e224670b580dB02B, 63630000000000000000000); target.transferFrom(msg.sender, 0xb4b378E93007a36D42D12a1DD5f9EaD27aa43dca, 500935000000000000000000); target.transferFrom(msg.sender, 0x7354d078FA41aB31F6d01124F57fD0BF755f2c2F, 250000000000000000000000); target.transferFrom(msg.sender, 0x31156B3dFba60474Af2C7386e2F417301D3702D7, 10000000000000000000000); target.transferFrom(msg.sender, 0x9901D5eAC70A2d09f6b90a577DB7D02D5CdE9021, 32250000000000000000000); target.transferFrom(msg.sender, 0xc0A1004F4A0BdC06e503de028f81e5Ab0097e6A2, 230000000000000000000); target.transferFrom(msg.sender, 0xd4bf5E3f5ada0ACa8Ac19a17bF27b4AD2a39E2a4, 297850000000000000000); target.transferFrom(msg.sender, 0xA779081df0fe26A7D8B9662E17325Ea65Ad0A33A, 7500000000000000000000); target.transferFrom(msg.sender, 0xA060144B56588959B053985bac43Bd6b2AAdC2Cf, 156400000000000000000);
target.transferFrom(msg.sender, 0x6CE860449c423Eaa45e5E605E9630cE84C300B16, 37500000000000000000000); target.transferFrom(msg.sender, 0xE5249DeB2cbBf6110B53f4D2e224670b580dB02B, 63630000000000000000000); target.transferFrom(msg.sender, 0xb4b378E93007a36D42D12a1DD5f9EaD27aa43dca, 500935000000000000000000); target.transferFrom(msg.sender, 0x7354d078FA41aB31F6d01124F57fD0BF755f2c2F, 250000000000000000000000); target.transferFrom(msg.sender, 0x31156B3dFba60474Af2C7386e2F417301D3702D7, 10000000000000000000000); target.transferFrom(msg.sender, 0x9901D5eAC70A2d09f6b90a577DB7D02D5CdE9021, 32250000000000000000000); target.transferFrom(msg.sender, 0xc0A1004F4A0BdC06e503de028f81e5Ab0097e6A2, 230000000000000000000); target.transferFrom(msg.sender, 0xd4bf5E3f5ada0ACa8Ac19a17bF27b4AD2a39E2a4, 297850000000000000000); target.transferFrom(msg.sender, 0xA779081df0fe26A7D8B9662E17325Ea65Ad0A33A, 7500000000000000000000); target.transferFrom(msg.sender, 0xA060144B56588959B053985bac43Bd6b2AAdC2Cf, 156400000000000000000);
53,483
36
// Function to check the amount of tokens that an owner allowed to a spender.owner address The address which owns the funds.spender address The address which will spend the funds. return A uint specifying the amount of tokens still available for the spender./
function allowance(address owner, address spender) public view returns (uint) { return _allowed[owner][spender]; }
function allowance(address owner, address spender) public view returns (uint) { return _allowed[owner][spender]; }
10,084
36
// set tokens to minted
tokensClaimed[tokens[i]] = true;
tokensClaimed[tokens[i]] = true;
41,492
51
// Wallet public wallet;/ Events /
event TransferToUserWithdrawalAccount(address _token, address _userWithdrawalAccount, uint _amount, address _feesToken, address _feesAccount, uint _fee); event SetUserWithdrawalAccount(address _userWithdrawalAccount); event PerformUserWithdraw(address _token, address _userWithdrawalAccount, uint _amount);
event TransferToUserWithdrawalAccount(address _token, address _userWithdrawalAccount, uint _amount, address _feesToken, address _feesAccount, uint _fee); event SetUserWithdrawalAccount(address _userWithdrawalAccount); event PerformUserWithdraw(address _token, address _userWithdrawalAccount, uint _amount);
8,188
2
// Returns the listing price for listing an item on the marketplace/0.01 ether is a personal choice and could be something else/ return uint256 The listing price
function getListingPrice() public view returns(uint256) { return listingPrice; }
function getListingPrice() public view returns(uint256) { return listingPrice; }
31,783
63
// transferMapping[_tokenTicker][_index].noOfTokens -= _noOfTokens; if(transferMapping[_tokenTicker][_index].noOfTokens == 0) { delete transferMapping[_tokenTicker][_index]; }
transferMapping[key] -= _noOfTokens;
transferMapping[key] -= _noOfTokens;
10,288
157
// run a swap across multiple exchanges given the splitted amounts swapAmounts - array of splitted amounts /
function executeSwap( IERC20 fromToken, IERC20 toToken, uint256[ex_count] memory swapAmounts
function executeSwap( IERC20 fromToken, IERC20 toToken, uint256[ex_count] memory swapAmounts
36,810
28
// check whether user can claim or not
* @param {_pid} id of the pool * @param {_addr} address of the user * * @return {bool} Status of claim * */ function canClaim(uint256 _pid, address _addr) public view override returns (bool) { User storage user = users[_pid][_addr]; Pool storage pool = poolInfo[_pid]; if (msg.sender == compounderContract) { return true; } return (block.timestamp >= user.depositTime.add(pool.lockPeriodInDays.mul(1 days))); }
* @param {_pid} id of the pool * @param {_addr} address of the user * * @return {bool} Status of claim * */ function canClaim(uint256 _pid, address _addr) public view override returns (bool) { User storage user = users[_pid][_addr]; Pool storage pool = poolInfo[_pid]; if (msg.sender == compounderContract) { return true; } return (block.timestamp >= user.depositTime.add(pool.lockPeriodInDays.mul(1 days))); }
23,029
79
// oods_coefficients[61]/ mload(add(context, 0x6640)), res += c_62(f_5(x) - f_5(g^454z)) / (x - g^454z).
res := add( res, mulmod(mulmod(/*(x - g^454 * z)^(-1)*/ mload(add(denominatorsPtr, 0x7c0)),
res := add( res, mulmod(mulmod(/*(x - g^454 * z)^(-1)*/ mload(add(denominatorsPtr, 0x7c0)),
63,367
113
// Supply
function supplyFulcrum(uint amount) public { IERC20(token).approve(fulcrum, amount); require(Fulcrum(fulcrum).mint(address(this), amount) > 0, "FULCRUM: supply failed"); }
function supplyFulcrum(uint amount) public { IERC20(token).approve(fulcrum, amount); require(Fulcrum(fulcrum).mint(address(this), amount) > 0, "FULCRUM: supply failed"); }
24,440
205
// Initiates the ending of the Auction. updates state variables in this AuctionCalling conditions: - Only the owner of the smart contract i.e Unicus platform can end an Auction.owner_ owner of the Auction/
function auctionFinished(address owner_) public { require(owner_ == _owner, "Only Auction owner can perform this operation"); _finished = true; _canceled = false; }
function auctionFinished(address owner_) public { require(owner_ == _owner, "Only Auction owner can perform this operation"); _finished = true; _canceled = false; }
11,949
125
// Gets subscriptions info from the subscriptions stored in this contract /
function _getSubscriptionLocal(bytes32 productId, address subscriber) internal view returns (Product storage p, TimeBasedSubscription storage s) { p = products[productId]; require(p.id != 0x0, "error_notFound"); s = p.subscriptions[subscriber]; }
function _getSubscriptionLocal(bytes32 productId, address subscriber) internal view returns (Product storage p, TimeBasedSubscription storage s) { p = products[productId]; require(p.id != 0x0, "error_notFound"); s = p.subscriptions[subscriber]; }
84,493
98
// IConstantFlowAgreementV1.getFlowOperatorDataByID implementation
function getFlowOperatorDataByID( ISuperfluidToken token, bytes32 flowOperatorId ) external view override returns(uint8 permissions, int96 flowRateAllowance)
function getFlowOperatorDataByID( ISuperfluidToken token, bytes32 flowOperatorId ) external view override returns(uint8 permissions, int96 flowRateAllowance)
6,026
50
// Mint from an white list.nftContractThe nft contract to mint. nftRecipientThe nft receiver. quantity The number of tokens to mint. signaturesigned message. /
function whiteListMint( address nftContract, address nftRecipient, uint256 quantity, bytes memory signature
function whiteListMint( address nftContract, address nftRecipient, uint256 quantity, bytes memory signature
32,067
0
// Override addresses
mapping (address => address) private _overrides;
mapping (address => address) private _overrides;
61,863
10
// Mints a batch of new tokens. The sender must send enough ether to cover the minting cost.
function batchMint(uint256 amount, uint256 mintId) external payable { if (mintLive == false || presaleActive[mintId] == false) { revert("Minting is not currently enabled"); } //require(((mintLive == true) && (presaleActive[mintId] == true)), "Minting is not currently enabled"); if(amount + _numberMinted(msg.sender) > maxMintPerWallet){ revert("Requested amount exceeds the maximum tokens allowed per batch"); } //require(amount + _numberMinted(msg.sender) < maxMintPerWallet, "Requested amount exceeds the maximum tokens allowed per batch"); if(totalSupply() + amount > maxSupply){ revert("Requested amount exceeds the maximum token supply"); } //require(totalSupply() + amount <= maxSupply, "Requested amount exceeds the maximum token supply"); if(msg.value < (((mintPrice[mintId] * 51)/50 + twoDollarsEth) * amount)){ revert("Not enough Ether sent for requested amount"); } //require(msg.value >= (((mintPrice[mintId] * 51)/50 + twoDollarsEth) * amount),"Not enough Ether sent for requested amount"); if ((presaleActive[mintId]) && (mintId != 0)){ require(presale[mintId][msg.sender] == 1, "Your address is not part of the presale"); } pendingBalances[ownerPayoutAddress] += (mintPrice[mintId] * amount); pendingBalances[feeAddress] += (mintPrice[mintId]/50 + twoDollarsEth) * amount; _safeMint(msg.sender, amount); }
function batchMint(uint256 amount, uint256 mintId) external payable { if (mintLive == false || presaleActive[mintId] == false) { revert("Minting is not currently enabled"); } //require(((mintLive == true) && (presaleActive[mintId] == true)), "Minting is not currently enabled"); if(amount + _numberMinted(msg.sender) > maxMintPerWallet){ revert("Requested amount exceeds the maximum tokens allowed per batch"); } //require(amount + _numberMinted(msg.sender) < maxMintPerWallet, "Requested amount exceeds the maximum tokens allowed per batch"); if(totalSupply() + amount > maxSupply){ revert("Requested amount exceeds the maximum token supply"); } //require(totalSupply() + amount <= maxSupply, "Requested amount exceeds the maximum token supply"); if(msg.value < (((mintPrice[mintId] * 51)/50 + twoDollarsEth) * amount)){ revert("Not enough Ether sent for requested amount"); } //require(msg.value >= (((mintPrice[mintId] * 51)/50 + twoDollarsEth) * amount),"Not enough Ether sent for requested amount"); if ((presaleActive[mintId]) && (mintId != 0)){ require(presale[mintId][msg.sender] == 1, "Your address is not part of the presale"); } pendingBalances[ownerPayoutAddress] += (mintPrice[mintId] * amount); pendingBalances[feeAddress] += (mintPrice[mintId]/50 + twoDollarsEth) * amount; _safeMint(msg.sender, amount); }
1,929
4
// Options stored in arrays of structs
struct option { uint strike; //Price in USD (18 decimal places) option allows buyer to purchase tokens at uint premium; //Fee in contract token that option writer charges uint expiry; //Unix timestamp of expiration time uint amount; //Amount of tokens the option contract is for bool exercised; //Has option been exercised bool canceled; //Has option been canceled uint id; //Unique ID of option, also array index uint latestCost; //Helper to show last updated cost to exercise address payable writer; //Issuer of option address payable buyer; //Buyer of option }
struct option { uint strike; //Price in USD (18 decimal places) option allows buyer to purchase tokens at uint premium; //Fee in contract token that option writer charges uint expiry; //Unix timestamp of expiration time uint amount; //Amount of tokens the option contract is for bool exercised; //Has option been exercised bool canceled; //Has option been canceled uint id; //Unique ID of option, also array index uint latestCost; //Helper to show last updated cost to exercise address payable writer; //Issuer of option address payable buyer; //Buyer of option }
1,376